Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Universal Flash Storage Host controller driver Core
4 * Copyright (C) 2011-2013 Samsung India Software Operations
5 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
6 *
7 * Authors:
8 * Santosh Yaraganavi <santosh.sy@samsung.com>
9 * Vinayak Holikatti <h.vinayak@samsung.com>
10 */
11
12#include <linux/async.h>
13#include <linux/devfreq.h>
14#include <linux/nls.h>
15#include <linux/of.h>
16#include <linux/bitfield.h>
17#include <linux/blk-pm.h>
18#include <linux/blkdev.h>
19#include <linux/clk.h>
20#include <linux/delay.h>
21#include <linux/interrupt.h>
22#include <linux/module.h>
23#include <linux/regulator/consumer.h>
24#include <linux/sched/clock.h>
25#include <scsi/scsi_cmnd.h>
26#include <scsi/scsi_dbg.h>
27#include <scsi/scsi_driver.h>
28#include <scsi/scsi_eh.h>
29#include "ufshcd-priv.h"
30#include <ufs/ufs_quirks.h>
31#include <ufs/unipro.h>
32#include "ufs-sysfs.h"
33#include "ufs-debugfs.h"
34#include "ufs-fault-injection.h"
35#include "ufs_bsg.h"
36#include "ufshcd-crypto.h"
37#include "ufshpb.h"
38#include <asm/unaligned.h>
39
40#define CREATE_TRACE_POINTS
41#include <trace/events/ufs.h>
42
43#define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
44 UTP_TASK_REQ_COMPL |\
45 UFSHCD_ERROR_MASK)
46/* UIC command timeout, unit: ms */
47#define UIC_CMD_TIMEOUT 500
48
49/* NOP OUT retries waiting for NOP IN response */
50#define NOP_OUT_RETRIES 10
51/* Timeout after 50 msecs if NOP OUT hangs without response */
52#define NOP_OUT_TIMEOUT 50 /* msecs */
53
54/* Query request retries */
55#define QUERY_REQ_RETRIES 3
56/* Query request timeout */
57#define QUERY_REQ_TIMEOUT 1500 /* 1.5 seconds */
58
59/* Task management command timeout */
60#define TM_CMD_TIMEOUT 100 /* msecs */
61
62/* maximum number of retries for a general UIC command */
63#define UFS_UIC_COMMAND_RETRIES 3
64
65/* maximum number of link-startup retries */
66#define DME_LINKSTARTUP_RETRIES 3
67
68/* maximum number of reset retries before giving up */
69#define MAX_HOST_RESET_RETRIES 5
70
71/* Maximum number of error handler retries before giving up */
72#define MAX_ERR_HANDLER_RETRIES 5
73
74/* Expose the flag value from utp_upiu_query.value */
75#define MASK_QUERY_UPIU_FLAG_LOC 0xFF
76
77/* Interrupt aggregation default timeout, unit: 40us */
78#define INT_AGGR_DEF_TO 0x02
79
80/* default delay of autosuspend: 2000 ms */
81#define RPM_AUTOSUSPEND_DELAY_MS 2000
82
83/* Default delay of RPM device flush delayed work */
84#define RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS 5000
85
86/* Default value of wait time before gating device ref clock */
87#define UFSHCD_REF_CLK_GATING_WAIT_US 0xFF /* microsecs */
88
89/* Polling time to wait for fDeviceInit */
90#define FDEVICEINIT_COMPL_TIMEOUT 1500 /* millisecs */
91
92#define ufshcd_toggle_vreg(_dev, _vreg, _on) \
93 ({ \
94 int _ret; \
95 if (_on) \
96 _ret = ufshcd_enable_vreg(_dev, _vreg); \
97 else \
98 _ret = ufshcd_disable_vreg(_dev, _vreg); \
99 _ret; \
100 })
101
102#define ufshcd_hex_dump(prefix_str, buf, len) do { \
103 size_t __len = (len); \
104 print_hex_dump(KERN_ERR, prefix_str, \
105 __len > 4 ? DUMP_PREFIX_OFFSET : DUMP_PREFIX_NONE,\
106 16, 4, buf, __len, false); \
107} while (0)
108
109int ufshcd_dump_regs(struct ufs_hba *hba, size_t offset, size_t len,
110 const char *prefix)
111{
112 u32 *regs;
113 size_t pos;
114
115 if (offset % 4 != 0 || len % 4 != 0) /* keep readl happy */
116 return -EINVAL;
117
118 regs = kzalloc(len, GFP_ATOMIC);
119 if (!regs)
120 return -ENOMEM;
121
122 for (pos = 0; pos < len; pos += 4) {
123 if (offset == 0 &&
124 pos >= REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER &&
125 pos <= REG_UIC_ERROR_CODE_DME)
126 continue;
127 regs[pos / 4] = ufshcd_readl(hba, offset + pos);
128 }
129
130 ufshcd_hex_dump(prefix, regs, len);
131 kfree(regs);
132
133 return 0;
134}
135EXPORT_SYMBOL_GPL(ufshcd_dump_regs);
136
137enum {
138 UFSHCD_MAX_CHANNEL = 0,
139 UFSHCD_MAX_ID = 1,
140 UFSHCD_NUM_RESERVED = 1,
141 UFSHCD_CMD_PER_LUN = 32 - UFSHCD_NUM_RESERVED,
142 UFSHCD_CAN_QUEUE = 32 - UFSHCD_NUM_RESERVED,
143};
144
145static const char *const ufshcd_state_name[] = {
146 [UFSHCD_STATE_RESET] = "reset",
147 [UFSHCD_STATE_OPERATIONAL] = "operational",
148 [UFSHCD_STATE_ERROR] = "error",
149 [UFSHCD_STATE_EH_SCHEDULED_FATAL] = "eh_fatal",
150 [UFSHCD_STATE_EH_SCHEDULED_NON_FATAL] = "eh_non_fatal",
151};
152
153/* UFSHCD error handling flags */
154enum {
155 UFSHCD_EH_IN_PROGRESS = (1 << 0),
156};
157
158/* UFSHCD UIC layer error flags */
159enum {
160 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
161 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
162 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
163 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
164 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
165 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
166 UFSHCD_UIC_PA_GENERIC_ERROR = (1 << 6), /* Generic PA error */
167};
168
169#define ufshcd_set_eh_in_progress(h) \
170 ((h)->eh_flags |= UFSHCD_EH_IN_PROGRESS)
171#define ufshcd_eh_in_progress(h) \
172 ((h)->eh_flags & UFSHCD_EH_IN_PROGRESS)
173#define ufshcd_clear_eh_in_progress(h) \
174 ((h)->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
175
176const struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
177 [UFS_PM_LVL_0] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
178 [UFS_PM_LVL_1] = {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
179 [UFS_PM_LVL_2] = {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
180 [UFS_PM_LVL_3] = {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
181 [UFS_PM_LVL_4] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
182 [UFS_PM_LVL_5] = {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
183 /*
184 * For DeepSleep, the link is first put in hibern8 and then off.
185 * Leaving the link in hibern8 is not supported.
186 */
187 [UFS_PM_LVL_6] = {UFS_DEEPSLEEP_PWR_MODE, UIC_LINK_OFF_STATE},
188};
189
190static inline enum ufs_dev_pwr_mode
191ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
192{
193 return ufs_pm_lvl_states[lvl].dev_state;
194}
195
196static inline enum uic_link_state
197ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
198{
199 return ufs_pm_lvl_states[lvl].link_state;
200}
201
202static inline enum ufs_pm_level
203ufs_get_desired_pm_lvl_for_dev_link_state(enum ufs_dev_pwr_mode dev_state,
204 enum uic_link_state link_state)
205{
206 enum ufs_pm_level lvl;
207
208 for (lvl = UFS_PM_LVL_0; lvl < UFS_PM_LVL_MAX; lvl++) {
209 if ((ufs_pm_lvl_states[lvl].dev_state == dev_state) &&
210 (ufs_pm_lvl_states[lvl].link_state == link_state))
211 return lvl;
212 }
213
214 /* if no match found, return the level 0 */
215 return UFS_PM_LVL_0;
216}
217
218static const struct ufs_dev_quirk ufs_fixups[] = {
219 /* UFS cards deviations table */
220 { .wmanufacturerid = UFS_VENDOR_MICRON,
221 .model = UFS_ANY_MODEL,
222 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
223 UFS_DEVICE_QUIRK_SWAP_L2P_ENTRY_FOR_HPB_READ },
224 { .wmanufacturerid = UFS_VENDOR_SAMSUNG,
225 .model = UFS_ANY_MODEL,
226 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM |
227 UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE |
228 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS },
229 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
230 .model = UFS_ANY_MODEL,
231 .quirk = UFS_DEVICE_QUIRK_HOST_PA_SAVECONFIGTIME },
232 { .wmanufacturerid = UFS_VENDOR_SKHYNIX,
233 .model = "hB8aL1" /*H28U62301AMR*/,
234 .quirk = UFS_DEVICE_QUIRK_HOST_VS_DEBUGSAVECONFIGTIME },
235 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
236 .model = UFS_ANY_MODEL,
237 .quirk = UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM },
238 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
239 .model = "THGLF2G9C8KBADG",
240 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
241 { .wmanufacturerid = UFS_VENDOR_TOSHIBA,
242 .model = "THGLF2G9D8KBADG",
243 .quirk = UFS_DEVICE_QUIRK_PA_TACTIVATE },
244 {}
245};
246
247static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba);
248static void ufshcd_async_scan(void *data, async_cookie_t cookie);
249static int ufshcd_reset_and_restore(struct ufs_hba *hba);
250static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd);
251static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
252static void ufshcd_hba_exit(struct ufs_hba *hba);
253static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params);
254static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
255static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
256static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
257static void ufshcd_resume_clkscaling(struct ufs_hba *hba);
258static void ufshcd_suspend_clkscaling(struct ufs_hba *hba);
259static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba);
260static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up);
261static irqreturn_t ufshcd_intr(int irq, void *__hba);
262static int ufshcd_change_power_mode(struct ufs_hba *hba,
263 struct ufs_pa_layer_attr *pwr_mode);
264static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on);
265static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on);
266static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
267 struct ufs_vreg *vreg);
268static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag);
269static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
270 bool enable);
271static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba);
272static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba);
273
274static inline void ufshcd_enable_irq(struct ufs_hba *hba)
275{
276 if (!hba->is_irq_enabled) {
277 enable_irq(hba->irq);
278 hba->is_irq_enabled = true;
279 }
280}
281
282static inline void ufshcd_disable_irq(struct ufs_hba *hba)
283{
284 if (hba->is_irq_enabled) {
285 disable_irq(hba->irq);
286 hba->is_irq_enabled = false;
287 }
288}
289
290static void ufshcd_configure_wb(struct ufs_hba *hba)
291{
292 if (!ufshcd_is_wb_allowed(hba))
293 return;
294
295 ufshcd_wb_toggle(hba, true);
296
297 ufshcd_wb_toggle_buf_flush_during_h8(hba, true);
298
299 if (ufshcd_is_wb_buf_flush_allowed(hba))
300 ufshcd_wb_toggle_buf_flush(hba, true);
301}
302
303static void ufshcd_scsi_unblock_requests(struct ufs_hba *hba)
304{
305 if (atomic_dec_and_test(&hba->scsi_block_reqs_cnt))
306 scsi_unblock_requests(hba->host);
307}
308
309static void ufshcd_scsi_block_requests(struct ufs_hba *hba)
310{
311 if (atomic_inc_return(&hba->scsi_block_reqs_cnt) == 1)
312 scsi_block_requests(hba->host);
313}
314
315static void ufshcd_add_cmd_upiu_trace(struct ufs_hba *hba, unsigned int tag,
316 enum ufs_trace_str_t str_t)
317{
318 struct utp_upiu_req *rq = hba->lrb[tag].ucd_req_ptr;
319 struct utp_upiu_header *header;
320
321 if (!trace_ufshcd_upiu_enabled())
322 return;
323
324 if (str_t == UFS_CMD_SEND)
325 header = &rq->header;
326 else
327 header = &hba->lrb[tag].ucd_rsp_ptr->header;
328
329 trace_ufshcd_upiu(dev_name(hba->dev), str_t, header, &rq->sc.cdb,
330 UFS_TSF_CDB);
331}
332
333static void ufshcd_add_query_upiu_trace(struct ufs_hba *hba,
334 enum ufs_trace_str_t str_t,
335 struct utp_upiu_req *rq_rsp)
336{
337 if (!trace_ufshcd_upiu_enabled())
338 return;
339
340 trace_ufshcd_upiu(dev_name(hba->dev), str_t, &rq_rsp->header,
341 &rq_rsp->qr, UFS_TSF_OSF);
342}
343
344static void ufshcd_add_tm_upiu_trace(struct ufs_hba *hba, unsigned int tag,
345 enum ufs_trace_str_t str_t)
346{
347 struct utp_task_req_desc *descp = &hba->utmrdl_base_addr[tag];
348
349 if (!trace_ufshcd_upiu_enabled())
350 return;
351
352 if (str_t == UFS_TM_SEND)
353 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
354 &descp->upiu_req.req_header,
355 &descp->upiu_req.input_param1,
356 UFS_TSF_TM_INPUT);
357 else
358 trace_ufshcd_upiu(dev_name(hba->dev), str_t,
359 &descp->upiu_rsp.rsp_header,
360 &descp->upiu_rsp.output_param1,
361 UFS_TSF_TM_OUTPUT);
362}
363
364static void ufshcd_add_uic_command_trace(struct ufs_hba *hba,
365 const struct uic_command *ucmd,
366 enum ufs_trace_str_t str_t)
367{
368 u32 cmd;
369
370 if (!trace_ufshcd_uic_command_enabled())
371 return;
372
373 if (str_t == UFS_CMD_SEND)
374 cmd = ucmd->command;
375 else
376 cmd = ufshcd_readl(hba, REG_UIC_COMMAND);
377
378 trace_ufshcd_uic_command(dev_name(hba->dev), str_t, cmd,
379 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_1),
380 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2),
381 ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3));
382}
383
384static void ufshcd_add_command_trace(struct ufs_hba *hba, unsigned int tag,
385 enum ufs_trace_str_t str_t)
386{
387 u64 lba = 0;
388 u8 opcode = 0, group_id = 0;
389 u32 intr, doorbell;
390 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
391 struct scsi_cmnd *cmd = lrbp->cmd;
392 struct request *rq = scsi_cmd_to_rq(cmd);
393 int transfer_len = -1;
394
395 if (!cmd)
396 return;
397
398 /* trace UPIU also */
399 ufshcd_add_cmd_upiu_trace(hba, tag, str_t);
400 if (!trace_ufshcd_command_enabled())
401 return;
402
403 opcode = cmd->cmnd[0];
404
405 if (opcode == READ_10 || opcode == WRITE_10) {
406 /*
407 * Currently we only fully trace read(10) and write(10) commands
408 */
409 transfer_len =
410 be32_to_cpu(lrbp->ucd_req_ptr->sc.exp_data_transfer_len);
411 lba = scsi_get_lba(cmd);
412 if (opcode == WRITE_10)
413 group_id = lrbp->cmd->cmnd[6];
414 } else if (opcode == UNMAP) {
415 /*
416 * The number of Bytes to be unmapped beginning with the lba.
417 */
418 transfer_len = blk_rq_bytes(rq);
419 lba = scsi_get_lba(cmd);
420 }
421
422 intr = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
423 doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
424 trace_ufshcd_command(dev_name(hba->dev), str_t, tag,
425 doorbell, transfer_len, intr, lba, opcode, group_id);
426}
427
428static void ufshcd_print_clk_freqs(struct ufs_hba *hba)
429{
430 struct ufs_clk_info *clki;
431 struct list_head *head = &hba->clk_list_head;
432
433 if (list_empty(head))
434 return;
435
436 list_for_each_entry(clki, head, list) {
437 if (!IS_ERR_OR_NULL(clki->clk) && clki->min_freq &&
438 clki->max_freq)
439 dev_err(hba->dev, "clk: %s, rate: %u\n",
440 clki->name, clki->curr_freq);
441 }
442}
443
444static void ufshcd_print_evt(struct ufs_hba *hba, u32 id,
445 const char *err_name)
446{
447 int i;
448 bool found = false;
449 const struct ufs_event_hist *e;
450
451 if (id >= UFS_EVT_CNT)
452 return;
453
454 e = &hba->ufs_stats.event[id];
455
456 for (i = 0; i < UFS_EVENT_HIST_LENGTH; i++) {
457 int p = (i + e->pos) % UFS_EVENT_HIST_LENGTH;
458
459 if (e->tstamp[p] == 0)
460 continue;
461 dev_err(hba->dev, "%s[%d] = 0x%x at %lld us\n", err_name, p,
462 e->val[p], div_u64(e->tstamp[p], 1000));
463 found = true;
464 }
465
466 if (!found)
467 dev_err(hba->dev, "No record of %s\n", err_name);
468 else
469 dev_err(hba->dev, "%s: total cnt=%llu\n", err_name, e->cnt);
470}
471
472static void ufshcd_print_evt_hist(struct ufs_hba *hba)
473{
474 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
475
476 ufshcd_print_evt(hba, UFS_EVT_PA_ERR, "pa_err");
477 ufshcd_print_evt(hba, UFS_EVT_DL_ERR, "dl_err");
478 ufshcd_print_evt(hba, UFS_EVT_NL_ERR, "nl_err");
479 ufshcd_print_evt(hba, UFS_EVT_TL_ERR, "tl_err");
480 ufshcd_print_evt(hba, UFS_EVT_DME_ERR, "dme_err");
481 ufshcd_print_evt(hba, UFS_EVT_AUTO_HIBERN8_ERR,
482 "auto_hibern8_err");
483 ufshcd_print_evt(hba, UFS_EVT_FATAL_ERR, "fatal_err");
484 ufshcd_print_evt(hba, UFS_EVT_LINK_STARTUP_FAIL,
485 "link_startup_fail");
486 ufshcd_print_evt(hba, UFS_EVT_RESUME_ERR, "resume_fail");
487 ufshcd_print_evt(hba, UFS_EVT_SUSPEND_ERR,
488 "suspend_fail");
489 ufshcd_print_evt(hba, UFS_EVT_WL_RES_ERR, "wlun resume_fail");
490 ufshcd_print_evt(hba, UFS_EVT_WL_SUSP_ERR,
491 "wlun suspend_fail");
492 ufshcd_print_evt(hba, UFS_EVT_DEV_RESET, "dev_reset");
493 ufshcd_print_evt(hba, UFS_EVT_HOST_RESET, "host_reset");
494 ufshcd_print_evt(hba, UFS_EVT_ABORT, "task_abort");
495
496 ufshcd_vops_dbg_register_dump(hba);
497}
498
499static
500void ufshcd_print_trs(struct ufs_hba *hba, unsigned long bitmap, bool pr_prdt)
501{
502 const struct ufshcd_lrb *lrbp;
503 int prdt_length;
504 int tag;
505
506 for_each_set_bit(tag, &bitmap, hba->nutrs) {
507 lrbp = &hba->lrb[tag];
508
509 dev_err(hba->dev, "UPIU[%d] - issue time %lld us\n",
510 tag, div_u64(lrbp->issue_time_stamp_local_clock, 1000));
511 dev_err(hba->dev, "UPIU[%d] - complete time %lld us\n",
512 tag, div_u64(lrbp->compl_time_stamp_local_clock, 1000));
513 dev_err(hba->dev,
514 "UPIU[%d] - Transfer Request Descriptor phys@0x%llx\n",
515 tag, (u64)lrbp->utrd_dma_addr);
516
517 ufshcd_hex_dump("UPIU TRD: ", lrbp->utr_descriptor_ptr,
518 sizeof(struct utp_transfer_req_desc));
519 dev_err(hba->dev, "UPIU[%d] - Request UPIU phys@0x%llx\n", tag,
520 (u64)lrbp->ucd_req_dma_addr);
521 ufshcd_hex_dump("UPIU REQ: ", lrbp->ucd_req_ptr,
522 sizeof(struct utp_upiu_req));
523 dev_err(hba->dev, "UPIU[%d] - Response UPIU phys@0x%llx\n", tag,
524 (u64)lrbp->ucd_rsp_dma_addr);
525 ufshcd_hex_dump("UPIU RSP: ", lrbp->ucd_rsp_ptr,
526 sizeof(struct utp_upiu_rsp));
527
528 prdt_length = le16_to_cpu(
529 lrbp->utr_descriptor_ptr->prd_table_length);
530 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
531 prdt_length /= sizeof(struct ufshcd_sg_entry);
532
533 dev_err(hba->dev,
534 "UPIU[%d] - PRDT - %d entries phys@0x%llx\n",
535 tag, prdt_length,
536 (u64)lrbp->ucd_prdt_dma_addr);
537
538 if (pr_prdt)
539 ufshcd_hex_dump("UPIU PRDT: ", lrbp->ucd_prdt_ptr,
540 sizeof(struct ufshcd_sg_entry) * prdt_length);
541 }
542}
543
544static void ufshcd_print_tmrs(struct ufs_hba *hba, unsigned long bitmap)
545{
546 int tag;
547
548 for_each_set_bit(tag, &bitmap, hba->nutmrs) {
549 struct utp_task_req_desc *tmrdp = &hba->utmrdl_base_addr[tag];
550
551 dev_err(hba->dev, "TM[%d] - Task Management Header\n", tag);
552 ufshcd_hex_dump("", tmrdp, sizeof(*tmrdp));
553 }
554}
555
556static void ufshcd_print_host_state(struct ufs_hba *hba)
557{
558 const struct scsi_device *sdev_ufs = hba->ufs_device_wlun;
559
560 dev_err(hba->dev, "UFS Host state=%d\n", hba->ufshcd_state);
561 dev_err(hba->dev, "outstanding reqs=0x%lx tasks=0x%lx\n",
562 hba->outstanding_reqs, hba->outstanding_tasks);
563 dev_err(hba->dev, "saved_err=0x%x, saved_uic_err=0x%x\n",
564 hba->saved_err, hba->saved_uic_err);
565 dev_err(hba->dev, "Device power mode=%d, UIC link state=%d\n",
566 hba->curr_dev_pwr_mode, hba->uic_link_state);
567 dev_err(hba->dev, "PM in progress=%d, sys. suspended=%d\n",
568 hba->pm_op_in_progress, hba->is_sys_suspended);
569 dev_err(hba->dev, "Auto BKOPS=%d, Host self-block=%d\n",
570 hba->auto_bkops_enabled, hba->host->host_self_blocked);
571 dev_err(hba->dev, "Clk gate=%d\n", hba->clk_gating.state);
572 dev_err(hba->dev,
573 "last_hibern8_exit_tstamp at %lld us, hibern8_exit_cnt=%d\n",
574 div_u64(hba->ufs_stats.last_hibern8_exit_tstamp, 1000),
575 hba->ufs_stats.hibern8_exit_cnt);
576 dev_err(hba->dev, "last intr at %lld us, last intr status=0x%x\n",
577 div_u64(hba->ufs_stats.last_intr_ts, 1000),
578 hba->ufs_stats.last_intr_status);
579 dev_err(hba->dev, "error handling flags=0x%x, req. abort count=%d\n",
580 hba->eh_flags, hba->req_abort_count);
581 dev_err(hba->dev, "hba->ufs_version=0x%x, Host capabilities=0x%x, caps=0x%x\n",
582 hba->ufs_version, hba->capabilities, hba->caps);
583 dev_err(hba->dev, "quirks=0x%x, dev. quirks=0x%x\n", hba->quirks,
584 hba->dev_quirks);
585 if (sdev_ufs)
586 dev_err(hba->dev, "UFS dev info: %.8s %.16s rev %.4s\n",
587 sdev_ufs->vendor, sdev_ufs->model, sdev_ufs->rev);
588
589 ufshcd_print_clk_freqs(hba);
590}
591
592/**
593 * ufshcd_print_pwr_info - print power params as saved in hba
594 * power info
595 * @hba: per-adapter instance
596 */
597static void ufshcd_print_pwr_info(struct ufs_hba *hba)
598{
599 static const char * const names[] = {
600 "INVALID MODE",
601 "FAST MODE",
602 "SLOW_MODE",
603 "INVALID MODE",
604 "FASTAUTO_MODE",
605 "SLOWAUTO_MODE",
606 "INVALID MODE",
607 };
608
609 /*
610 * Using dev_dbg to avoid messages during runtime PM to avoid
611 * never-ending cycles of messages written back to storage by user space
612 * causing runtime resume, causing more messages and so on.
613 */
614 dev_dbg(hba->dev, "%s:[RX, TX]: gear=[%d, %d], lane[%d, %d], pwr[%s, %s], rate = %d\n",
615 __func__,
616 hba->pwr_info.gear_rx, hba->pwr_info.gear_tx,
617 hba->pwr_info.lane_rx, hba->pwr_info.lane_tx,
618 names[hba->pwr_info.pwr_rx],
619 names[hba->pwr_info.pwr_tx],
620 hba->pwr_info.hs_rate);
621}
622
623static void ufshcd_device_reset(struct ufs_hba *hba)
624{
625 int err;
626
627 err = ufshcd_vops_device_reset(hba);
628
629 if (!err) {
630 ufshcd_set_ufs_dev_active(hba);
631 if (ufshcd_is_wb_allowed(hba)) {
632 hba->dev_info.wb_enabled = false;
633 hba->dev_info.wb_buf_flush_enabled = false;
634 }
635 }
636 if (err != -EOPNOTSUPP)
637 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, err);
638}
639
640void ufshcd_delay_us(unsigned long us, unsigned long tolerance)
641{
642 if (!us)
643 return;
644
645 if (us < 10)
646 udelay(us);
647 else
648 usleep_range(us, us + tolerance);
649}
650EXPORT_SYMBOL_GPL(ufshcd_delay_us);
651
652/**
653 * ufshcd_wait_for_register - wait for register value to change
654 * @hba: per-adapter interface
655 * @reg: mmio register offset
656 * @mask: mask to apply to the read register value
657 * @val: value to wait for
658 * @interval_us: polling interval in microseconds
659 * @timeout_ms: timeout in milliseconds
660 *
661 * Return:
662 * -ETIMEDOUT on error, zero on success.
663 */
664static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
665 u32 val, unsigned long interval_us,
666 unsigned long timeout_ms)
667{
668 int err = 0;
669 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
670
671 /* ignore bits that we don't intend to wait on */
672 val = val & mask;
673
674 while ((ufshcd_readl(hba, reg) & mask) != val) {
675 usleep_range(interval_us, interval_us + 50);
676 if (time_after(jiffies, timeout)) {
677 if ((ufshcd_readl(hba, reg) & mask) != val)
678 err = -ETIMEDOUT;
679 break;
680 }
681 }
682
683 return err;
684}
685
686/**
687 * ufshcd_get_intr_mask - Get the interrupt bit mask
688 * @hba: Pointer to adapter instance
689 *
690 * Returns interrupt bit mask per version
691 */
692static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
693{
694 if (hba->ufs_version == ufshci_version(1, 0))
695 return INTERRUPT_MASK_ALL_VER_10;
696 if (hba->ufs_version <= ufshci_version(2, 0))
697 return INTERRUPT_MASK_ALL_VER_11;
698
699 return INTERRUPT_MASK_ALL_VER_21;
700}
701
702/**
703 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
704 * @hba: Pointer to adapter instance
705 *
706 * Returns UFSHCI version supported by the controller
707 */
708static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
709{
710 u32 ufshci_ver;
711
712 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
713 ufshci_ver = ufshcd_vops_get_ufs_hci_version(hba);
714 else
715 ufshci_ver = ufshcd_readl(hba, REG_UFS_VERSION);
716
717 /*
718 * UFSHCI v1.x uses a different version scheme, in order
719 * to allow the use of comparisons with the ufshci_version
720 * function, we convert it to the same scheme as ufs 2.0+.
721 */
722 if (ufshci_ver & 0x00010000)
723 return ufshci_version(1, ufshci_ver & 0x00000100);
724
725 return ufshci_ver;
726}
727
728/**
729 * ufshcd_is_device_present - Check if any device connected to
730 * the host controller
731 * @hba: pointer to adapter instance
732 *
733 * Returns true if device present, false if no device detected
734 */
735static inline bool ufshcd_is_device_present(struct ufs_hba *hba)
736{
737 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & DEVICE_PRESENT;
738}
739
740/**
741 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
742 * @lrbp: pointer to local command reference block
743 *
744 * This function is used to get the OCS field from UTRD
745 * Returns the OCS field in the UTRD
746 */
747static enum utp_ocs ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
748{
749 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
750}
751
752/**
753 * ufshcd_utrl_clear() - Clear requests from the controller request list.
754 * @hba: per adapter instance
755 * @mask: mask with one bit set for each request to be cleared
756 */
757static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 mask)
758{
759 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
760 mask = ~mask;
761 /*
762 * From the UFSHCI specification: "UTP Transfer Request List CLear
763 * Register (UTRLCLR): This field is bit significant. Each bit
764 * corresponds to a slot in the UTP Transfer Request List, where bit 0
765 * corresponds to request slot 0. A bit in this field is set to ‘0’
766 * by host software to indicate to the host controller that a transfer
767 * request slot is cleared. The host controller
768 * shall free up any resources associated to the request slot
769 * immediately, and shall set the associated bit in UTRLDBR to ‘0’. The
770 * host software indicates no change to request slots by setting the
771 * associated bits in this field to ‘1’. Bits in this field shall only
772 * be set ‘1’ or ‘0’ by host software when UTRLRSR is set to ‘1’."
773 */
774 ufshcd_writel(hba, ~mask, REG_UTP_TRANSFER_REQ_LIST_CLEAR);
775}
776
777/**
778 * ufshcd_utmrl_clear - Clear a bit in UTMRLCLR register
779 * @hba: per adapter instance
780 * @pos: position of the bit to be cleared
781 */
782static inline void ufshcd_utmrl_clear(struct ufs_hba *hba, u32 pos)
783{
784 if (hba->quirks & UFSHCI_QUIRK_BROKEN_REQ_LIST_CLR)
785 ufshcd_writel(hba, (1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
786 else
787 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TASK_REQ_LIST_CLEAR);
788}
789
790/**
791 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
792 * @reg: Register value of host controller status
793 *
794 * Returns integer, 0 on Success and positive value if failed
795 */
796static inline int ufshcd_get_lists_status(u32 reg)
797{
798 return !((reg & UFSHCD_STATUS_READY) == UFSHCD_STATUS_READY);
799}
800
801/**
802 * ufshcd_get_uic_cmd_result - Get the UIC command result
803 * @hba: Pointer to adapter instance
804 *
805 * This function gets the result of UIC command completion
806 * Returns 0 on success, non zero value on error
807 */
808static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
809{
810 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
811 MASK_UIC_COMMAND_RESULT;
812}
813
814/**
815 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
816 * @hba: Pointer to adapter instance
817 *
818 * This function gets UIC command argument3
819 * Returns 0 on success, non zero value on error
820 */
821static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
822{
823 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
824}
825
826/**
827 * ufshcd_get_req_rsp - returns the TR response transaction type
828 * @ucd_rsp_ptr: pointer to response UPIU
829 */
830static inline int
831ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
832{
833 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
834}
835
836/**
837 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
838 * @ucd_rsp_ptr: pointer to response UPIU
839 *
840 * This function gets the response status and scsi_status from response UPIU
841 * Returns the response result code.
842 */
843static inline int
844ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
845{
846 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
847}
848
849/*
850 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
851 * from response UPIU
852 * @ucd_rsp_ptr: pointer to response UPIU
853 *
854 * Return the data segment length.
855 */
856static inline unsigned int
857ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
858{
859 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
860 MASK_RSP_UPIU_DATA_SEG_LEN;
861}
862
863/**
864 * ufshcd_is_exception_event - Check if the device raised an exception event
865 * @ucd_rsp_ptr: pointer to response UPIU
866 *
867 * The function checks if the device raised an exception event indicated in
868 * the Device Information field of response UPIU.
869 *
870 * Returns true if exception is raised, false otherwise.
871 */
872static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
873{
874 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
875 MASK_RSP_EXCEPTION_EVENT;
876}
877
878/**
879 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
880 * @hba: per adapter instance
881 */
882static inline void
883ufshcd_reset_intr_aggr(struct ufs_hba *hba)
884{
885 ufshcd_writel(hba, INT_AGGR_ENABLE |
886 INT_AGGR_COUNTER_AND_TIMER_RESET,
887 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
888}
889
890/**
891 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
892 * @hba: per adapter instance
893 * @cnt: Interrupt aggregation counter threshold
894 * @tmout: Interrupt aggregation timeout value
895 */
896static inline void
897ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
898{
899 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
900 INT_AGGR_COUNTER_THLD_VAL(cnt) |
901 INT_AGGR_TIMEOUT_VAL(tmout),
902 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
903}
904
905/**
906 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
907 * @hba: per adapter instance
908 */
909static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
910{
911 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
912}
913
914/**
915 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
916 * When run-stop registers are set to 1, it indicates the
917 * host controller that it can process the requests
918 * @hba: per adapter instance
919 */
920static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
921{
922 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
923 REG_UTP_TASK_REQ_LIST_RUN_STOP);
924 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
925 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
926}
927
928/**
929 * ufshcd_hba_start - Start controller initialization sequence
930 * @hba: per adapter instance
931 */
932static inline void ufshcd_hba_start(struct ufs_hba *hba)
933{
934 u32 val = CONTROLLER_ENABLE;
935
936 if (ufshcd_crypto_enable(hba))
937 val |= CRYPTO_GENERAL_ENABLE;
938
939 ufshcd_writel(hba, val, REG_CONTROLLER_ENABLE);
940}
941
942/**
943 * ufshcd_is_hba_active - Get controller state
944 * @hba: per adapter instance
945 *
946 * Returns true if and only if the controller is active.
947 */
948static inline bool ufshcd_is_hba_active(struct ufs_hba *hba)
949{
950 return ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & CONTROLLER_ENABLE;
951}
952
953u32 ufshcd_get_local_unipro_ver(struct ufs_hba *hba)
954{
955 /* HCI version 1.0 and 1.1 supports UniPro 1.41 */
956 if (hba->ufs_version <= ufshci_version(1, 1))
957 return UFS_UNIPRO_VER_1_41;
958 else
959 return UFS_UNIPRO_VER_1_6;
960}
961EXPORT_SYMBOL(ufshcd_get_local_unipro_ver);
962
963static bool ufshcd_is_unipro_pa_params_tuning_req(struct ufs_hba *hba)
964{
965 /*
966 * If both host and device support UniPro ver1.6 or later, PA layer
967 * parameters tuning happens during link startup itself.
968 *
969 * We can manually tune PA layer parameters if either host or device
970 * doesn't support UniPro ver 1.6 or later. But to keep manual tuning
971 * logic simple, we will only do manual tuning if local unipro version
972 * doesn't support ver1.6 or later.
973 */
974 return ufshcd_get_local_unipro_ver(hba) < UFS_UNIPRO_VER_1_6;
975}
976
977/**
978 * ufshcd_set_clk_freq - set UFS controller clock frequencies
979 * @hba: per adapter instance
980 * @scale_up: If True, set max possible frequency othewise set low frequency
981 *
982 * Returns 0 if successful
983 * Returns < 0 for any other errors
984 */
985static int ufshcd_set_clk_freq(struct ufs_hba *hba, bool scale_up)
986{
987 int ret = 0;
988 struct ufs_clk_info *clki;
989 struct list_head *head = &hba->clk_list_head;
990
991 if (list_empty(head))
992 goto out;
993
994 list_for_each_entry(clki, head, list) {
995 if (!IS_ERR_OR_NULL(clki->clk)) {
996 if (scale_up && clki->max_freq) {
997 if (clki->curr_freq == clki->max_freq)
998 continue;
999
1000 ret = clk_set_rate(clki->clk, clki->max_freq);
1001 if (ret) {
1002 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1003 __func__, clki->name,
1004 clki->max_freq, ret);
1005 break;
1006 }
1007 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1008 "scaled up", clki->name,
1009 clki->curr_freq,
1010 clki->max_freq);
1011
1012 clki->curr_freq = clki->max_freq;
1013
1014 } else if (!scale_up && clki->min_freq) {
1015 if (clki->curr_freq == clki->min_freq)
1016 continue;
1017
1018 ret = clk_set_rate(clki->clk, clki->min_freq);
1019 if (ret) {
1020 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
1021 __func__, clki->name,
1022 clki->min_freq, ret);
1023 break;
1024 }
1025 trace_ufshcd_clk_scaling(dev_name(hba->dev),
1026 "scaled down", clki->name,
1027 clki->curr_freq,
1028 clki->min_freq);
1029 clki->curr_freq = clki->min_freq;
1030 }
1031 }
1032 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
1033 clki->name, clk_get_rate(clki->clk));
1034 }
1035
1036out:
1037 return ret;
1038}
1039
1040/**
1041 * ufshcd_scale_clks - scale up or scale down UFS controller clocks
1042 * @hba: per adapter instance
1043 * @scale_up: True if scaling up and false if scaling down
1044 *
1045 * Returns 0 if successful
1046 * Returns < 0 for any other errors
1047 */
1048static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
1049{
1050 int ret = 0;
1051 ktime_t start = ktime_get();
1052
1053 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
1054 if (ret)
1055 goto out;
1056
1057 ret = ufshcd_set_clk_freq(hba, scale_up);
1058 if (ret)
1059 goto out;
1060
1061 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
1062 if (ret)
1063 ufshcd_set_clk_freq(hba, !scale_up);
1064
1065out:
1066 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1067 (scale_up ? "up" : "down"),
1068 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1069 return ret;
1070}
1071
1072/**
1073 * ufshcd_is_devfreq_scaling_required - check if scaling is required or not
1074 * @hba: per adapter instance
1075 * @scale_up: True if scaling up and false if scaling down
1076 *
1077 * Returns true if scaling is required, false otherwise.
1078 */
1079static bool ufshcd_is_devfreq_scaling_required(struct ufs_hba *hba,
1080 bool scale_up)
1081{
1082 struct ufs_clk_info *clki;
1083 struct list_head *head = &hba->clk_list_head;
1084
1085 if (list_empty(head))
1086 return false;
1087
1088 list_for_each_entry(clki, head, list) {
1089 if (!IS_ERR_OR_NULL(clki->clk)) {
1090 if (scale_up && clki->max_freq) {
1091 if (clki->curr_freq == clki->max_freq)
1092 continue;
1093 return true;
1094 } else if (!scale_up && clki->min_freq) {
1095 if (clki->curr_freq == clki->min_freq)
1096 continue;
1097 return true;
1098 }
1099 }
1100 }
1101
1102 return false;
1103}
1104
1105/*
1106 * Determine the number of pending commands by counting the bits in the SCSI
1107 * device budget maps. This approach has been selected because a bit is set in
1108 * the budget map before scsi_host_queue_ready() checks the host_self_blocked
1109 * flag. The host_self_blocked flag can be modified by calling
1110 * scsi_block_requests() or scsi_unblock_requests().
1111 */
1112static u32 ufshcd_pending_cmds(struct ufs_hba *hba)
1113{
1114 const struct scsi_device *sdev;
1115 u32 pending = 0;
1116
1117 lockdep_assert_held(hba->host->host_lock);
1118 __shost_for_each_device(sdev, hba->host)
1119 pending += sbitmap_weight(&sdev->budget_map);
1120
1121 return pending;
1122}
1123
1124static int ufshcd_wait_for_doorbell_clr(struct ufs_hba *hba,
1125 u64 wait_timeout_us)
1126{
1127 unsigned long flags;
1128 int ret = 0;
1129 u32 tm_doorbell;
1130 u32 tr_pending;
1131 bool timeout = false, do_last_check = false;
1132 ktime_t start;
1133
1134 ufshcd_hold(hba, false);
1135 spin_lock_irqsave(hba->host->host_lock, flags);
1136 /*
1137 * Wait for all the outstanding tasks/transfer requests.
1138 * Verify by checking the doorbell registers are clear.
1139 */
1140 start = ktime_get();
1141 do {
1142 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL) {
1143 ret = -EBUSY;
1144 goto out;
1145 }
1146
1147 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
1148 tr_pending = ufshcd_pending_cmds(hba);
1149 if (!tm_doorbell && !tr_pending) {
1150 timeout = false;
1151 break;
1152 } else if (do_last_check) {
1153 break;
1154 }
1155
1156 spin_unlock_irqrestore(hba->host->host_lock, flags);
1157 schedule();
1158 if (ktime_to_us(ktime_sub(ktime_get(), start)) >
1159 wait_timeout_us) {
1160 timeout = true;
1161 /*
1162 * We might have scheduled out for long time so make
1163 * sure to check if doorbells are cleared by this time
1164 * or not.
1165 */
1166 do_last_check = true;
1167 }
1168 spin_lock_irqsave(hba->host->host_lock, flags);
1169 } while (tm_doorbell || tr_pending);
1170
1171 if (timeout) {
1172 dev_err(hba->dev,
1173 "%s: timedout waiting for doorbell to clear (tm=0x%x, tr=0x%x)\n",
1174 __func__, tm_doorbell, tr_pending);
1175 ret = -EBUSY;
1176 }
1177out:
1178 spin_unlock_irqrestore(hba->host->host_lock, flags);
1179 ufshcd_release(hba);
1180 return ret;
1181}
1182
1183/**
1184 * ufshcd_scale_gear - scale up/down UFS gear
1185 * @hba: per adapter instance
1186 * @scale_up: True for scaling up gear and false for scaling down
1187 *
1188 * Returns 0 for success,
1189 * Returns -EBUSY if scaling can't happen at this time
1190 * Returns non-zero for any other errors
1191 */
1192static int ufshcd_scale_gear(struct ufs_hba *hba, bool scale_up)
1193{
1194 int ret = 0;
1195 struct ufs_pa_layer_attr new_pwr_info;
1196
1197 if (scale_up) {
1198 memcpy(&new_pwr_info, &hba->clk_scaling.saved_pwr_info.info,
1199 sizeof(struct ufs_pa_layer_attr));
1200 } else {
1201 memcpy(&new_pwr_info, &hba->pwr_info,
1202 sizeof(struct ufs_pa_layer_attr));
1203
1204 if (hba->pwr_info.gear_tx > hba->clk_scaling.min_gear ||
1205 hba->pwr_info.gear_rx > hba->clk_scaling.min_gear) {
1206 /* save the current power mode */
1207 memcpy(&hba->clk_scaling.saved_pwr_info.info,
1208 &hba->pwr_info,
1209 sizeof(struct ufs_pa_layer_attr));
1210
1211 /* scale down gear */
1212 new_pwr_info.gear_tx = hba->clk_scaling.min_gear;
1213 new_pwr_info.gear_rx = hba->clk_scaling.min_gear;
1214 }
1215 }
1216
1217 /* check if the power mode needs to be changed or not? */
1218 ret = ufshcd_config_pwr_mode(hba, &new_pwr_info);
1219 if (ret)
1220 dev_err(hba->dev, "%s: failed err %d, old gear: (tx %d rx %d), new gear: (tx %d rx %d)",
1221 __func__, ret,
1222 hba->pwr_info.gear_tx, hba->pwr_info.gear_rx,
1223 new_pwr_info.gear_tx, new_pwr_info.gear_rx);
1224
1225 return ret;
1226}
1227
1228static int ufshcd_clock_scaling_prepare(struct ufs_hba *hba)
1229{
1230 #define DOORBELL_CLR_TOUT_US (1000 * 1000) /* 1 sec */
1231 int ret = 0;
1232 /*
1233 * make sure that there are no outstanding requests when
1234 * clock scaling is in progress
1235 */
1236 ufshcd_scsi_block_requests(hba);
1237 mutex_lock(&hba->wb_mutex);
1238 down_write(&hba->clk_scaling_lock);
1239
1240 if (!hba->clk_scaling.is_allowed ||
1241 ufshcd_wait_for_doorbell_clr(hba, DOORBELL_CLR_TOUT_US)) {
1242 ret = -EBUSY;
1243 up_write(&hba->clk_scaling_lock);
1244 mutex_unlock(&hba->wb_mutex);
1245 ufshcd_scsi_unblock_requests(hba);
1246 goto out;
1247 }
1248
1249 /* let's not get into low power until clock scaling is completed */
1250 ufshcd_hold(hba, false);
1251
1252out:
1253 return ret;
1254}
1255
1256static void ufshcd_clock_scaling_unprepare(struct ufs_hba *hba, int err, bool scale_up)
1257{
1258 up_write(&hba->clk_scaling_lock);
1259
1260 /* Enable Write Booster if we have scaled up else disable it */
1261 if (ufshcd_enable_wb_if_scaling_up(hba) && !err)
1262 ufshcd_wb_toggle(hba, scale_up);
1263
1264 mutex_unlock(&hba->wb_mutex);
1265
1266 ufshcd_scsi_unblock_requests(hba);
1267 ufshcd_release(hba);
1268}
1269
1270/**
1271 * ufshcd_devfreq_scale - scale up/down UFS clocks and gear
1272 * @hba: per adapter instance
1273 * @scale_up: True for scaling up and false for scalin down
1274 *
1275 * Returns 0 for success,
1276 * Returns -EBUSY if scaling can't happen at this time
1277 * Returns non-zero for any other errors
1278 */
1279static int ufshcd_devfreq_scale(struct ufs_hba *hba, bool scale_up)
1280{
1281 int ret = 0;
1282
1283 ret = ufshcd_clock_scaling_prepare(hba);
1284 if (ret)
1285 return ret;
1286
1287 /* scale down the gear before scaling down clocks */
1288 if (!scale_up) {
1289 ret = ufshcd_scale_gear(hba, false);
1290 if (ret)
1291 goto out_unprepare;
1292 }
1293
1294 ret = ufshcd_scale_clks(hba, scale_up);
1295 if (ret) {
1296 if (!scale_up)
1297 ufshcd_scale_gear(hba, true);
1298 goto out_unprepare;
1299 }
1300
1301 /* scale up the gear after scaling up clocks */
1302 if (scale_up) {
1303 ret = ufshcd_scale_gear(hba, true);
1304 if (ret) {
1305 ufshcd_scale_clks(hba, false);
1306 goto out_unprepare;
1307 }
1308 }
1309
1310out_unprepare:
1311 ufshcd_clock_scaling_unprepare(hba, ret, scale_up);
1312 return ret;
1313}
1314
1315static void ufshcd_clk_scaling_suspend_work(struct work_struct *work)
1316{
1317 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1318 clk_scaling.suspend_work);
1319 unsigned long irq_flags;
1320
1321 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1322 if (hba->clk_scaling.active_reqs || hba->clk_scaling.is_suspended) {
1323 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1324 return;
1325 }
1326 hba->clk_scaling.is_suspended = true;
1327 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1328
1329 __ufshcd_suspend_clkscaling(hba);
1330}
1331
1332static void ufshcd_clk_scaling_resume_work(struct work_struct *work)
1333{
1334 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1335 clk_scaling.resume_work);
1336 unsigned long irq_flags;
1337
1338 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1339 if (!hba->clk_scaling.is_suspended) {
1340 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1341 return;
1342 }
1343 hba->clk_scaling.is_suspended = false;
1344 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1345
1346 devfreq_resume_device(hba->devfreq);
1347}
1348
1349static int ufshcd_devfreq_target(struct device *dev,
1350 unsigned long *freq, u32 flags)
1351{
1352 int ret = 0;
1353 struct ufs_hba *hba = dev_get_drvdata(dev);
1354 ktime_t start;
1355 bool scale_up, sched_clk_scaling_suspend_work = false;
1356 struct list_head *clk_list = &hba->clk_list_head;
1357 struct ufs_clk_info *clki;
1358 unsigned long irq_flags;
1359
1360 if (!ufshcd_is_clkscaling_supported(hba))
1361 return -EINVAL;
1362
1363 clki = list_first_entry(&hba->clk_list_head, struct ufs_clk_info, list);
1364 /* Override with the closest supported frequency */
1365 *freq = (unsigned long) clk_round_rate(clki->clk, *freq);
1366 spin_lock_irqsave(hba->host->host_lock, irq_flags);
1367 if (ufshcd_eh_in_progress(hba)) {
1368 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1369 return 0;
1370 }
1371
1372 if (!hba->clk_scaling.active_reqs)
1373 sched_clk_scaling_suspend_work = true;
1374
1375 if (list_empty(clk_list)) {
1376 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1377 goto out;
1378 }
1379
1380 /* Decide based on the rounded-off frequency and update */
1381 scale_up = *freq == clki->max_freq;
1382 if (!scale_up)
1383 *freq = clki->min_freq;
1384 /* Update the frequency */
1385 if (!ufshcd_is_devfreq_scaling_required(hba, scale_up)) {
1386 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1387 ret = 0;
1388 goto out; /* no state change required */
1389 }
1390 spin_unlock_irqrestore(hba->host->host_lock, irq_flags);
1391
1392 start = ktime_get();
1393 ret = ufshcd_devfreq_scale(hba, scale_up);
1394
1395 trace_ufshcd_profile_clk_scaling(dev_name(hba->dev),
1396 (scale_up ? "up" : "down"),
1397 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
1398
1399out:
1400 if (sched_clk_scaling_suspend_work)
1401 queue_work(hba->clk_scaling.workq,
1402 &hba->clk_scaling.suspend_work);
1403
1404 return ret;
1405}
1406
1407static int ufshcd_devfreq_get_dev_status(struct device *dev,
1408 struct devfreq_dev_status *stat)
1409{
1410 struct ufs_hba *hba = dev_get_drvdata(dev);
1411 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
1412 unsigned long flags;
1413 struct list_head *clk_list = &hba->clk_list_head;
1414 struct ufs_clk_info *clki;
1415 ktime_t curr_t;
1416
1417 if (!ufshcd_is_clkscaling_supported(hba))
1418 return -EINVAL;
1419
1420 memset(stat, 0, sizeof(*stat));
1421
1422 spin_lock_irqsave(hba->host->host_lock, flags);
1423 curr_t = ktime_get();
1424 if (!scaling->window_start_t)
1425 goto start_window;
1426
1427 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1428 /*
1429 * If current frequency is 0, then the ondemand governor considers
1430 * there's no initial frequency set. And it always requests to set
1431 * to max. frequency.
1432 */
1433 stat->current_frequency = clki->curr_freq;
1434 if (scaling->is_busy_started)
1435 scaling->tot_busy_t += ktime_us_delta(curr_t,
1436 scaling->busy_start_t);
1437
1438 stat->total_time = ktime_us_delta(curr_t, scaling->window_start_t);
1439 stat->busy_time = scaling->tot_busy_t;
1440start_window:
1441 scaling->window_start_t = curr_t;
1442 scaling->tot_busy_t = 0;
1443
1444 if (hba->outstanding_reqs) {
1445 scaling->busy_start_t = curr_t;
1446 scaling->is_busy_started = true;
1447 } else {
1448 scaling->busy_start_t = 0;
1449 scaling->is_busy_started = false;
1450 }
1451 spin_unlock_irqrestore(hba->host->host_lock, flags);
1452 return 0;
1453}
1454
1455static int ufshcd_devfreq_init(struct ufs_hba *hba)
1456{
1457 struct list_head *clk_list = &hba->clk_list_head;
1458 struct ufs_clk_info *clki;
1459 struct devfreq *devfreq;
1460 int ret;
1461
1462 /* Skip devfreq if we don't have any clocks in the list */
1463 if (list_empty(clk_list))
1464 return 0;
1465
1466 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1467 dev_pm_opp_add(hba->dev, clki->min_freq, 0);
1468 dev_pm_opp_add(hba->dev, clki->max_freq, 0);
1469
1470 ufshcd_vops_config_scaling_param(hba, &hba->vps->devfreq_profile,
1471 &hba->vps->ondemand_data);
1472 devfreq = devfreq_add_device(hba->dev,
1473 &hba->vps->devfreq_profile,
1474 DEVFREQ_GOV_SIMPLE_ONDEMAND,
1475 &hba->vps->ondemand_data);
1476 if (IS_ERR(devfreq)) {
1477 ret = PTR_ERR(devfreq);
1478 dev_err(hba->dev, "Unable to register with devfreq %d\n", ret);
1479
1480 dev_pm_opp_remove(hba->dev, clki->min_freq);
1481 dev_pm_opp_remove(hba->dev, clki->max_freq);
1482 return ret;
1483 }
1484
1485 hba->devfreq = devfreq;
1486
1487 return 0;
1488}
1489
1490static void ufshcd_devfreq_remove(struct ufs_hba *hba)
1491{
1492 struct list_head *clk_list = &hba->clk_list_head;
1493 struct ufs_clk_info *clki;
1494
1495 if (!hba->devfreq)
1496 return;
1497
1498 devfreq_remove_device(hba->devfreq);
1499 hba->devfreq = NULL;
1500
1501 clki = list_first_entry(clk_list, struct ufs_clk_info, list);
1502 dev_pm_opp_remove(hba->dev, clki->min_freq);
1503 dev_pm_opp_remove(hba->dev, clki->max_freq);
1504}
1505
1506static void __ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1507{
1508 unsigned long flags;
1509
1510 devfreq_suspend_device(hba->devfreq);
1511 spin_lock_irqsave(hba->host->host_lock, flags);
1512 hba->clk_scaling.window_start_t = 0;
1513 spin_unlock_irqrestore(hba->host->host_lock, flags);
1514}
1515
1516static void ufshcd_suspend_clkscaling(struct ufs_hba *hba)
1517{
1518 unsigned long flags;
1519 bool suspend = false;
1520
1521 cancel_work_sync(&hba->clk_scaling.suspend_work);
1522 cancel_work_sync(&hba->clk_scaling.resume_work);
1523
1524 spin_lock_irqsave(hba->host->host_lock, flags);
1525 if (!hba->clk_scaling.is_suspended) {
1526 suspend = true;
1527 hba->clk_scaling.is_suspended = true;
1528 }
1529 spin_unlock_irqrestore(hba->host->host_lock, flags);
1530
1531 if (suspend)
1532 __ufshcd_suspend_clkscaling(hba);
1533}
1534
1535static void ufshcd_resume_clkscaling(struct ufs_hba *hba)
1536{
1537 unsigned long flags;
1538 bool resume = false;
1539
1540 spin_lock_irqsave(hba->host->host_lock, flags);
1541 if (hba->clk_scaling.is_suspended) {
1542 resume = true;
1543 hba->clk_scaling.is_suspended = false;
1544 }
1545 spin_unlock_irqrestore(hba->host->host_lock, flags);
1546
1547 if (resume)
1548 devfreq_resume_device(hba->devfreq);
1549}
1550
1551static ssize_t ufshcd_clkscale_enable_show(struct device *dev,
1552 struct device_attribute *attr, char *buf)
1553{
1554 struct ufs_hba *hba = dev_get_drvdata(dev);
1555
1556 return sysfs_emit(buf, "%d\n", hba->clk_scaling.is_enabled);
1557}
1558
1559static ssize_t ufshcd_clkscale_enable_store(struct device *dev,
1560 struct device_attribute *attr, const char *buf, size_t count)
1561{
1562 struct ufs_hba *hba = dev_get_drvdata(dev);
1563 u32 value;
1564 int err = 0;
1565
1566 if (kstrtou32(buf, 0, &value))
1567 return -EINVAL;
1568
1569 down(&hba->host_sem);
1570 if (!ufshcd_is_user_access_allowed(hba)) {
1571 err = -EBUSY;
1572 goto out;
1573 }
1574
1575 value = !!value;
1576 if (value == hba->clk_scaling.is_enabled)
1577 goto out;
1578
1579 ufshcd_rpm_get_sync(hba);
1580 ufshcd_hold(hba, false);
1581
1582 hba->clk_scaling.is_enabled = value;
1583
1584 if (value) {
1585 ufshcd_resume_clkscaling(hba);
1586 } else {
1587 ufshcd_suspend_clkscaling(hba);
1588 err = ufshcd_devfreq_scale(hba, true);
1589 if (err)
1590 dev_err(hba->dev, "%s: failed to scale clocks up %d\n",
1591 __func__, err);
1592 }
1593
1594 ufshcd_release(hba);
1595 ufshcd_rpm_put_sync(hba);
1596out:
1597 up(&hba->host_sem);
1598 return err ? err : count;
1599}
1600
1601static void ufshcd_init_clk_scaling_sysfs(struct ufs_hba *hba)
1602{
1603 hba->clk_scaling.enable_attr.show = ufshcd_clkscale_enable_show;
1604 hba->clk_scaling.enable_attr.store = ufshcd_clkscale_enable_store;
1605 sysfs_attr_init(&hba->clk_scaling.enable_attr.attr);
1606 hba->clk_scaling.enable_attr.attr.name = "clkscale_enable";
1607 hba->clk_scaling.enable_attr.attr.mode = 0644;
1608 if (device_create_file(hba->dev, &hba->clk_scaling.enable_attr))
1609 dev_err(hba->dev, "Failed to create sysfs for clkscale_enable\n");
1610}
1611
1612static void ufshcd_remove_clk_scaling_sysfs(struct ufs_hba *hba)
1613{
1614 if (hba->clk_scaling.enable_attr.attr.name)
1615 device_remove_file(hba->dev, &hba->clk_scaling.enable_attr);
1616}
1617
1618static void ufshcd_init_clk_scaling(struct ufs_hba *hba)
1619{
1620 char wq_name[sizeof("ufs_clkscaling_00")];
1621
1622 if (!ufshcd_is_clkscaling_supported(hba))
1623 return;
1624
1625 if (!hba->clk_scaling.min_gear)
1626 hba->clk_scaling.min_gear = UFS_HS_G1;
1627
1628 INIT_WORK(&hba->clk_scaling.suspend_work,
1629 ufshcd_clk_scaling_suspend_work);
1630 INIT_WORK(&hba->clk_scaling.resume_work,
1631 ufshcd_clk_scaling_resume_work);
1632
1633 snprintf(wq_name, sizeof(wq_name), "ufs_clkscaling_%d",
1634 hba->host->host_no);
1635 hba->clk_scaling.workq = create_singlethread_workqueue(wq_name);
1636
1637 hba->clk_scaling.is_initialized = true;
1638}
1639
1640static void ufshcd_exit_clk_scaling(struct ufs_hba *hba)
1641{
1642 if (!hba->clk_scaling.is_initialized)
1643 return;
1644
1645 ufshcd_remove_clk_scaling_sysfs(hba);
1646 destroy_workqueue(hba->clk_scaling.workq);
1647 ufshcd_devfreq_remove(hba);
1648 hba->clk_scaling.is_initialized = false;
1649}
1650
1651static void ufshcd_ungate_work(struct work_struct *work)
1652{
1653 int ret;
1654 unsigned long flags;
1655 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1656 clk_gating.ungate_work);
1657
1658 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1659
1660 spin_lock_irqsave(hba->host->host_lock, flags);
1661 if (hba->clk_gating.state == CLKS_ON) {
1662 spin_unlock_irqrestore(hba->host->host_lock, flags);
1663 goto unblock_reqs;
1664 }
1665
1666 spin_unlock_irqrestore(hba->host->host_lock, flags);
1667 ufshcd_hba_vreg_set_hpm(hba);
1668 ufshcd_setup_clocks(hba, true);
1669
1670 ufshcd_enable_irq(hba);
1671
1672 /* Exit from hibern8 */
1673 if (ufshcd_can_hibern8_during_gating(hba)) {
1674 /* Prevent gating in this path */
1675 hba->clk_gating.is_suspended = true;
1676 if (ufshcd_is_link_hibern8(hba)) {
1677 ret = ufshcd_uic_hibern8_exit(hba);
1678 if (ret)
1679 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
1680 __func__, ret);
1681 else
1682 ufshcd_set_link_active(hba);
1683 }
1684 hba->clk_gating.is_suspended = false;
1685 }
1686unblock_reqs:
1687 ufshcd_scsi_unblock_requests(hba);
1688}
1689
1690/**
1691 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
1692 * Also, exit from hibern8 mode and set the link as active.
1693 * @hba: per adapter instance
1694 * @async: This indicates whether caller should ungate clocks asynchronously.
1695 */
1696int ufshcd_hold(struct ufs_hba *hba, bool async)
1697{
1698 int rc = 0;
1699 bool flush_result;
1700 unsigned long flags;
1701
1702 if (!ufshcd_is_clkgating_allowed(hba) ||
1703 !hba->clk_gating.is_initialized)
1704 goto out;
1705 spin_lock_irqsave(hba->host->host_lock, flags);
1706 hba->clk_gating.active_reqs++;
1707
1708start:
1709 switch (hba->clk_gating.state) {
1710 case CLKS_ON:
1711 /*
1712 * Wait for the ungate work to complete if in progress.
1713 * Though the clocks may be in ON state, the link could
1714 * still be in hibner8 state if hibern8 is allowed
1715 * during clock gating.
1716 * Make sure we exit hibern8 state also in addition to
1717 * clocks being ON.
1718 */
1719 if (ufshcd_can_hibern8_during_gating(hba) &&
1720 ufshcd_is_link_hibern8(hba)) {
1721 if (async) {
1722 rc = -EAGAIN;
1723 hba->clk_gating.active_reqs--;
1724 break;
1725 }
1726 spin_unlock_irqrestore(hba->host->host_lock, flags);
1727 flush_result = flush_work(&hba->clk_gating.ungate_work);
1728 if (hba->clk_gating.is_suspended && !flush_result)
1729 goto out;
1730 spin_lock_irqsave(hba->host->host_lock, flags);
1731 goto start;
1732 }
1733 break;
1734 case REQ_CLKS_OFF:
1735 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
1736 hba->clk_gating.state = CLKS_ON;
1737 trace_ufshcd_clk_gating(dev_name(hba->dev),
1738 hba->clk_gating.state);
1739 break;
1740 }
1741 /*
1742 * If we are here, it means gating work is either done or
1743 * currently running. Hence, fall through to cancel gating
1744 * work and to enable clocks.
1745 */
1746 fallthrough;
1747 case CLKS_OFF:
1748 hba->clk_gating.state = REQ_CLKS_ON;
1749 trace_ufshcd_clk_gating(dev_name(hba->dev),
1750 hba->clk_gating.state);
1751 if (queue_work(hba->clk_gating.clk_gating_workq,
1752 &hba->clk_gating.ungate_work))
1753 ufshcd_scsi_block_requests(hba);
1754 /*
1755 * fall through to check if we should wait for this
1756 * work to be done or not.
1757 */
1758 fallthrough;
1759 case REQ_CLKS_ON:
1760 if (async) {
1761 rc = -EAGAIN;
1762 hba->clk_gating.active_reqs--;
1763 break;
1764 }
1765
1766 spin_unlock_irqrestore(hba->host->host_lock, flags);
1767 flush_work(&hba->clk_gating.ungate_work);
1768 /* Make sure state is CLKS_ON before returning */
1769 spin_lock_irqsave(hba->host->host_lock, flags);
1770 goto start;
1771 default:
1772 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
1773 __func__, hba->clk_gating.state);
1774 break;
1775 }
1776 spin_unlock_irqrestore(hba->host->host_lock, flags);
1777out:
1778 return rc;
1779}
1780EXPORT_SYMBOL_GPL(ufshcd_hold);
1781
1782static void ufshcd_gate_work(struct work_struct *work)
1783{
1784 struct ufs_hba *hba = container_of(work, struct ufs_hba,
1785 clk_gating.gate_work.work);
1786 unsigned long flags;
1787 int ret;
1788
1789 spin_lock_irqsave(hba->host->host_lock, flags);
1790 /*
1791 * In case you are here to cancel this work the gating state
1792 * would be marked as REQ_CLKS_ON. In this case save time by
1793 * skipping the gating work and exit after changing the clock
1794 * state to CLKS_ON.
1795 */
1796 if (hba->clk_gating.is_suspended ||
1797 (hba->clk_gating.state != REQ_CLKS_OFF)) {
1798 hba->clk_gating.state = CLKS_ON;
1799 trace_ufshcd_clk_gating(dev_name(hba->dev),
1800 hba->clk_gating.state);
1801 goto rel_lock;
1802 }
1803
1804 if (hba->clk_gating.active_reqs
1805 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
1806 || hba->outstanding_reqs || hba->outstanding_tasks
1807 || hba->active_uic_cmd || hba->uic_async_done)
1808 goto rel_lock;
1809
1810 spin_unlock_irqrestore(hba->host->host_lock, flags);
1811
1812 /* put the link into hibern8 mode before turning off clocks */
1813 if (ufshcd_can_hibern8_during_gating(hba)) {
1814 ret = ufshcd_uic_hibern8_enter(hba);
1815 if (ret) {
1816 hba->clk_gating.state = CLKS_ON;
1817 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
1818 __func__, ret);
1819 trace_ufshcd_clk_gating(dev_name(hba->dev),
1820 hba->clk_gating.state);
1821 goto out;
1822 }
1823 ufshcd_set_link_hibern8(hba);
1824 }
1825
1826 ufshcd_disable_irq(hba);
1827
1828 ufshcd_setup_clocks(hba, false);
1829
1830 /* Put the host controller in low power mode if possible */
1831 ufshcd_hba_vreg_set_lpm(hba);
1832 /*
1833 * In case you are here to cancel this work the gating state
1834 * would be marked as REQ_CLKS_ON. In this case keep the state
1835 * as REQ_CLKS_ON which would anyway imply that clocks are off
1836 * and a request to turn them on is pending. By doing this way,
1837 * we keep the state machine in tact and this would ultimately
1838 * prevent from doing cancel work multiple times when there are
1839 * new requests arriving before the current cancel work is done.
1840 */
1841 spin_lock_irqsave(hba->host->host_lock, flags);
1842 if (hba->clk_gating.state == REQ_CLKS_OFF) {
1843 hba->clk_gating.state = CLKS_OFF;
1844 trace_ufshcd_clk_gating(dev_name(hba->dev),
1845 hba->clk_gating.state);
1846 }
1847rel_lock:
1848 spin_unlock_irqrestore(hba->host->host_lock, flags);
1849out:
1850 return;
1851}
1852
1853/* host lock must be held before calling this variant */
1854static void __ufshcd_release(struct ufs_hba *hba)
1855{
1856 if (!ufshcd_is_clkgating_allowed(hba))
1857 return;
1858
1859 hba->clk_gating.active_reqs--;
1860
1861 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended ||
1862 hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL ||
1863 hba->outstanding_tasks || !hba->clk_gating.is_initialized ||
1864 hba->active_uic_cmd || hba->uic_async_done ||
1865 hba->clk_gating.state == CLKS_OFF)
1866 return;
1867
1868 hba->clk_gating.state = REQ_CLKS_OFF;
1869 trace_ufshcd_clk_gating(dev_name(hba->dev), hba->clk_gating.state);
1870 queue_delayed_work(hba->clk_gating.clk_gating_workq,
1871 &hba->clk_gating.gate_work,
1872 msecs_to_jiffies(hba->clk_gating.delay_ms));
1873}
1874
1875void ufshcd_release(struct ufs_hba *hba)
1876{
1877 unsigned long flags;
1878
1879 spin_lock_irqsave(hba->host->host_lock, flags);
1880 __ufshcd_release(hba);
1881 spin_unlock_irqrestore(hba->host->host_lock, flags);
1882}
1883EXPORT_SYMBOL_GPL(ufshcd_release);
1884
1885static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
1886 struct device_attribute *attr, char *buf)
1887{
1888 struct ufs_hba *hba = dev_get_drvdata(dev);
1889
1890 return sysfs_emit(buf, "%lu\n", hba->clk_gating.delay_ms);
1891}
1892
1893void ufshcd_clkgate_delay_set(struct device *dev, unsigned long value)
1894{
1895 struct ufs_hba *hba = dev_get_drvdata(dev);
1896 unsigned long flags;
1897
1898 spin_lock_irqsave(hba->host->host_lock, flags);
1899 hba->clk_gating.delay_ms = value;
1900 spin_unlock_irqrestore(hba->host->host_lock, flags);
1901}
1902EXPORT_SYMBOL_GPL(ufshcd_clkgate_delay_set);
1903
1904static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
1905 struct device_attribute *attr, const char *buf, size_t count)
1906{
1907 unsigned long value;
1908
1909 if (kstrtoul(buf, 0, &value))
1910 return -EINVAL;
1911
1912 ufshcd_clkgate_delay_set(dev, value);
1913 return count;
1914}
1915
1916static ssize_t ufshcd_clkgate_enable_show(struct device *dev,
1917 struct device_attribute *attr, char *buf)
1918{
1919 struct ufs_hba *hba = dev_get_drvdata(dev);
1920
1921 return sysfs_emit(buf, "%d\n", hba->clk_gating.is_enabled);
1922}
1923
1924static ssize_t ufshcd_clkgate_enable_store(struct device *dev,
1925 struct device_attribute *attr, const char *buf, size_t count)
1926{
1927 struct ufs_hba *hba = dev_get_drvdata(dev);
1928 unsigned long flags;
1929 u32 value;
1930
1931 if (kstrtou32(buf, 0, &value))
1932 return -EINVAL;
1933
1934 value = !!value;
1935
1936 spin_lock_irqsave(hba->host->host_lock, flags);
1937 if (value == hba->clk_gating.is_enabled)
1938 goto out;
1939
1940 if (value)
1941 __ufshcd_release(hba);
1942 else
1943 hba->clk_gating.active_reqs++;
1944
1945 hba->clk_gating.is_enabled = value;
1946out:
1947 spin_unlock_irqrestore(hba->host->host_lock, flags);
1948 return count;
1949}
1950
1951static void ufshcd_init_clk_gating_sysfs(struct ufs_hba *hba)
1952{
1953 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
1954 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
1955 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
1956 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
1957 hba->clk_gating.delay_attr.attr.mode = 0644;
1958 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
1959 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
1960
1961 hba->clk_gating.enable_attr.show = ufshcd_clkgate_enable_show;
1962 hba->clk_gating.enable_attr.store = ufshcd_clkgate_enable_store;
1963 sysfs_attr_init(&hba->clk_gating.enable_attr.attr);
1964 hba->clk_gating.enable_attr.attr.name = "clkgate_enable";
1965 hba->clk_gating.enable_attr.attr.mode = 0644;
1966 if (device_create_file(hba->dev, &hba->clk_gating.enable_attr))
1967 dev_err(hba->dev, "Failed to create sysfs for clkgate_enable\n");
1968}
1969
1970static void ufshcd_remove_clk_gating_sysfs(struct ufs_hba *hba)
1971{
1972 if (hba->clk_gating.delay_attr.attr.name)
1973 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
1974 if (hba->clk_gating.enable_attr.attr.name)
1975 device_remove_file(hba->dev, &hba->clk_gating.enable_attr);
1976}
1977
1978static void ufshcd_init_clk_gating(struct ufs_hba *hba)
1979{
1980 char wq_name[sizeof("ufs_clk_gating_00")];
1981
1982 if (!ufshcd_is_clkgating_allowed(hba))
1983 return;
1984
1985 hba->clk_gating.state = CLKS_ON;
1986
1987 hba->clk_gating.delay_ms = 150;
1988 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
1989 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
1990
1991 snprintf(wq_name, ARRAY_SIZE(wq_name), "ufs_clk_gating_%d",
1992 hba->host->host_no);
1993 hba->clk_gating.clk_gating_workq = alloc_ordered_workqueue(wq_name,
1994 WQ_MEM_RECLAIM | WQ_HIGHPRI);
1995
1996 ufshcd_init_clk_gating_sysfs(hba);
1997
1998 hba->clk_gating.is_enabled = true;
1999 hba->clk_gating.is_initialized = true;
2000}
2001
2002static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
2003{
2004 if (!hba->clk_gating.is_initialized)
2005 return;
2006
2007 ufshcd_remove_clk_gating_sysfs(hba);
2008
2009 /* Ungate the clock if necessary. */
2010 ufshcd_hold(hba, false);
2011 hba->clk_gating.is_initialized = false;
2012 ufshcd_release(hba);
2013
2014 destroy_workqueue(hba->clk_gating.clk_gating_workq);
2015}
2016
2017static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
2018{
2019 bool queue_resume_work = false;
2020 ktime_t curr_t = ktime_get();
2021 unsigned long flags;
2022
2023 if (!ufshcd_is_clkscaling_supported(hba))
2024 return;
2025
2026 spin_lock_irqsave(hba->host->host_lock, flags);
2027 if (!hba->clk_scaling.active_reqs++)
2028 queue_resume_work = true;
2029
2030 if (!hba->clk_scaling.is_enabled || hba->pm_op_in_progress) {
2031 spin_unlock_irqrestore(hba->host->host_lock, flags);
2032 return;
2033 }
2034
2035 if (queue_resume_work)
2036 queue_work(hba->clk_scaling.workq,
2037 &hba->clk_scaling.resume_work);
2038
2039 if (!hba->clk_scaling.window_start_t) {
2040 hba->clk_scaling.window_start_t = curr_t;
2041 hba->clk_scaling.tot_busy_t = 0;
2042 hba->clk_scaling.is_busy_started = false;
2043 }
2044
2045 if (!hba->clk_scaling.is_busy_started) {
2046 hba->clk_scaling.busy_start_t = curr_t;
2047 hba->clk_scaling.is_busy_started = true;
2048 }
2049 spin_unlock_irqrestore(hba->host->host_lock, flags);
2050}
2051
2052static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
2053{
2054 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
2055 unsigned long flags;
2056
2057 if (!ufshcd_is_clkscaling_supported(hba))
2058 return;
2059
2060 spin_lock_irqsave(hba->host->host_lock, flags);
2061 hba->clk_scaling.active_reqs--;
2062 if (!hba->outstanding_reqs && scaling->is_busy_started) {
2063 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
2064 scaling->busy_start_t));
2065 scaling->busy_start_t = 0;
2066 scaling->is_busy_started = false;
2067 }
2068 spin_unlock_irqrestore(hba->host->host_lock, flags);
2069}
2070
2071static inline int ufshcd_monitor_opcode2dir(u8 opcode)
2072{
2073 if (opcode == READ_6 || opcode == READ_10 || opcode == READ_16)
2074 return READ;
2075 else if (opcode == WRITE_6 || opcode == WRITE_10 || opcode == WRITE_16)
2076 return WRITE;
2077 else
2078 return -EINVAL;
2079}
2080
2081static inline bool ufshcd_should_inform_monitor(struct ufs_hba *hba,
2082 struct ufshcd_lrb *lrbp)
2083{
2084 const struct ufs_hba_monitor *m = &hba->monitor;
2085
2086 return (m->enabled && lrbp && lrbp->cmd &&
2087 (!m->chunk_size || m->chunk_size == lrbp->cmd->sdb.length) &&
2088 ktime_before(hba->monitor.enabled_ts, lrbp->issue_time_stamp));
2089}
2090
2091static void ufshcd_start_monitor(struct ufs_hba *hba,
2092 const struct ufshcd_lrb *lrbp)
2093{
2094 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2095 unsigned long flags;
2096
2097 spin_lock_irqsave(hba->host->host_lock, flags);
2098 if (dir >= 0 && hba->monitor.nr_queued[dir]++ == 0)
2099 hba->monitor.busy_start_ts[dir] = ktime_get();
2100 spin_unlock_irqrestore(hba->host->host_lock, flags);
2101}
2102
2103static void ufshcd_update_monitor(struct ufs_hba *hba, const struct ufshcd_lrb *lrbp)
2104{
2105 int dir = ufshcd_monitor_opcode2dir(*lrbp->cmd->cmnd);
2106 unsigned long flags;
2107
2108 spin_lock_irqsave(hba->host->host_lock, flags);
2109 if (dir >= 0 && hba->monitor.nr_queued[dir] > 0) {
2110 const struct request *req = scsi_cmd_to_rq(lrbp->cmd);
2111 struct ufs_hba_monitor *m = &hba->monitor;
2112 ktime_t now, inc, lat;
2113
2114 now = lrbp->compl_time_stamp;
2115 inc = ktime_sub(now, m->busy_start_ts[dir]);
2116 m->total_busy[dir] = ktime_add(m->total_busy[dir], inc);
2117 m->nr_sec_rw[dir] += blk_rq_sectors(req);
2118
2119 /* Update latencies */
2120 m->nr_req[dir]++;
2121 lat = ktime_sub(now, lrbp->issue_time_stamp);
2122 m->lat_sum[dir] += lat;
2123 if (m->lat_max[dir] < lat || !m->lat_max[dir])
2124 m->lat_max[dir] = lat;
2125 if (m->lat_min[dir] > lat || !m->lat_min[dir])
2126 m->lat_min[dir] = lat;
2127
2128 m->nr_queued[dir]--;
2129 /* Push forward the busy start of monitor */
2130 m->busy_start_ts[dir] = now;
2131 }
2132 spin_unlock_irqrestore(hba->host->host_lock, flags);
2133}
2134
2135/**
2136 * ufshcd_send_command - Send SCSI or device management commands
2137 * @hba: per adapter instance
2138 * @task_tag: Task tag of the command
2139 */
2140static inline
2141void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
2142{
2143 struct ufshcd_lrb *lrbp = &hba->lrb[task_tag];
2144 unsigned long flags;
2145
2146 lrbp->issue_time_stamp = ktime_get();
2147 lrbp->issue_time_stamp_local_clock = local_clock();
2148 lrbp->compl_time_stamp = ktime_set(0, 0);
2149 lrbp->compl_time_stamp_local_clock = 0;
2150 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_SEND);
2151 ufshcd_clk_scaling_start_busy(hba);
2152 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
2153 ufshcd_start_monitor(hba, lrbp);
2154
2155 spin_lock_irqsave(&hba->outstanding_lock, flags);
2156 if (hba->vops && hba->vops->setup_xfer_req)
2157 hba->vops->setup_xfer_req(hba, task_tag, !!lrbp->cmd);
2158 __set_bit(task_tag, &hba->outstanding_reqs);
2159 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2160 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2161}
2162
2163/**
2164 * ufshcd_copy_sense_data - Copy sense data in case of check condition
2165 * @lrbp: pointer to local reference block
2166 */
2167static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
2168{
2169 u8 *const sense_buffer = lrbp->cmd->sense_buffer;
2170 int len;
2171
2172 if (sense_buffer &&
2173 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
2174 int len_to_copy;
2175
2176 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
2177 len_to_copy = min_t(int, UFS_SENSE_SIZE, len);
2178
2179 memcpy(sense_buffer, lrbp->ucd_rsp_ptr->sr.sense_data,
2180 len_to_copy);
2181 }
2182}
2183
2184/**
2185 * ufshcd_copy_query_response() - Copy the Query Response and the data
2186 * descriptor
2187 * @hba: per adapter instance
2188 * @lrbp: pointer to local reference block
2189 */
2190static
2191int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2192{
2193 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2194
2195 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
2196
2197 /* Get the descriptor */
2198 if (hba->dev_cmd.query.descriptor &&
2199 lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
2200 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
2201 GENERAL_UPIU_REQUEST_SIZE;
2202 u16 resp_len;
2203 u16 buf_len;
2204
2205 /* data segment length */
2206 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
2207 MASK_QUERY_DATA_SEG_LEN;
2208 buf_len = be16_to_cpu(
2209 hba->dev_cmd.query.request.upiu_req.length);
2210 if (likely(buf_len >= resp_len)) {
2211 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
2212 } else {
2213 dev_warn(hba->dev,
2214 "%s: rsp size %d is bigger than buffer size %d",
2215 __func__, resp_len, buf_len);
2216 return -EINVAL;
2217 }
2218 }
2219
2220 return 0;
2221}
2222
2223/**
2224 * ufshcd_hba_capabilities - Read controller capabilities
2225 * @hba: per adapter instance
2226 *
2227 * Return: 0 on success, negative on error.
2228 */
2229static inline int ufshcd_hba_capabilities(struct ufs_hba *hba)
2230{
2231 int err;
2232
2233 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
2234 if (hba->quirks & UFSHCD_QUIRK_BROKEN_64BIT_ADDRESS)
2235 hba->capabilities &= ~MASK_64_ADDRESSING_SUPPORT;
2236
2237 /* nutrs and nutmrs are 0 based values */
2238 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
2239 hba->nutmrs =
2240 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
2241 hba->reserved_slot = hba->nutrs - 1;
2242
2243 /* Read crypto capabilities */
2244 err = ufshcd_hba_init_crypto_capabilities(hba);
2245 if (err)
2246 dev_err(hba->dev, "crypto setup failed\n");
2247
2248 return err;
2249}
2250
2251/**
2252 * ufshcd_ready_for_uic_cmd - Check if controller is ready
2253 * to accept UIC commands
2254 * @hba: per adapter instance
2255 * Return true on success, else false
2256 */
2257static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
2258{
2259 return ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY;
2260}
2261
2262/**
2263 * ufshcd_get_upmcrs - Get the power mode change request status
2264 * @hba: Pointer to adapter instance
2265 *
2266 * This function gets the UPMCRS field of HCS register
2267 * Returns value of UPMCRS field
2268 */
2269static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
2270{
2271 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
2272}
2273
2274/**
2275 * ufshcd_dispatch_uic_cmd - Dispatch an UIC command to the Unipro layer
2276 * @hba: per adapter instance
2277 * @uic_cmd: UIC command
2278 */
2279static inline void
2280ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2281{
2282 lockdep_assert_held(&hba->uic_cmd_mutex);
2283
2284 WARN_ON(hba->active_uic_cmd);
2285
2286 hba->active_uic_cmd = uic_cmd;
2287
2288 /* Write Args */
2289 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
2290 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
2291 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
2292
2293 ufshcd_add_uic_command_trace(hba, uic_cmd, UFS_CMD_SEND);
2294
2295 /* Write UIC Cmd */
2296 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
2297 REG_UIC_COMMAND);
2298}
2299
2300/**
2301 * ufshcd_wait_for_uic_cmd - Wait for completion of an UIC command
2302 * @hba: per adapter instance
2303 * @uic_cmd: UIC command
2304 *
2305 * Returns 0 only if success.
2306 */
2307static int
2308ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2309{
2310 int ret;
2311 unsigned long flags;
2312
2313 lockdep_assert_held(&hba->uic_cmd_mutex);
2314
2315 if (wait_for_completion_timeout(&uic_cmd->done,
2316 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2317 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2318 } else {
2319 ret = -ETIMEDOUT;
2320 dev_err(hba->dev,
2321 "uic cmd 0x%x with arg3 0x%x completion timeout\n",
2322 uic_cmd->command, uic_cmd->argument3);
2323
2324 if (!uic_cmd->cmd_active) {
2325 dev_err(hba->dev, "%s: UIC cmd has been completed, return the result\n",
2326 __func__);
2327 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
2328 }
2329 }
2330
2331 spin_lock_irqsave(hba->host->host_lock, flags);
2332 hba->active_uic_cmd = NULL;
2333 spin_unlock_irqrestore(hba->host->host_lock, flags);
2334
2335 return ret;
2336}
2337
2338/**
2339 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2340 * @hba: per adapter instance
2341 * @uic_cmd: UIC command
2342 * @completion: initialize the completion only if this is set to true
2343 *
2344 * Returns 0 only if success.
2345 */
2346static int
2347__ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
2348 bool completion)
2349{
2350 lockdep_assert_held(&hba->uic_cmd_mutex);
2351 lockdep_assert_held(hba->host->host_lock);
2352
2353 if (!ufshcd_ready_for_uic_cmd(hba)) {
2354 dev_err(hba->dev,
2355 "Controller not ready to accept UIC commands\n");
2356 return -EIO;
2357 }
2358
2359 if (completion)
2360 init_completion(&uic_cmd->done);
2361
2362 uic_cmd->cmd_active = 1;
2363 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
2364
2365 return 0;
2366}
2367
2368/**
2369 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
2370 * @hba: per adapter instance
2371 * @uic_cmd: UIC command
2372 *
2373 * Returns 0 only if success.
2374 */
2375int ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
2376{
2377 int ret;
2378 unsigned long flags;
2379
2380 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
2381 return 0;
2382
2383 ufshcd_hold(hba, false);
2384 mutex_lock(&hba->uic_cmd_mutex);
2385 ufshcd_add_delay_before_dme_cmd(hba);
2386
2387 spin_lock_irqsave(hba->host->host_lock, flags);
2388 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
2389 spin_unlock_irqrestore(hba->host->host_lock, flags);
2390 if (!ret)
2391 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
2392
2393 mutex_unlock(&hba->uic_cmd_mutex);
2394
2395 ufshcd_release(hba);
2396 return ret;
2397}
2398
2399/**
2400 * ufshcd_map_sg - Map scatter-gather list to prdt
2401 * @hba: per adapter instance
2402 * @lrbp: pointer to local reference block
2403 *
2404 * Returns 0 in case of success, non-zero value in case of failure
2405 */
2406static int ufshcd_map_sg(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2407{
2408 struct ufshcd_sg_entry *prd_table;
2409 struct scatterlist *sg;
2410 struct scsi_cmnd *cmd;
2411 int sg_segments;
2412 int i;
2413
2414 cmd = lrbp->cmd;
2415 sg_segments = scsi_dma_map(cmd);
2416 if (sg_segments < 0)
2417 return sg_segments;
2418
2419 if (sg_segments) {
2420
2421 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN)
2422 lrbp->utr_descriptor_ptr->prd_table_length =
2423 cpu_to_le16((sg_segments *
2424 sizeof(struct ufshcd_sg_entry)));
2425 else
2426 lrbp->utr_descriptor_ptr->prd_table_length =
2427 cpu_to_le16(sg_segments);
2428
2429 prd_table = lrbp->ucd_prdt_ptr;
2430
2431 scsi_for_each_sg(cmd, sg, sg_segments, i) {
2432 const unsigned int len = sg_dma_len(sg);
2433
2434 /*
2435 * From the UFSHCI spec: "Data Byte Count (DBC): A '0'
2436 * based value that indicates the length, in bytes, of
2437 * the data block. A maximum of length of 256KB may
2438 * exist for any entry. Bits 1:0 of this field shall be
2439 * 11b to indicate Dword granularity. A value of '3'
2440 * indicates 4 bytes, '7' indicates 8 bytes, etc."
2441 */
2442 WARN_ONCE(len > 256 * 1024, "len = %#x\n", len);
2443 prd_table[i].size = cpu_to_le32(len - 1);
2444 prd_table[i].addr = cpu_to_le64(sg->dma_address);
2445 prd_table[i].reserved = 0;
2446 }
2447 } else {
2448 lrbp->utr_descriptor_ptr->prd_table_length = 0;
2449 }
2450
2451 return 0;
2452}
2453
2454/**
2455 * ufshcd_enable_intr - enable interrupts
2456 * @hba: per adapter instance
2457 * @intrs: interrupt bits
2458 */
2459static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
2460{
2461 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2462
2463 if (hba->ufs_version == ufshci_version(1, 0)) {
2464 u32 rw;
2465 rw = set & INTERRUPT_MASK_RW_VER_10;
2466 set = rw | ((set ^ intrs) & intrs);
2467 } else {
2468 set |= intrs;
2469 }
2470
2471 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2472}
2473
2474/**
2475 * ufshcd_disable_intr - disable interrupts
2476 * @hba: per adapter instance
2477 * @intrs: interrupt bits
2478 */
2479static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
2480{
2481 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
2482
2483 if (hba->ufs_version == ufshci_version(1, 0)) {
2484 u32 rw;
2485 rw = (set & INTERRUPT_MASK_RW_VER_10) &
2486 ~(intrs & INTERRUPT_MASK_RW_VER_10);
2487 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
2488
2489 } else {
2490 set &= ~intrs;
2491 }
2492
2493 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
2494}
2495
2496/**
2497 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
2498 * descriptor according to request
2499 * @lrbp: pointer to local reference block
2500 * @upiu_flags: flags required in the header
2501 * @cmd_dir: requests data direction
2502 */
2503static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
2504 u8 *upiu_flags, enum dma_data_direction cmd_dir)
2505{
2506 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
2507 u32 data_direction;
2508 u32 dword_0;
2509 u32 dword_1 = 0;
2510 u32 dword_3 = 0;
2511
2512 if (cmd_dir == DMA_FROM_DEVICE) {
2513 data_direction = UTP_DEVICE_TO_HOST;
2514 *upiu_flags = UPIU_CMD_FLAGS_READ;
2515 } else if (cmd_dir == DMA_TO_DEVICE) {
2516 data_direction = UTP_HOST_TO_DEVICE;
2517 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
2518 } else {
2519 data_direction = UTP_NO_DATA_TRANSFER;
2520 *upiu_flags = UPIU_CMD_FLAGS_NONE;
2521 }
2522
2523 dword_0 = data_direction | (lrbp->command_type
2524 << UPIU_COMMAND_TYPE_OFFSET);
2525 if (lrbp->intr_cmd)
2526 dword_0 |= UTP_REQ_DESC_INT_CMD;
2527
2528 /* Prepare crypto related dwords */
2529 ufshcd_prepare_req_desc_hdr_crypto(lrbp, &dword_0, &dword_1, &dword_3);
2530
2531 /* Transfer request descriptor header fields */
2532 req_desc->header.dword_0 = cpu_to_le32(dword_0);
2533 req_desc->header.dword_1 = cpu_to_le32(dword_1);
2534 /*
2535 * assigning invalid value for command status. Controller
2536 * updates OCS on command completion, with the command
2537 * status
2538 */
2539 req_desc->header.dword_2 =
2540 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2541 req_desc->header.dword_3 = cpu_to_le32(dword_3);
2542
2543 req_desc->prd_table_length = 0;
2544}
2545
2546/**
2547 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
2548 * for scsi commands
2549 * @lrbp: local reference block pointer
2550 * @upiu_flags: flags
2551 */
2552static
2553void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u8 upiu_flags)
2554{
2555 struct scsi_cmnd *cmd = lrbp->cmd;
2556 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2557 unsigned short cdb_len;
2558
2559 /* command descriptor fields */
2560 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2561 UPIU_TRANSACTION_COMMAND, upiu_flags,
2562 lrbp->lun, lrbp->task_tag);
2563 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2564 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
2565
2566 /* Total EHS length and Data segment length will be zero */
2567 ucd_req_ptr->header.dword_2 = 0;
2568
2569 ucd_req_ptr->sc.exp_data_transfer_len = cpu_to_be32(cmd->sdb.length);
2570
2571 cdb_len = min_t(unsigned short, cmd->cmd_len, UFS_CDB_SIZE);
2572 memset(ucd_req_ptr->sc.cdb, 0, UFS_CDB_SIZE);
2573 memcpy(ucd_req_ptr->sc.cdb, cmd->cmnd, cdb_len);
2574
2575 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2576}
2577
2578/**
2579 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
2580 * for query requsts
2581 * @hba: UFS hba
2582 * @lrbp: local reference block pointer
2583 * @upiu_flags: flags
2584 */
2585static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
2586 struct ufshcd_lrb *lrbp, u8 upiu_flags)
2587{
2588 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2589 struct ufs_query *query = &hba->dev_cmd.query;
2590 u16 len = be16_to_cpu(query->request.upiu_req.length);
2591
2592 /* Query request header */
2593 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
2594 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
2595 lrbp->lun, lrbp->task_tag);
2596 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
2597 0, query->request.query_func, 0, 0);
2598
2599 /* Data segment length only need for WRITE_DESC */
2600 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2601 ucd_req_ptr->header.dword_2 =
2602 UPIU_HEADER_DWORD(0, 0, (len >> 8), (u8)len);
2603 else
2604 ucd_req_ptr->header.dword_2 = 0;
2605
2606 /* Copy the Query Request buffer as is */
2607 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
2608 QUERY_OSF_SIZE);
2609
2610 /* Copy the Descriptor */
2611 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
2612 memcpy(ucd_req_ptr + 1, query->descriptor, len);
2613
2614 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2615}
2616
2617static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
2618{
2619 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
2620
2621 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
2622
2623 /* command descriptor fields */
2624 ucd_req_ptr->header.dword_0 =
2625 UPIU_HEADER_DWORD(
2626 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
2627 /* clear rest of the fields of basic header */
2628 ucd_req_ptr->header.dword_1 = 0;
2629 ucd_req_ptr->header.dword_2 = 0;
2630
2631 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
2632}
2633
2634/**
2635 * ufshcd_compose_devman_upiu - UFS Protocol Information Unit(UPIU)
2636 * for Device Management Purposes
2637 * @hba: per adapter instance
2638 * @lrbp: pointer to local reference block
2639 */
2640static int ufshcd_compose_devman_upiu(struct ufs_hba *hba,
2641 struct ufshcd_lrb *lrbp)
2642{
2643 u8 upiu_flags;
2644 int ret = 0;
2645
2646 if (hba->ufs_version <= ufshci_version(1, 1))
2647 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
2648 else
2649 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2650
2651 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
2652 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
2653 ufshcd_prepare_utp_query_req_upiu(hba, lrbp, upiu_flags);
2654 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
2655 ufshcd_prepare_utp_nop_upiu(lrbp);
2656 else
2657 ret = -EINVAL;
2658
2659 return ret;
2660}
2661
2662/**
2663 * ufshcd_comp_scsi_upiu - UFS Protocol Information Unit(UPIU)
2664 * for SCSI Purposes
2665 * @hba: per adapter instance
2666 * @lrbp: pointer to local reference block
2667 */
2668static int ufshcd_comp_scsi_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2669{
2670 u8 upiu_flags;
2671 int ret = 0;
2672
2673 if (hba->ufs_version <= ufshci_version(1, 1))
2674 lrbp->command_type = UTP_CMD_TYPE_SCSI;
2675 else
2676 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
2677
2678 if (likely(lrbp->cmd)) {
2679 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
2680 lrbp->cmd->sc_data_direction);
2681 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
2682 } else {
2683 ret = -EINVAL;
2684 }
2685
2686 return ret;
2687}
2688
2689/**
2690 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
2691 * @upiu_wlun_id: UPIU W-LUN id
2692 *
2693 * Returns SCSI W-LUN id
2694 */
2695static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
2696{
2697 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
2698}
2699
2700static inline bool is_device_wlun(struct scsi_device *sdev)
2701{
2702 return sdev->lun ==
2703 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN);
2704}
2705
2706/*
2707 * Associate the UFS controller queue with the default and poll HCTX types.
2708 * Initialize the mq_map[] arrays.
2709 */
2710static void ufshcd_map_queues(struct Scsi_Host *shost)
2711{
2712 int i;
2713
2714 for (i = 0; i < shost->nr_maps; i++) {
2715 struct blk_mq_queue_map *map = &shost->tag_set.map[i];
2716
2717 switch (i) {
2718 case HCTX_TYPE_DEFAULT:
2719 case HCTX_TYPE_POLL:
2720 map->nr_queues = 1;
2721 break;
2722 case HCTX_TYPE_READ:
2723 map->nr_queues = 0;
2724 continue;
2725 default:
2726 WARN_ON_ONCE(true);
2727 }
2728 map->queue_offset = 0;
2729 blk_mq_map_queues(map);
2730 }
2731}
2732
2733static void ufshcd_init_lrb(struct ufs_hba *hba, struct ufshcd_lrb *lrb, int i)
2734{
2735 struct utp_transfer_cmd_desc *cmd_descp = hba->ucdl_base_addr;
2736 struct utp_transfer_req_desc *utrdlp = hba->utrdl_base_addr;
2737 dma_addr_t cmd_desc_element_addr = hba->ucdl_dma_addr +
2738 i * sizeof(struct utp_transfer_cmd_desc);
2739 u16 response_offset = offsetof(struct utp_transfer_cmd_desc,
2740 response_upiu);
2741 u16 prdt_offset = offsetof(struct utp_transfer_cmd_desc, prd_table);
2742
2743 lrb->utr_descriptor_ptr = utrdlp + i;
2744 lrb->utrd_dma_addr = hba->utrdl_dma_addr +
2745 i * sizeof(struct utp_transfer_req_desc);
2746 lrb->ucd_req_ptr = (struct utp_upiu_req *)(cmd_descp + i);
2747 lrb->ucd_req_dma_addr = cmd_desc_element_addr;
2748 lrb->ucd_rsp_ptr = (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2749 lrb->ucd_rsp_dma_addr = cmd_desc_element_addr + response_offset;
2750 lrb->ucd_prdt_ptr = cmd_descp[i].prd_table;
2751 lrb->ucd_prdt_dma_addr = cmd_desc_element_addr + prdt_offset;
2752}
2753
2754/**
2755 * ufshcd_queuecommand - main entry point for SCSI requests
2756 * @host: SCSI host pointer
2757 * @cmd: command from SCSI Midlayer
2758 *
2759 * Returns 0 for success, non-zero in case of failure
2760 */
2761static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
2762{
2763 struct ufs_hba *hba = shost_priv(host);
2764 int tag = scsi_cmd_to_rq(cmd)->tag;
2765 struct ufshcd_lrb *lrbp;
2766 int err = 0;
2767
2768 WARN_ONCE(tag < 0 || tag >= hba->nutrs, "Invalid tag %d\n", tag);
2769
2770 /*
2771 * Allows the UFS error handler to wait for prior ufshcd_queuecommand()
2772 * calls.
2773 */
2774 rcu_read_lock();
2775
2776 switch (hba->ufshcd_state) {
2777 case UFSHCD_STATE_OPERATIONAL:
2778 break;
2779 case UFSHCD_STATE_EH_SCHEDULED_NON_FATAL:
2780 /*
2781 * SCSI error handler can call ->queuecommand() while UFS error
2782 * handler is in progress. Error interrupts could change the
2783 * state from UFSHCD_STATE_RESET to
2784 * UFSHCD_STATE_EH_SCHEDULED_NON_FATAL. Prevent requests
2785 * being issued in that case.
2786 */
2787 if (ufshcd_eh_in_progress(hba)) {
2788 err = SCSI_MLQUEUE_HOST_BUSY;
2789 goto out;
2790 }
2791 break;
2792 case UFSHCD_STATE_EH_SCHEDULED_FATAL:
2793 /*
2794 * pm_runtime_get_sync() is used at error handling preparation
2795 * stage. If a scsi cmd, e.g. the SSU cmd, is sent from hba's
2796 * PM ops, it can never be finished if we let SCSI layer keep
2797 * retrying it, which gets err handler stuck forever. Neither
2798 * can we let the scsi cmd pass through, because UFS is in bad
2799 * state, the scsi cmd may eventually time out, which will get
2800 * err handler blocked for too long. So, just fail the scsi cmd
2801 * sent from PM ops, err handler can recover PM error anyways.
2802 */
2803 if (hba->pm_op_in_progress) {
2804 hba->force_reset = true;
2805 set_host_byte(cmd, DID_BAD_TARGET);
2806 scsi_done(cmd);
2807 goto out;
2808 }
2809 fallthrough;
2810 case UFSHCD_STATE_RESET:
2811 err = SCSI_MLQUEUE_HOST_BUSY;
2812 goto out;
2813 case UFSHCD_STATE_ERROR:
2814 set_host_byte(cmd, DID_ERROR);
2815 scsi_done(cmd);
2816 goto out;
2817 }
2818
2819 hba->req_abort_count = 0;
2820
2821 err = ufshcd_hold(hba, true);
2822 if (err) {
2823 err = SCSI_MLQUEUE_HOST_BUSY;
2824 goto out;
2825 }
2826 WARN_ON(ufshcd_is_clkgating_allowed(hba) &&
2827 (hba->clk_gating.state != CLKS_ON));
2828
2829 lrbp = &hba->lrb[tag];
2830 WARN_ON(lrbp->cmd);
2831 lrbp->cmd = cmd;
2832 lrbp->task_tag = tag;
2833 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
2834 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba);
2835
2836 ufshcd_prepare_lrbp_crypto(scsi_cmd_to_rq(cmd), lrbp);
2837
2838 lrbp->req_abort_skip = false;
2839
2840 ufshpb_prep(hba, lrbp);
2841
2842 ufshcd_comp_scsi_upiu(hba, lrbp);
2843
2844 err = ufshcd_map_sg(hba, lrbp);
2845 if (err) {
2846 lrbp->cmd = NULL;
2847 ufshcd_release(hba);
2848 goto out;
2849 }
2850
2851 ufshcd_send_command(hba, tag);
2852
2853out:
2854 rcu_read_unlock();
2855
2856 if (ufs_trigger_eh()) {
2857 unsigned long flags;
2858
2859 spin_lock_irqsave(hba->host->host_lock, flags);
2860 ufshcd_schedule_eh_work(hba);
2861 spin_unlock_irqrestore(hba->host->host_lock, flags);
2862 }
2863
2864 return err;
2865}
2866
2867static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
2868 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
2869{
2870 lrbp->cmd = NULL;
2871 lrbp->task_tag = tag;
2872 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
2873 lrbp->intr_cmd = true; /* No interrupt aggregation */
2874 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
2875 hba->dev_cmd.type = cmd_type;
2876
2877 return ufshcd_compose_devman_upiu(hba, lrbp);
2878}
2879
2880/*
2881 * Clear all the requests from the controller for which a bit has been set in
2882 * @mask and wait until the controller confirms that these requests have been
2883 * cleared.
2884 */
2885static int ufshcd_clear_cmds(struct ufs_hba *hba, u32 mask)
2886{
2887 unsigned long flags;
2888
2889 /* clear outstanding transaction before retry */
2890 spin_lock_irqsave(hba->host->host_lock, flags);
2891 ufshcd_utrl_clear(hba, mask);
2892 spin_unlock_irqrestore(hba->host->host_lock, flags);
2893
2894 /*
2895 * wait for h/w to clear corresponding bit in door-bell.
2896 * max. wait is 1 sec.
2897 */
2898 return ufshcd_wait_for_register(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL,
2899 mask, ~mask, 1000, 1000);
2900}
2901
2902static int
2903ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2904{
2905 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
2906
2907 /* Get the UPIU response */
2908 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
2909 UPIU_RSP_CODE_OFFSET;
2910 return query_res->response;
2911}
2912
2913/**
2914 * ufshcd_dev_cmd_completion() - handles device management command responses
2915 * @hba: per adapter instance
2916 * @lrbp: pointer to local reference block
2917 */
2918static int
2919ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2920{
2921 int resp;
2922 int err = 0;
2923
2924 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
2925 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2926
2927 switch (resp) {
2928 case UPIU_TRANSACTION_NOP_IN:
2929 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
2930 err = -EINVAL;
2931 dev_err(hba->dev, "%s: unexpected response %x\n",
2932 __func__, resp);
2933 }
2934 break;
2935 case UPIU_TRANSACTION_QUERY_RSP:
2936 err = ufshcd_check_query_response(hba, lrbp);
2937 if (!err)
2938 err = ufshcd_copy_query_response(hba, lrbp);
2939 break;
2940 case UPIU_TRANSACTION_REJECT_UPIU:
2941 /* TODO: handle Reject UPIU Response */
2942 err = -EPERM;
2943 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
2944 __func__);
2945 break;
2946 default:
2947 err = -EINVAL;
2948 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
2949 __func__, resp);
2950 break;
2951 }
2952
2953 return err;
2954}
2955
2956static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
2957 struct ufshcd_lrb *lrbp, int max_timeout)
2958{
2959 unsigned long time_left = msecs_to_jiffies(max_timeout);
2960 unsigned long flags;
2961 bool pending;
2962 int err;
2963
2964retry:
2965 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
2966 time_left);
2967
2968 if (likely(time_left)) {
2969 /*
2970 * The completion handler called complete() and the caller of
2971 * this function still owns the @lrbp tag so the code below does
2972 * not trigger any race conditions.
2973 */
2974 hba->dev_cmd.complete = NULL;
2975 err = ufshcd_get_tr_ocs(lrbp);
2976 if (!err)
2977 err = ufshcd_dev_cmd_completion(hba, lrbp);
2978 } else {
2979 err = -ETIMEDOUT;
2980 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
2981 __func__, lrbp->task_tag);
2982 if (ufshcd_clear_cmds(hba, 1U << lrbp->task_tag) == 0) {
2983 /* successfully cleared the command, retry if needed */
2984 err = -EAGAIN;
2985 /*
2986 * Since clearing the command succeeded we also need to
2987 * clear the task tag bit from the outstanding_reqs
2988 * variable.
2989 */
2990 spin_lock_irqsave(&hba->outstanding_lock, flags);
2991 pending = test_bit(lrbp->task_tag,
2992 &hba->outstanding_reqs);
2993 if (pending) {
2994 hba->dev_cmd.complete = NULL;
2995 __clear_bit(lrbp->task_tag,
2996 &hba->outstanding_reqs);
2997 }
2998 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
2999
3000 if (!pending) {
3001 /*
3002 * The completion handler ran while we tried to
3003 * clear the command.
3004 */
3005 time_left = 1;
3006 goto retry;
3007 }
3008 } else {
3009 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3010 __func__, lrbp->task_tag);
3011 }
3012 }
3013
3014 return err;
3015}
3016
3017/**
3018 * ufshcd_exec_dev_cmd - API for sending device management requests
3019 * @hba: UFS hba
3020 * @cmd_type: specifies the type (NOP, Query...)
3021 * @timeout: timeout in milliseconds
3022 *
3023 * NOTE: Since there is only one available tag for device management commands,
3024 * it is expected you hold the hba->dev_cmd.lock mutex.
3025 */
3026static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3027 enum dev_cmd_type cmd_type, int timeout)
3028{
3029 DECLARE_COMPLETION_ONSTACK(wait);
3030 const u32 tag = hba->reserved_slot;
3031 struct ufshcd_lrb *lrbp;
3032 int err;
3033
3034 /* Protects use of hba->reserved_slot. */
3035 lockdep_assert_held(&hba->dev_cmd.lock);
3036
3037 down_read(&hba->clk_scaling_lock);
3038
3039 lrbp = &hba->lrb[tag];
3040 WARN_ON(lrbp->cmd);
3041 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3042 if (unlikely(err))
3043 goto out;
3044
3045 hba->dev_cmd.complete = &wait;
3046
3047 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3048
3049 ufshcd_send_command(hba, tag);
3050 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3051 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3052 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3053
3054out:
3055 up_read(&hba->clk_scaling_lock);
3056 return err;
3057}
3058
3059/**
3060 * ufshcd_init_query() - init the query response and request parameters
3061 * @hba: per-adapter instance
3062 * @request: address of the request pointer to be initialized
3063 * @response: address of the response pointer to be initialized
3064 * @opcode: operation to perform
3065 * @idn: flag idn to access
3066 * @index: LU number to access
3067 * @selector: query/flag/descriptor further identification
3068 */
3069static inline void ufshcd_init_query(struct ufs_hba *hba,
3070 struct ufs_query_req **request, struct ufs_query_res **response,
3071 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3072{
3073 *request = &hba->dev_cmd.query.request;
3074 *response = &hba->dev_cmd.query.response;
3075 memset(*request, 0, sizeof(struct ufs_query_req));
3076 memset(*response, 0, sizeof(struct ufs_query_res));
3077 (*request)->upiu_req.opcode = opcode;
3078 (*request)->upiu_req.idn = idn;
3079 (*request)->upiu_req.index = index;
3080 (*request)->upiu_req.selector = selector;
3081}
3082
3083static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3084 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3085{
3086 int ret;
3087 int retries;
3088
3089 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3090 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3091 if (ret)
3092 dev_dbg(hba->dev,
3093 "%s: failed with error %d, retries %d\n",
3094 __func__, ret, retries);
3095 else
3096 break;
3097 }
3098
3099 if (ret)
3100 dev_err(hba->dev,
3101 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3102 __func__, opcode, idn, ret, retries);
3103 return ret;
3104}
3105
3106/**
3107 * ufshcd_query_flag() - API function for sending flag query requests
3108 * @hba: per-adapter instance
3109 * @opcode: flag query to perform
3110 * @idn: flag idn to access
3111 * @index: flag index to access
3112 * @flag_res: the flag value after the query request completes
3113 *
3114 * Returns 0 for success, non-zero in case of failure
3115 */
3116int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3117 enum flag_idn idn, u8 index, bool *flag_res)
3118{
3119 struct ufs_query_req *request = NULL;
3120 struct ufs_query_res *response = NULL;
3121 int err, selector = 0;
3122 int timeout = QUERY_REQ_TIMEOUT;
3123
3124 BUG_ON(!hba);
3125
3126 ufshcd_hold(hba, false);
3127 mutex_lock(&hba->dev_cmd.lock);
3128 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3129 selector);
3130
3131 switch (opcode) {
3132 case UPIU_QUERY_OPCODE_SET_FLAG:
3133 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3134 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3135 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3136 break;
3137 case UPIU_QUERY_OPCODE_READ_FLAG:
3138 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3139 if (!flag_res) {
3140 /* No dummy reads */
3141 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3142 __func__);
3143 err = -EINVAL;
3144 goto out_unlock;
3145 }
3146 break;
3147 default:
3148 dev_err(hba->dev,
3149 "%s: Expected query flag opcode but got = %d\n",
3150 __func__, opcode);
3151 err = -EINVAL;
3152 goto out_unlock;
3153 }
3154
3155 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3156
3157 if (err) {
3158 dev_err(hba->dev,
3159 "%s: Sending flag query for idn %d failed, err = %d\n",
3160 __func__, idn, err);
3161 goto out_unlock;
3162 }
3163
3164 if (flag_res)
3165 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3166 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3167
3168out_unlock:
3169 mutex_unlock(&hba->dev_cmd.lock);
3170 ufshcd_release(hba);
3171 return err;
3172}
3173
3174/**
3175 * ufshcd_query_attr - API function for sending attribute requests
3176 * @hba: per-adapter instance
3177 * @opcode: attribute opcode
3178 * @idn: attribute idn to access
3179 * @index: index field
3180 * @selector: selector field
3181 * @attr_val: the attribute value after the query request completes
3182 *
3183 * Returns 0 for success, non-zero in case of failure
3184*/
3185int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3186 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3187{
3188 struct ufs_query_req *request = NULL;
3189 struct ufs_query_res *response = NULL;
3190 int err;
3191
3192 BUG_ON(!hba);
3193
3194 if (!attr_val) {
3195 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3196 __func__, opcode);
3197 return -EINVAL;
3198 }
3199
3200 ufshcd_hold(hba, false);
3201
3202 mutex_lock(&hba->dev_cmd.lock);
3203 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3204 selector);
3205
3206 switch (opcode) {
3207 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3208 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3209 request->upiu_req.value = cpu_to_be32(*attr_val);
3210 break;
3211 case UPIU_QUERY_OPCODE_READ_ATTR:
3212 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3213 break;
3214 default:
3215 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3216 __func__, opcode);
3217 err = -EINVAL;
3218 goto out_unlock;
3219 }
3220
3221 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3222
3223 if (err) {
3224 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3225 __func__, opcode, idn, index, err);
3226 goto out_unlock;
3227 }
3228
3229 *attr_val = be32_to_cpu(response->upiu_res.value);
3230
3231out_unlock:
3232 mutex_unlock(&hba->dev_cmd.lock);
3233 ufshcd_release(hba);
3234 return err;
3235}
3236
3237/**
3238 * ufshcd_query_attr_retry() - API function for sending query
3239 * attribute with retries
3240 * @hba: per-adapter instance
3241 * @opcode: attribute opcode
3242 * @idn: attribute idn to access
3243 * @index: index field
3244 * @selector: selector field
3245 * @attr_val: the attribute value after the query request
3246 * completes
3247 *
3248 * Returns 0 for success, non-zero in case of failure
3249*/
3250int ufshcd_query_attr_retry(struct ufs_hba *hba,
3251 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3252 u32 *attr_val)
3253{
3254 int ret = 0;
3255 u32 retries;
3256
3257 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3258 ret = ufshcd_query_attr(hba, opcode, idn, index,
3259 selector, attr_val);
3260 if (ret)
3261 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3262 __func__, ret, retries);
3263 else
3264 break;
3265 }
3266
3267 if (ret)
3268 dev_err(hba->dev,
3269 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3270 __func__, idn, ret, QUERY_REQ_RETRIES);
3271 return ret;
3272}
3273
3274static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3275 enum query_opcode opcode, enum desc_idn idn, u8 index,
3276 u8 selector, u8 *desc_buf, int *buf_len)
3277{
3278 struct ufs_query_req *request = NULL;
3279 struct ufs_query_res *response = NULL;
3280 int err;
3281
3282 BUG_ON(!hba);
3283
3284 if (!desc_buf) {
3285 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3286 __func__, opcode);
3287 return -EINVAL;
3288 }
3289
3290 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3291 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3292 __func__, *buf_len);
3293 return -EINVAL;
3294 }
3295
3296 ufshcd_hold(hba, false);
3297
3298 mutex_lock(&hba->dev_cmd.lock);
3299 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3300 selector);
3301 hba->dev_cmd.query.descriptor = desc_buf;
3302 request->upiu_req.length = cpu_to_be16(*buf_len);
3303
3304 switch (opcode) {
3305 case UPIU_QUERY_OPCODE_WRITE_DESC:
3306 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3307 break;
3308 case UPIU_QUERY_OPCODE_READ_DESC:
3309 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3310 break;
3311 default:
3312 dev_err(hba->dev,
3313 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3314 __func__, opcode);
3315 err = -EINVAL;
3316 goto out_unlock;
3317 }
3318
3319 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3320
3321 if (err) {
3322 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3323 __func__, opcode, idn, index, err);
3324 goto out_unlock;
3325 }
3326
3327 *buf_len = be16_to_cpu(response->upiu_res.length);
3328
3329out_unlock:
3330 hba->dev_cmd.query.descriptor = NULL;
3331 mutex_unlock(&hba->dev_cmd.lock);
3332 ufshcd_release(hba);
3333 return err;
3334}
3335
3336/**
3337 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3338 * @hba: per-adapter instance
3339 * @opcode: attribute opcode
3340 * @idn: attribute idn to access
3341 * @index: index field
3342 * @selector: selector field
3343 * @desc_buf: the buffer that contains the descriptor
3344 * @buf_len: length parameter passed to the device
3345 *
3346 * Returns 0 for success, non-zero in case of failure.
3347 * The buf_len parameter will contain, on return, the length parameter
3348 * received on the response.
3349 */
3350int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3351 enum query_opcode opcode,
3352 enum desc_idn idn, u8 index,
3353 u8 selector,
3354 u8 *desc_buf, int *buf_len)
3355{
3356 int err;
3357 int retries;
3358
3359 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3360 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3361 selector, desc_buf, buf_len);
3362 if (!err || err == -EINVAL)
3363 break;
3364 }
3365
3366 return err;
3367}
3368
3369/**
3370 * ufshcd_map_desc_id_to_length - map descriptor IDN to its length
3371 * @hba: Pointer to adapter instance
3372 * @desc_id: descriptor idn value
3373 * @desc_len: mapped desc length (out)
3374 */
3375void ufshcd_map_desc_id_to_length(struct ufs_hba *hba, enum desc_idn desc_id,
3376 int *desc_len)
3377{
3378 if (desc_id >= QUERY_DESC_IDN_MAX || desc_id == QUERY_DESC_IDN_RFU_0 ||
3379 desc_id == QUERY_DESC_IDN_RFU_1)
3380 *desc_len = 0;
3381 else
3382 *desc_len = hba->desc_size[desc_id];
3383}
3384EXPORT_SYMBOL(ufshcd_map_desc_id_to_length);
3385
3386static void ufshcd_update_desc_length(struct ufs_hba *hba,
3387 enum desc_idn desc_id, int desc_index,
3388 unsigned char desc_len)
3389{
3390 if (hba->desc_size[desc_id] == QUERY_DESC_MAX_SIZE &&
3391 desc_id != QUERY_DESC_IDN_STRING && desc_index != UFS_RPMB_UNIT)
3392 /* For UFS 3.1, the normal unit descriptor is 10 bytes larger
3393 * than the RPMB unit, however, both descriptors share the same
3394 * desc_idn, to cover both unit descriptors with one length, we
3395 * choose the normal unit descriptor length by desc_index.
3396 */
3397 hba->desc_size[desc_id] = desc_len;
3398}
3399
3400/**
3401 * ufshcd_read_desc_param - read the specified descriptor parameter
3402 * @hba: Pointer to adapter instance
3403 * @desc_id: descriptor idn value
3404 * @desc_index: descriptor index
3405 * @param_offset: offset of the parameter to read
3406 * @param_read_buf: pointer to buffer where parameter would be read
3407 * @param_size: sizeof(param_read_buf)
3408 *
3409 * Return 0 in case of success, non-zero otherwise
3410 */
3411int ufshcd_read_desc_param(struct ufs_hba *hba,
3412 enum desc_idn desc_id,
3413 int desc_index,
3414 u8 param_offset,
3415 u8 *param_read_buf,
3416 u8 param_size)
3417{
3418 int ret;
3419 u8 *desc_buf;
3420 int buff_len;
3421 bool is_kmalloc = true;
3422
3423 /* Safety check */
3424 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3425 return -EINVAL;
3426
3427 /* Get the length of descriptor */
3428 ufshcd_map_desc_id_to_length(hba, desc_id, &buff_len);
3429 if (!buff_len) {
3430 dev_err(hba->dev, "%s: Failed to get desc length\n", __func__);
3431 return -EINVAL;
3432 }
3433
3434 if (param_offset >= buff_len) {
3435 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3436 __func__, param_offset, desc_id, buff_len);
3437 return -EINVAL;
3438 }
3439
3440 /* Check whether we need temp memory */
3441 if (param_offset != 0 || param_size < buff_len) {
3442 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3443 if (!desc_buf)
3444 return -ENOMEM;
3445 } else {
3446 desc_buf = param_read_buf;
3447 is_kmalloc = false;
3448 }
3449
3450 /* Request for full descriptor */
3451 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3452 desc_id, desc_index, 0,
3453 desc_buf, &buff_len);
3454
3455 if (ret) {
3456 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3457 __func__, desc_id, desc_index, param_offset, ret);
3458 goto out;
3459 }
3460
3461 /* Sanity check */
3462 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3463 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3464 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3465 ret = -EINVAL;
3466 goto out;
3467 }
3468
3469 /* Update descriptor length */
3470 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3471 ufshcd_update_desc_length(hba, desc_id, desc_index, buff_len);
3472
3473 if (is_kmalloc) {
3474 /* Make sure we don't copy more data than available */
3475 if (param_offset >= buff_len)
3476 ret = -EINVAL;
3477 else
3478 memcpy(param_read_buf, &desc_buf[param_offset],
3479 min_t(u32, param_size, buff_len - param_offset));
3480 }
3481out:
3482 if (is_kmalloc)
3483 kfree(desc_buf);
3484 return ret;
3485}
3486
3487/**
3488 * struct uc_string_id - unicode string
3489 *
3490 * @len: size of this descriptor inclusive
3491 * @type: descriptor type
3492 * @uc: unicode string character
3493 */
3494struct uc_string_id {
3495 u8 len;
3496 u8 type;
3497 wchar_t uc[];
3498} __packed;
3499
3500/* replace non-printable or non-ASCII characters with spaces */
3501static inline char ufshcd_remove_non_printable(u8 ch)
3502{
3503 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3504}
3505
3506/**
3507 * ufshcd_read_string_desc - read string descriptor
3508 * @hba: pointer to adapter instance
3509 * @desc_index: descriptor index
3510 * @buf: pointer to buffer where descriptor would be read,
3511 * the caller should free the memory.
3512 * @ascii: if true convert from unicode to ascii characters
3513 * null terminated string.
3514 *
3515 * Return:
3516 * * string size on success.
3517 * * -ENOMEM: on allocation failure
3518 * * -EINVAL: on a wrong parameter
3519 */
3520int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3521 u8 **buf, bool ascii)
3522{
3523 struct uc_string_id *uc_str;
3524 u8 *str;
3525 int ret;
3526
3527 if (!buf)
3528 return -EINVAL;
3529
3530 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3531 if (!uc_str)
3532 return -ENOMEM;
3533
3534 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3535 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3536 if (ret < 0) {
3537 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3538 QUERY_REQ_RETRIES, ret);
3539 str = NULL;
3540 goto out;
3541 }
3542
3543 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3544 dev_dbg(hba->dev, "String Desc is of zero length\n");
3545 str = NULL;
3546 ret = 0;
3547 goto out;
3548 }
3549
3550 if (ascii) {
3551 ssize_t ascii_len;
3552 int i;
3553 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3554 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3555 str = kzalloc(ascii_len, GFP_KERNEL);
3556 if (!str) {
3557 ret = -ENOMEM;
3558 goto out;
3559 }
3560
3561 /*
3562 * the descriptor contains string in UTF16 format
3563 * we need to convert to utf-8 so it can be displayed
3564 */
3565 ret = utf16s_to_utf8s(uc_str->uc,
3566 uc_str->len - QUERY_DESC_HDR_SIZE,
3567 UTF16_BIG_ENDIAN, str, ascii_len);
3568
3569 /* replace non-printable or non-ASCII characters with spaces */
3570 for (i = 0; i < ret; i++)
3571 str[i] = ufshcd_remove_non_printable(str[i]);
3572
3573 str[ret++] = '\0';
3574
3575 } else {
3576 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3577 if (!str) {
3578 ret = -ENOMEM;
3579 goto out;
3580 }
3581 ret = uc_str->len;
3582 }
3583out:
3584 *buf = str;
3585 kfree(uc_str);
3586 return ret;
3587}
3588
3589/**
3590 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3591 * @hba: Pointer to adapter instance
3592 * @lun: lun id
3593 * @param_offset: offset of the parameter to read
3594 * @param_read_buf: pointer to buffer where parameter would be read
3595 * @param_size: sizeof(param_read_buf)
3596 *
3597 * Return 0 in case of success, non-zero otherwise
3598 */
3599static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3600 int lun,
3601 enum unit_desc_param param_offset,
3602 u8 *param_read_buf,
3603 u32 param_size)
3604{
3605 /*
3606 * Unit descriptors are only available for general purpose LUs (LUN id
3607 * from 0 to 7) and RPMB Well known LU.
3608 */
3609 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3610 return -EOPNOTSUPP;
3611
3612 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3613 param_offset, param_read_buf, param_size);
3614}
3615
3616static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3617{
3618 int err = 0;
3619 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3620
3621 if (hba->dev_info.wspecversion >= 0x300) {
3622 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3623 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3624 &gating_wait);
3625 if (err)
3626 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3627 err, gating_wait);
3628
3629 if (gating_wait == 0) {
3630 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3631 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3632 gating_wait);
3633 }
3634
3635 hba->dev_info.clk_gating_wait_us = gating_wait;
3636 }
3637
3638 return err;
3639}
3640
3641/**
3642 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3643 * @hba: per adapter instance
3644 *
3645 * 1. Allocate DMA memory for Command Descriptor array
3646 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3647 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3648 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3649 * (UTMRDL)
3650 * 4. Allocate memory for local reference block(lrb).
3651 *
3652 * Returns 0 for success, non-zero in case of failure
3653 */
3654static int ufshcd_memory_alloc(struct ufs_hba *hba)
3655{
3656 size_t utmrdl_size, utrdl_size, ucdl_size;
3657
3658 /* Allocate memory for UTP command descriptors */
3659 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
3660 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3661 ucdl_size,
3662 &hba->ucdl_dma_addr,
3663 GFP_KERNEL);
3664
3665 /*
3666 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3667 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
3668 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
3669 * be aligned to 128 bytes as well
3670 */
3671 if (!hba->ucdl_base_addr ||
3672 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3673 dev_err(hba->dev,
3674 "Command Descriptor Memory allocation failed\n");
3675 goto out;
3676 }
3677
3678 /*
3679 * Allocate memory for UTP Transfer descriptors
3680 * UFSHCI requires 1024 byte alignment of UTRD
3681 */
3682 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3683 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3684 utrdl_size,
3685 &hba->utrdl_dma_addr,
3686 GFP_KERNEL);
3687 if (!hba->utrdl_base_addr ||
3688 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3689 dev_err(hba->dev,
3690 "Transfer Descriptor Memory allocation failed\n");
3691 goto out;
3692 }
3693
3694 /*
3695 * Allocate memory for UTP Task Management descriptors
3696 * UFSHCI requires 1024 byte alignment of UTMRD
3697 */
3698 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3699 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3700 utmrdl_size,
3701 &hba->utmrdl_dma_addr,
3702 GFP_KERNEL);
3703 if (!hba->utmrdl_base_addr ||
3704 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3705 dev_err(hba->dev,
3706 "Task Management Descriptor Memory allocation failed\n");
3707 goto out;
3708 }
3709
3710 /* Allocate memory for local reference block */
3711 hba->lrb = devm_kcalloc(hba->dev,
3712 hba->nutrs, sizeof(struct ufshcd_lrb),
3713 GFP_KERNEL);
3714 if (!hba->lrb) {
3715 dev_err(hba->dev, "LRB Memory allocation failed\n");
3716 goto out;
3717 }
3718 return 0;
3719out:
3720 return -ENOMEM;
3721}
3722
3723/**
3724 * ufshcd_host_memory_configure - configure local reference block with
3725 * memory offsets
3726 * @hba: per adapter instance
3727 *
3728 * Configure Host memory space
3729 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3730 * address.
3731 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3732 * and PRDT offset.
3733 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3734 * into local reference block.
3735 */
3736static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3737{
3738 struct utp_transfer_req_desc *utrdlp;
3739 dma_addr_t cmd_desc_dma_addr;
3740 dma_addr_t cmd_desc_element_addr;
3741 u16 response_offset;
3742 u16 prdt_offset;
3743 int cmd_desc_size;
3744 int i;
3745
3746 utrdlp = hba->utrdl_base_addr;
3747
3748 response_offset =
3749 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3750 prdt_offset =
3751 offsetof(struct utp_transfer_cmd_desc, prd_table);
3752
3753 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
3754 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3755
3756 for (i = 0; i < hba->nutrs; i++) {
3757 /* Configure UTRD with command descriptor base address */
3758 cmd_desc_element_addr =
3759 (cmd_desc_dma_addr + (cmd_desc_size * i));
3760 utrdlp[i].command_desc_base_addr_lo =
3761 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
3762 utrdlp[i].command_desc_base_addr_hi =
3763 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
3764
3765 /* Response upiu and prdt offset should be in double words */
3766 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3767 utrdlp[i].response_upiu_offset =
3768 cpu_to_le16(response_offset);
3769 utrdlp[i].prd_table_offset =
3770 cpu_to_le16(prdt_offset);
3771 utrdlp[i].response_upiu_length =
3772 cpu_to_le16(ALIGNED_UPIU_SIZE);
3773 } else {
3774 utrdlp[i].response_upiu_offset =
3775 cpu_to_le16(response_offset >> 2);
3776 utrdlp[i].prd_table_offset =
3777 cpu_to_le16(prdt_offset >> 2);
3778 utrdlp[i].response_upiu_length =
3779 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3780 }
3781
3782 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3783 }
3784}
3785
3786/**
3787 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3788 * @hba: per adapter instance
3789 *
3790 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3791 * in order to initialize the Unipro link startup procedure.
3792 * Once the Unipro links are up, the device connected to the controller
3793 * is detected.
3794 *
3795 * Returns 0 on success, non-zero value on failure
3796 */
3797static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3798{
3799 struct uic_command uic_cmd = {0};
3800 int ret;
3801
3802 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3803
3804 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3805 if (ret)
3806 dev_dbg(hba->dev,
3807 "dme-link-startup: error code %d\n", ret);
3808 return ret;
3809}
3810/**
3811 * ufshcd_dme_reset - UIC command for DME_RESET
3812 * @hba: per adapter instance
3813 *
3814 * DME_RESET command is issued in order to reset UniPro stack.
3815 * This function now deals with cold reset.
3816 *
3817 * Returns 0 on success, non-zero value on failure
3818 */
3819static int ufshcd_dme_reset(struct ufs_hba *hba)
3820{
3821 struct uic_command uic_cmd = {0};
3822 int ret;
3823
3824 uic_cmd.command = UIC_CMD_DME_RESET;
3825
3826 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3827 if (ret)
3828 dev_err(hba->dev,
3829 "dme-reset: error code %d\n", ret);
3830
3831 return ret;
3832}
3833
3834int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3835 int agreed_gear,
3836 int adapt_val)
3837{
3838 int ret;
3839
3840 if (agreed_gear < UFS_HS_G4)
3841 adapt_val = PA_NO_ADAPT;
3842
3843 ret = ufshcd_dme_set(hba,
3844 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3845 adapt_val);
3846 return ret;
3847}
3848EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3849
3850/**
3851 * ufshcd_dme_enable - UIC command for DME_ENABLE
3852 * @hba: per adapter instance
3853 *
3854 * DME_ENABLE command is issued in order to enable UniPro stack.
3855 *
3856 * Returns 0 on success, non-zero value on failure
3857 */
3858static int ufshcd_dme_enable(struct ufs_hba *hba)
3859{
3860 struct uic_command uic_cmd = {0};
3861 int ret;
3862
3863 uic_cmd.command = UIC_CMD_DME_ENABLE;
3864
3865 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3866 if (ret)
3867 dev_err(hba->dev,
3868 "dme-enable: error code %d\n", ret);
3869
3870 return ret;
3871}
3872
3873static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3874{
3875 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3876 unsigned long min_sleep_time_us;
3877
3878 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3879 return;
3880
3881 /*
3882 * last_dme_cmd_tstamp will be 0 only for 1st call to
3883 * this function
3884 */
3885 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3886 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3887 } else {
3888 unsigned long delta =
3889 (unsigned long) ktime_to_us(
3890 ktime_sub(ktime_get(),
3891 hba->last_dme_cmd_tstamp));
3892
3893 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3894 min_sleep_time_us =
3895 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3896 else
3897 return; /* no more delay required */
3898 }
3899
3900 /* allow sleep for extra 50us if needed */
3901 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
3902}
3903
3904/**
3905 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
3906 * @hba: per adapter instance
3907 * @attr_sel: uic command argument1
3908 * @attr_set: attribute set type as uic command argument2
3909 * @mib_val: setting value as uic command argument3
3910 * @peer: indicate whether peer or local
3911 *
3912 * Returns 0 on success, non-zero value on failure
3913 */
3914int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
3915 u8 attr_set, u32 mib_val, u8 peer)
3916{
3917 struct uic_command uic_cmd = {0};
3918 static const char *const action[] = {
3919 "dme-set",
3920 "dme-peer-set"
3921 };
3922 const char *set = action[!!peer];
3923 int ret;
3924 int retries = UFS_UIC_COMMAND_RETRIES;
3925
3926 uic_cmd.command = peer ?
3927 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
3928 uic_cmd.argument1 = attr_sel;
3929 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
3930 uic_cmd.argument3 = mib_val;
3931
3932 do {
3933 /* for peer attributes we retry upon failure */
3934 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3935 if (ret)
3936 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
3937 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
3938 } while (ret && peer && --retries);
3939
3940 if (ret)
3941 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
3942 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
3943 UFS_UIC_COMMAND_RETRIES - retries);
3944
3945 return ret;
3946}
3947EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
3948
3949/**
3950 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
3951 * @hba: per adapter instance
3952 * @attr_sel: uic command argument1
3953 * @mib_val: the value of the attribute as returned by the UIC command
3954 * @peer: indicate whether peer or local
3955 *
3956 * Returns 0 on success, non-zero value on failure
3957 */
3958int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
3959 u32 *mib_val, u8 peer)
3960{
3961 struct uic_command uic_cmd = {0};
3962 static const char *const action[] = {
3963 "dme-get",
3964 "dme-peer-get"
3965 };
3966 const char *get = action[!!peer];
3967 int ret;
3968 int retries = UFS_UIC_COMMAND_RETRIES;
3969 struct ufs_pa_layer_attr orig_pwr_info;
3970 struct ufs_pa_layer_attr temp_pwr_info;
3971 bool pwr_mode_change = false;
3972
3973 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
3974 orig_pwr_info = hba->pwr_info;
3975 temp_pwr_info = orig_pwr_info;
3976
3977 if (orig_pwr_info.pwr_tx == FAST_MODE ||
3978 orig_pwr_info.pwr_rx == FAST_MODE) {
3979 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
3980 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
3981 pwr_mode_change = true;
3982 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
3983 orig_pwr_info.pwr_rx == SLOW_MODE) {
3984 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
3985 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
3986 pwr_mode_change = true;
3987 }
3988 if (pwr_mode_change) {
3989 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
3990 if (ret)
3991 goto out;
3992 }
3993 }
3994
3995 uic_cmd.command = peer ?
3996 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
3997 uic_cmd.argument1 = attr_sel;
3998
3999 do {
4000 /* for peer attributes we retry upon failure */
4001 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4002 if (ret)
4003 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4004 get, UIC_GET_ATTR_ID(attr_sel), ret);
4005 } while (ret && peer && --retries);
4006
4007 if (ret)
4008 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4009 get, UIC_GET_ATTR_ID(attr_sel),
4010 UFS_UIC_COMMAND_RETRIES - retries);
4011
4012 if (mib_val && !ret)
4013 *mib_val = uic_cmd.argument3;
4014
4015 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4016 && pwr_mode_change)
4017 ufshcd_change_power_mode(hba, &orig_pwr_info);
4018out:
4019 return ret;
4020}
4021EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4022
4023/**
4024 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4025 * state) and waits for it to take effect.
4026 *
4027 * @hba: per adapter instance
4028 * @cmd: UIC command to execute
4029 *
4030 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4031 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4032 * and device UniPro link and hence it's final completion would be indicated by
4033 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4034 * addition to normal UIC command completion Status (UCCS). This function only
4035 * returns after the relevant status bits indicate the completion.
4036 *
4037 * Returns 0 on success, non-zero value on failure
4038 */
4039static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4040{
4041 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4042 unsigned long flags;
4043 u8 status;
4044 int ret;
4045 bool reenable_intr = false;
4046
4047 mutex_lock(&hba->uic_cmd_mutex);
4048 ufshcd_add_delay_before_dme_cmd(hba);
4049
4050 spin_lock_irqsave(hba->host->host_lock, flags);
4051 if (ufshcd_is_link_broken(hba)) {
4052 ret = -ENOLINK;
4053 goto out_unlock;
4054 }
4055 hba->uic_async_done = &uic_async_done;
4056 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4057 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4058 /*
4059 * Make sure UIC command completion interrupt is disabled before
4060 * issuing UIC command.
4061 */
4062 wmb();
4063 reenable_intr = true;
4064 }
4065 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
4066 spin_unlock_irqrestore(hba->host->host_lock, flags);
4067 if (ret) {
4068 dev_err(hba->dev,
4069 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4070 cmd->command, cmd->argument3, ret);
4071 goto out;
4072 }
4073
4074 if (!wait_for_completion_timeout(hba->uic_async_done,
4075 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4076 dev_err(hba->dev,
4077 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4078 cmd->command, cmd->argument3);
4079
4080 if (!cmd->cmd_active) {
4081 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4082 __func__);
4083 goto check_upmcrs;
4084 }
4085
4086 ret = -ETIMEDOUT;
4087 goto out;
4088 }
4089
4090check_upmcrs:
4091 status = ufshcd_get_upmcrs(hba);
4092 if (status != PWR_LOCAL) {
4093 dev_err(hba->dev,
4094 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4095 cmd->command, status);
4096 ret = (status != PWR_OK) ? status : -1;
4097 }
4098out:
4099 if (ret) {
4100 ufshcd_print_host_state(hba);
4101 ufshcd_print_pwr_info(hba);
4102 ufshcd_print_evt_hist(hba);
4103 }
4104
4105 spin_lock_irqsave(hba->host->host_lock, flags);
4106 hba->active_uic_cmd = NULL;
4107 hba->uic_async_done = NULL;
4108 if (reenable_intr)
4109 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4110 if (ret) {
4111 ufshcd_set_link_broken(hba);
4112 ufshcd_schedule_eh_work(hba);
4113 }
4114out_unlock:
4115 spin_unlock_irqrestore(hba->host->host_lock, flags);
4116 mutex_unlock(&hba->uic_cmd_mutex);
4117
4118 return ret;
4119}
4120
4121/**
4122 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4123 * using DME_SET primitives.
4124 * @hba: per adapter instance
4125 * @mode: powr mode value
4126 *
4127 * Returns 0 on success, non-zero value on failure
4128 */
4129int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4130{
4131 struct uic_command uic_cmd = {0};
4132 int ret;
4133
4134 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4135 ret = ufshcd_dme_set(hba,
4136 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4137 if (ret) {
4138 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4139 __func__, ret);
4140 goto out;
4141 }
4142 }
4143
4144 uic_cmd.command = UIC_CMD_DME_SET;
4145 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4146 uic_cmd.argument3 = mode;
4147 ufshcd_hold(hba, false);
4148 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4149 ufshcd_release(hba);
4150
4151out:
4152 return ret;
4153}
4154EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4155
4156int ufshcd_link_recovery(struct ufs_hba *hba)
4157{
4158 int ret;
4159 unsigned long flags;
4160
4161 spin_lock_irqsave(hba->host->host_lock, flags);
4162 hba->ufshcd_state = UFSHCD_STATE_RESET;
4163 ufshcd_set_eh_in_progress(hba);
4164 spin_unlock_irqrestore(hba->host->host_lock, flags);
4165
4166 /* Reset the attached device */
4167 ufshcd_device_reset(hba);
4168
4169 ret = ufshcd_host_reset_and_restore(hba);
4170
4171 spin_lock_irqsave(hba->host->host_lock, flags);
4172 if (ret)
4173 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4174 ufshcd_clear_eh_in_progress(hba);
4175 spin_unlock_irqrestore(hba->host->host_lock, flags);
4176
4177 if (ret)
4178 dev_err(hba->dev, "%s: link recovery failed, err %d",
4179 __func__, ret);
4180
4181 return ret;
4182}
4183EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4184
4185int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4186{
4187 int ret;
4188 struct uic_command uic_cmd = {0};
4189 ktime_t start = ktime_get();
4190
4191 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4192
4193 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4194 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4195 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4196 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4197
4198 if (ret)
4199 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4200 __func__, ret);
4201 else
4202 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4203 POST_CHANGE);
4204
4205 return ret;
4206}
4207EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4208
4209int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4210{
4211 struct uic_command uic_cmd = {0};
4212 int ret;
4213 ktime_t start = ktime_get();
4214
4215 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4216
4217 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4218 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4219 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4220 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4221
4222 if (ret) {
4223 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4224 __func__, ret);
4225 } else {
4226 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4227 POST_CHANGE);
4228 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4229 hba->ufs_stats.hibern8_exit_cnt++;
4230 }
4231
4232 return ret;
4233}
4234EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4235
4236void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4237{
4238 unsigned long flags;
4239 bool update = false;
4240
4241 if (!ufshcd_is_auto_hibern8_supported(hba))
4242 return;
4243
4244 spin_lock_irqsave(hba->host->host_lock, flags);
4245 if (hba->ahit != ahit) {
4246 hba->ahit = ahit;
4247 update = true;
4248 }
4249 spin_unlock_irqrestore(hba->host->host_lock, flags);
4250
4251 if (update &&
4252 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4253 ufshcd_rpm_get_sync(hba);
4254 ufshcd_hold(hba, false);
4255 ufshcd_auto_hibern8_enable(hba);
4256 ufshcd_release(hba);
4257 ufshcd_rpm_put_sync(hba);
4258 }
4259}
4260EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4261
4262void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4263{
4264 if (!ufshcd_is_auto_hibern8_supported(hba))
4265 return;
4266
4267 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4268}
4269
4270 /**
4271 * ufshcd_init_pwr_info - setting the POR (power on reset)
4272 * values in hba power info
4273 * @hba: per-adapter instance
4274 */
4275static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4276{
4277 hba->pwr_info.gear_rx = UFS_PWM_G1;
4278 hba->pwr_info.gear_tx = UFS_PWM_G1;
4279 hba->pwr_info.lane_rx = 1;
4280 hba->pwr_info.lane_tx = 1;
4281 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4282 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4283 hba->pwr_info.hs_rate = 0;
4284}
4285
4286/**
4287 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4288 * @hba: per-adapter instance
4289 */
4290static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4291{
4292 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4293
4294 if (hba->max_pwr_info.is_valid)
4295 return 0;
4296
4297 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4298 pwr_info->pwr_tx = FASTAUTO_MODE;
4299 pwr_info->pwr_rx = FASTAUTO_MODE;
4300 } else {
4301 pwr_info->pwr_tx = FAST_MODE;
4302 pwr_info->pwr_rx = FAST_MODE;
4303 }
4304 pwr_info->hs_rate = PA_HS_MODE_B;
4305
4306 /* Get the connected lane count */
4307 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4308 &pwr_info->lane_rx);
4309 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4310 &pwr_info->lane_tx);
4311
4312 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4313 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4314 __func__,
4315 pwr_info->lane_rx,
4316 pwr_info->lane_tx);
4317 return -EINVAL;
4318 }
4319
4320 /*
4321 * First, get the maximum gears of HS speed.
4322 * If a zero value, it means there is no HSGEAR capability.
4323 * Then, get the maximum gears of PWM speed.
4324 */
4325 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4326 if (!pwr_info->gear_rx) {
4327 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4328 &pwr_info->gear_rx);
4329 if (!pwr_info->gear_rx) {
4330 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4331 __func__, pwr_info->gear_rx);
4332 return -EINVAL;
4333 }
4334 pwr_info->pwr_rx = SLOW_MODE;
4335 }
4336
4337 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4338 &pwr_info->gear_tx);
4339 if (!pwr_info->gear_tx) {
4340 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4341 &pwr_info->gear_tx);
4342 if (!pwr_info->gear_tx) {
4343 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4344 __func__, pwr_info->gear_tx);
4345 return -EINVAL;
4346 }
4347 pwr_info->pwr_tx = SLOW_MODE;
4348 }
4349
4350 hba->max_pwr_info.is_valid = true;
4351 return 0;
4352}
4353
4354static int ufshcd_change_power_mode(struct ufs_hba *hba,
4355 struct ufs_pa_layer_attr *pwr_mode)
4356{
4357 int ret;
4358
4359 /* if already configured to the requested pwr_mode */
4360 if (!hba->force_pmc &&
4361 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4362 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4363 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4364 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4365 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4366 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4367 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4368 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4369 return 0;
4370 }
4371
4372 /*
4373 * Configure attributes for power mode change with below.
4374 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4375 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4376 * - PA_HSSERIES
4377 */
4378 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4379 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4380 pwr_mode->lane_rx);
4381 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4382 pwr_mode->pwr_rx == FAST_MODE)
4383 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4384 else
4385 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4386
4387 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4388 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4389 pwr_mode->lane_tx);
4390 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4391 pwr_mode->pwr_tx == FAST_MODE)
4392 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4393 else
4394 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4395
4396 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4397 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4398 pwr_mode->pwr_rx == FAST_MODE ||
4399 pwr_mode->pwr_tx == FAST_MODE)
4400 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4401 pwr_mode->hs_rate);
4402
4403 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4404 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4405 DL_FC0ProtectionTimeOutVal_Default);
4406 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4407 DL_TC0ReplayTimeOutVal_Default);
4408 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4409 DL_AFC0ReqTimeOutVal_Default);
4410 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4411 DL_FC1ProtectionTimeOutVal_Default);
4412 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4413 DL_TC1ReplayTimeOutVal_Default);
4414 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4415 DL_AFC1ReqTimeOutVal_Default);
4416
4417 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4418 DL_FC0ProtectionTimeOutVal_Default);
4419 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4420 DL_TC0ReplayTimeOutVal_Default);
4421 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4422 DL_AFC0ReqTimeOutVal_Default);
4423 }
4424
4425 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4426 | pwr_mode->pwr_tx);
4427
4428 if (ret) {
4429 dev_err(hba->dev,
4430 "%s: power mode change failed %d\n", __func__, ret);
4431 } else {
4432 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4433 pwr_mode);
4434
4435 memcpy(&hba->pwr_info, pwr_mode,
4436 sizeof(struct ufs_pa_layer_attr));
4437 }
4438
4439 return ret;
4440}
4441
4442/**
4443 * ufshcd_config_pwr_mode - configure a new power mode
4444 * @hba: per-adapter instance
4445 * @desired_pwr_mode: desired power configuration
4446 */
4447int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4448 struct ufs_pa_layer_attr *desired_pwr_mode)
4449{
4450 struct ufs_pa_layer_attr final_params = { 0 };
4451 int ret;
4452
4453 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4454 desired_pwr_mode, &final_params);
4455
4456 if (ret)
4457 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4458
4459 ret = ufshcd_change_power_mode(hba, &final_params);
4460
4461 return ret;
4462}
4463EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4464
4465/**
4466 * ufshcd_complete_dev_init() - checks device readiness
4467 * @hba: per-adapter instance
4468 *
4469 * Set fDeviceInit flag and poll until device toggles it.
4470 */
4471static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4472{
4473 int err;
4474 bool flag_res = true;
4475 ktime_t timeout;
4476
4477 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4478 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4479 if (err) {
4480 dev_err(hba->dev,
4481 "%s: setting fDeviceInit flag failed with error %d\n",
4482 __func__, err);
4483 goto out;
4484 }
4485
4486 /* Poll fDeviceInit flag to be cleared */
4487 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4488 do {
4489 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4490 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4491 if (!flag_res)
4492 break;
4493 usleep_range(500, 1000);
4494 } while (ktime_before(ktime_get(), timeout));
4495
4496 if (err) {
4497 dev_err(hba->dev,
4498 "%s: reading fDeviceInit flag failed with error %d\n",
4499 __func__, err);
4500 } else if (flag_res) {
4501 dev_err(hba->dev,
4502 "%s: fDeviceInit was not cleared by the device\n",
4503 __func__);
4504 err = -EBUSY;
4505 }
4506out:
4507 return err;
4508}
4509
4510/**
4511 * ufshcd_make_hba_operational - Make UFS controller operational
4512 * @hba: per adapter instance
4513 *
4514 * To bring UFS host controller to operational state,
4515 * 1. Enable required interrupts
4516 * 2. Configure interrupt aggregation
4517 * 3. Program UTRL and UTMRL base address
4518 * 4. Configure run-stop-registers
4519 *
4520 * Returns 0 on success, non-zero value on failure
4521 */
4522int ufshcd_make_hba_operational(struct ufs_hba *hba)
4523{
4524 int err = 0;
4525 u32 reg;
4526
4527 /* Enable required interrupts */
4528 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4529
4530 /* Configure interrupt aggregation */
4531 if (ufshcd_is_intr_aggr_allowed(hba))
4532 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4533 else
4534 ufshcd_disable_intr_aggr(hba);
4535
4536 /* Configure UTRL and UTMRL base address registers */
4537 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4538 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4539 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4540 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4541 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4542 REG_UTP_TASK_REQ_LIST_BASE_L);
4543 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4544 REG_UTP_TASK_REQ_LIST_BASE_H);
4545
4546 /*
4547 * Make sure base address and interrupt setup are updated before
4548 * enabling the run/stop registers below.
4549 */
4550 wmb();
4551
4552 /*
4553 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4554 */
4555 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4556 if (!(ufshcd_get_lists_status(reg))) {
4557 ufshcd_enable_run_stop_reg(hba);
4558 } else {
4559 dev_err(hba->dev,
4560 "Host controller not ready to process requests");
4561 err = -EIO;
4562 }
4563
4564 return err;
4565}
4566EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4567
4568/**
4569 * ufshcd_hba_stop - Send controller to reset state
4570 * @hba: per adapter instance
4571 */
4572void ufshcd_hba_stop(struct ufs_hba *hba)
4573{
4574 unsigned long flags;
4575 int err;
4576
4577 /*
4578 * Obtain the host lock to prevent that the controller is disabled
4579 * while the UFS interrupt handler is active on another CPU.
4580 */
4581 spin_lock_irqsave(hba->host->host_lock, flags);
4582 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4583 spin_unlock_irqrestore(hba->host->host_lock, flags);
4584
4585 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4586 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4587 10, 1);
4588 if (err)
4589 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4590}
4591EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4592
4593/**
4594 * ufshcd_hba_execute_hce - initialize the controller
4595 * @hba: per adapter instance
4596 *
4597 * The controller resets itself and controller firmware initialization
4598 * sequence kicks off. When controller is ready it will set
4599 * the Host Controller Enable bit to 1.
4600 *
4601 * Returns 0 on success, non-zero value on failure
4602 */
4603static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4604{
4605 int retry_outer = 3;
4606 int retry_inner;
4607
4608start:
4609 if (ufshcd_is_hba_active(hba))
4610 /* change controller state to "reset state" */
4611 ufshcd_hba_stop(hba);
4612
4613 /* UniPro link is disabled at this point */
4614 ufshcd_set_link_off(hba);
4615
4616 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4617
4618 /* start controller initialization sequence */
4619 ufshcd_hba_start(hba);
4620
4621 /*
4622 * To initialize a UFS host controller HCE bit must be set to 1.
4623 * During initialization the HCE bit value changes from 1->0->1.
4624 * When the host controller completes initialization sequence
4625 * it sets the value of HCE bit to 1. The same HCE bit is read back
4626 * to check if the controller has completed initialization sequence.
4627 * So without this delay the value HCE = 1, set in the previous
4628 * instruction might be read back.
4629 * This delay can be changed based on the controller.
4630 */
4631 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4632
4633 /* wait for the host controller to complete initialization */
4634 retry_inner = 50;
4635 while (!ufshcd_is_hba_active(hba)) {
4636 if (retry_inner) {
4637 retry_inner--;
4638 } else {
4639 dev_err(hba->dev,
4640 "Controller enable failed\n");
4641 if (retry_outer) {
4642 retry_outer--;
4643 goto start;
4644 }
4645 return -EIO;
4646 }
4647 usleep_range(1000, 1100);
4648 }
4649
4650 /* enable UIC related interrupts */
4651 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4652
4653 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4654
4655 return 0;
4656}
4657
4658int ufshcd_hba_enable(struct ufs_hba *hba)
4659{
4660 int ret;
4661
4662 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4663 ufshcd_set_link_off(hba);
4664 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4665
4666 /* enable UIC related interrupts */
4667 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4668 ret = ufshcd_dme_reset(hba);
4669 if (ret) {
4670 dev_err(hba->dev, "DME_RESET failed\n");
4671 return ret;
4672 }
4673
4674 ret = ufshcd_dme_enable(hba);
4675 if (ret) {
4676 dev_err(hba->dev, "Enabling DME failed\n");
4677 return ret;
4678 }
4679
4680 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4681 } else {
4682 ret = ufshcd_hba_execute_hce(hba);
4683 }
4684
4685 return ret;
4686}
4687EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4688
4689static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4690{
4691 int tx_lanes = 0, i, err = 0;
4692
4693 if (!peer)
4694 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4695 &tx_lanes);
4696 else
4697 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4698 &tx_lanes);
4699 for (i = 0; i < tx_lanes; i++) {
4700 if (!peer)
4701 err = ufshcd_dme_set(hba,
4702 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4703 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4704 0);
4705 else
4706 err = ufshcd_dme_peer_set(hba,
4707 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4708 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4709 0);
4710 if (err) {
4711 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4712 __func__, peer, i, err);
4713 break;
4714 }
4715 }
4716
4717 return err;
4718}
4719
4720static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4721{
4722 return ufshcd_disable_tx_lcc(hba, true);
4723}
4724
4725void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4726{
4727 struct ufs_event_hist *e;
4728
4729 if (id >= UFS_EVT_CNT)
4730 return;
4731
4732 e = &hba->ufs_stats.event[id];
4733 e->val[e->pos] = val;
4734 e->tstamp[e->pos] = local_clock();
4735 e->cnt += 1;
4736 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4737
4738 ufshcd_vops_event_notify(hba, id, &val);
4739}
4740EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4741
4742/**
4743 * ufshcd_link_startup - Initialize unipro link startup
4744 * @hba: per adapter instance
4745 *
4746 * Returns 0 for success, non-zero in case of failure
4747 */
4748static int ufshcd_link_startup(struct ufs_hba *hba)
4749{
4750 int ret;
4751 int retries = DME_LINKSTARTUP_RETRIES;
4752 bool link_startup_again = false;
4753
4754 /*
4755 * If UFS device isn't active then we will have to issue link startup
4756 * 2 times to make sure the device state move to active.
4757 */
4758 if (!ufshcd_is_ufs_dev_active(hba))
4759 link_startup_again = true;
4760
4761link_startup:
4762 do {
4763 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4764
4765 ret = ufshcd_dme_link_startup(hba);
4766
4767 /* check if device is detected by inter-connect layer */
4768 if (!ret && !ufshcd_is_device_present(hba)) {
4769 ufshcd_update_evt_hist(hba,
4770 UFS_EVT_LINK_STARTUP_FAIL,
4771 0);
4772 dev_err(hba->dev, "%s: Device not present\n", __func__);
4773 ret = -ENXIO;
4774 goto out;
4775 }
4776
4777 /*
4778 * DME link lost indication is only received when link is up,
4779 * but we can't be sure if the link is up until link startup
4780 * succeeds. So reset the local Uni-Pro and try again.
4781 */
4782 if (ret && retries && ufshcd_hba_enable(hba)) {
4783 ufshcd_update_evt_hist(hba,
4784 UFS_EVT_LINK_STARTUP_FAIL,
4785 (u32)ret);
4786 goto out;
4787 }
4788 } while (ret && retries--);
4789
4790 if (ret) {
4791 /* failed to get the link up... retire */
4792 ufshcd_update_evt_hist(hba,
4793 UFS_EVT_LINK_STARTUP_FAIL,
4794 (u32)ret);
4795 goto out;
4796 }
4797
4798 if (link_startup_again) {
4799 link_startup_again = false;
4800 retries = DME_LINKSTARTUP_RETRIES;
4801 goto link_startup;
4802 }
4803
4804 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4805 ufshcd_init_pwr_info(hba);
4806 ufshcd_print_pwr_info(hba);
4807
4808 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4809 ret = ufshcd_disable_device_tx_lcc(hba);
4810 if (ret)
4811 goto out;
4812 }
4813
4814 /* Include any host controller configuration via UIC commands */
4815 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4816 if (ret)
4817 goto out;
4818
4819 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4820 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4821 ret = ufshcd_make_hba_operational(hba);
4822out:
4823 if (ret) {
4824 dev_err(hba->dev, "link startup failed %d\n", ret);
4825 ufshcd_print_host_state(hba);
4826 ufshcd_print_pwr_info(hba);
4827 ufshcd_print_evt_hist(hba);
4828 }
4829 return ret;
4830}
4831
4832/**
4833 * ufshcd_verify_dev_init() - Verify device initialization
4834 * @hba: per-adapter instance
4835 *
4836 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4837 * device Transport Protocol (UTP) layer is ready after a reset.
4838 * If the UTP layer at the device side is not initialized, it may
4839 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4840 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4841 */
4842static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4843{
4844 int err = 0;
4845 int retries;
4846
4847 ufshcd_hold(hba, false);
4848 mutex_lock(&hba->dev_cmd.lock);
4849 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
4850 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
4851 hba->nop_out_timeout);
4852
4853 if (!err || err == -ETIMEDOUT)
4854 break;
4855
4856 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
4857 }
4858 mutex_unlock(&hba->dev_cmd.lock);
4859 ufshcd_release(hba);
4860
4861 if (err)
4862 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
4863 return err;
4864}
4865
4866/**
4867 * ufshcd_setup_links - associate link b/w device wlun and other luns
4868 * @sdev: pointer to SCSI device
4869 * @hba: pointer to ufs hba
4870 */
4871static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
4872{
4873 struct device_link *link;
4874
4875 /*
4876 * Device wlun is the supplier & rest of the luns are consumers.
4877 * This ensures that device wlun suspends after all other luns.
4878 */
4879 if (hba->ufs_device_wlun) {
4880 link = device_link_add(&sdev->sdev_gendev,
4881 &hba->ufs_device_wlun->sdev_gendev,
4882 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
4883 if (!link) {
4884 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
4885 dev_name(&hba->ufs_device_wlun->sdev_gendev));
4886 return;
4887 }
4888 hba->luns_avail--;
4889 /* Ignore REPORT_LUN wlun probing */
4890 if (hba->luns_avail == 1) {
4891 ufshcd_rpm_put(hba);
4892 return;
4893 }
4894 } else {
4895 /*
4896 * Device wlun is probed. The assumption is that WLUNs are
4897 * scanned before other LUNs.
4898 */
4899 hba->luns_avail--;
4900 }
4901}
4902
4903/**
4904 * ufshcd_lu_init - Initialize the relevant parameters of the LU
4905 * @hba: per-adapter instance
4906 * @sdev: pointer to SCSI device
4907 */
4908static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
4909{
4910 int len = hba->desc_size[QUERY_DESC_IDN_UNIT];
4911 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
4912 u8 lun_qdepth = hba->nutrs;
4913 u8 *desc_buf;
4914 int ret;
4915
4916 desc_buf = kzalloc(len, GFP_KERNEL);
4917 if (!desc_buf)
4918 goto set_qdepth;
4919
4920 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
4921 if (ret < 0) {
4922 if (ret == -EOPNOTSUPP)
4923 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
4924 lun_qdepth = 1;
4925 kfree(desc_buf);
4926 goto set_qdepth;
4927 }
4928
4929 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
4930 /*
4931 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
4932 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
4933 */
4934 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
4935 }
4936 /*
4937 * According to UFS device specification, the write protection mode is only supported by
4938 * normal LU, not supported by WLUN.
4939 */
4940 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
4941 !hba->dev_info.is_lu_power_on_wp &&
4942 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
4943 hba->dev_info.is_lu_power_on_wp = true;
4944
4945 kfree(desc_buf);
4946set_qdepth:
4947 /*
4948 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
4949 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
4950 */
4951 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
4952 scsi_change_queue_depth(sdev, lun_qdepth);
4953}
4954
4955/**
4956 * ufshcd_slave_alloc - handle initial SCSI device configurations
4957 * @sdev: pointer to SCSI device
4958 *
4959 * Returns success
4960 */
4961static int ufshcd_slave_alloc(struct scsi_device *sdev)
4962{
4963 struct ufs_hba *hba;
4964
4965 hba = shost_priv(sdev->host);
4966
4967 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
4968 sdev->use_10_for_ms = 1;
4969
4970 /* DBD field should be set to 1 in mode sense(10) */
4971 sdev->set_dbd_for_ms = 1;
4972
4973 /* allow SCSI layer to restart the device in case of errors */
4974 sdev->allow_restart = 1;
4975
4976 /* REPORT SUPPORTED OPERATION CODES is not supported */
4977 sdev->no_report_opcodes = 1;
4978
4979 /* WRITE_SAME command is not supported */
4980 sdev->no_write_same = 1;
4981
4982 ufshcd_lu_init(hba, sdev);
4983
4984 ufshcd_setup_links(hba, sdev);
4985
4986 return 0;
4987}
4988
4989/**
4990 * ufshcd_change_queue_depth - change queue depth
4991 * @sdev: pointer to SCSI device
4992 * @depth: required depth to set
4993 *
4994 * Change queue depth and make sure the max. limits are not crossed.
4995 */
4996static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4997{
4998 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
4999}
5000
5001static void ufshcd_hpb_destroy(struct ufs_hba *hba, struct scsi_device *sdev)
5002{
5003 /* skip well-known LU */
5004 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5005 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5006 return;
5007
5008 ufshpb_destroy_lu(hba, sdev);
5009}
5010
5011static void ufshcd_hpb_configure(struct ufs_hba *hba, struct scsi_device *sdev)
5012{
5013 /* skip well-known LU */
5014 if ((sdev->lun >= UFS_UPIU_MAX_UNIT_NUM_ID) ||
5015 !(hba->dev_info.hpb_enabled) || !ufshpb_is_allowed(hba))
5016 return;
5017
5018 ufshpb_init_hpb_lu(hba, sdev);
5019}
5020
5021/**
5022 * ufshcd_slave_configure - adjust SCSI device configurations
5023 * @sdev: pointer to SCSI device
5024 */
5025static int ufshcd_slave_configure(struct scsi_device *sdev)
5026{
5027 struct ufs_hba *hba = shost_priv(sdev->host);
5028 struct request_queue *q = sdev->request_queue;
5029
5030 ufshcd_hpb_configure(hba, sdev);
5031
5032 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5033 if (hba->quirks & UFSHCD_QUIRK_ALIGN_SG_WITH_PAGE_SIZE)
5034 blk_queue_update_dma_alignment(q, PAGE_SIZE - 1);
5035 /*
5036 * Block runtime-pm until all consumers are added.
5037 * Refer ufshcd_setup_links().
5038 */
5039 if (is_device_wlun(sdev))
5040 pm_runtime_get_noresume(&sdev->sdev_gendev);
5041 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5042 sdev->rpm_autosuspend = 1;
5043 /*
5044 * Do not print messages during runtime PM to avoid never-ending cycles
5045 * of messages written back to storage by user space causing runtime
5046 * resume, causing more messages and so on.
5047 */
5048 sdev->silence_suspend = 1;
5049
5050 ufshcd_crypto_register(hba, q);
5051
5052 return 0;
5053}
5054
5055/**
5056 * ufshcd_slave_destroy - remove SCSI device configurations
5057 * @sdev: pointer to SCSI device
5058 */
5059static void ufshcd_slave_destroy(struct scsi_device *sdev)
5060{
5061 struct ufs_hba *hba;
5062 unsigned long flags;
5063
5064 hba = shost_priv(sdev->host);
5065
5066 ufshcd_hpb_destroy(hba, sdev);
5067
5068 /* Drop the reference as it won't be needed anymore */
5069 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5070 spin_lock_irqsave(hba->host->host_lock, flags);
5071 hba->ufs_device_wlun = NULL;
5072 spin_unlock_irqrestore(hba->host->host_lock, flags);
5073 } else if (hba->ufs_device_wlun) {
5074 struct device *supplier = NULL;
5075
5076 /* Ensure UFS Device WLUN exists and does not disappear */
5077 spin_lock_irqsave(hba->host->host_lock, flags);
5078 if (hba->ufs_device_wlun) {
5079 supplier = &hba->ufs_device_wlun->sdev_gendev;
5080 get_device(supplier);
5081 }
5082 spin_unlock_irqrestore(hba->host->host_lock, flags);
5083
5084 if (supplier) {
5085 /*
5086 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5087 * device will not have been registered but can still
5088 * have a device link holding a reference to the device.
5089 */
5090 device_link_remove(&sdev->sdev_gendev, supplier);
5091 put_device(supplier);
5092 }
5093 }
5094}
5095
5096/**
5097 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5098 * @lrbp: pointer to local reference block of completed command
5099 * @scsi_status: SCSI command status
5100 *
5101 * Returns value base on SCSI command status
5102 */
5103static inline int
5104ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5105{
5106 int result = 0;
5107
5108 switch (scsi_status) {
5109 case SAM_STAT_CHECK_CONDITION:
5110 ufshcd_copy_sense_data(lrbp);
5111 fallthrough;
5112 case SAM_STAT_GOOD:
5113 result |= DID_OK << 16 | scsi_status;
5114 break;
5115 case SAM_STAT_TASK_SET_FULL:
5116 case SAM_STAT_BUSY:
5117 case SAM_STAT_TASK_ABORTED:
5118 ufshcd_copy_sense_data(lrbp);
5119 result |= scsi_status;
5120 break;
5121 default:
5122 result |= DID_ERROR << 16;
5123 break;
5124 } /* end of switch */
5125
5126 return result;
5127}
5128
5129/**
5130 * ufshcd_transfer_rsp_status - Get overall status of the response
5131 * @hba: per adapter instance
5132 * @lrbp: pointer to local reference block of completed command
5133 *
5134 * Returns result of the command to notify SCSI midlayer
5135 */
5136static inline int
5137ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
5138{
5139 int result = 0;
5140 int scsi_status;
5141 enum utp_ocs ocs;
5142
5143 /* overall command status of utrd */
5144 ocs = ufshcd_get_tr_ocs(lrbp);
5145
5146 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5147 if (be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_1) &
5148 MASK_RSP_UPIU_RESULT)
5149 ocs = OCS_SUCCESS;
5150 }
5151
5152 switch (ocs) {
5153 case OCS_SUCCESS:
5154 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
5155 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5156 switch (result) {
5157 case UPIU_TRANSACTION_RESPONSE:
5158 /*
5159 * get the response UPIU result to extract
5160 * the SCSI command status
5161 */
5162 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
5163
5164 /*
5165 * get the result based on SCSI status response
5166 * to notify the SCSI midlayer of the command status
5167 */
5168 scsi_status = result & MASK_SCSI_STATUS;
5169 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5170
5171 /*
5172 * Currently we are only supporting BKOPs exception
5173 * events hence we can ignore BKOPs exception event
5174 * during power management callbacks. BKOPs exception
5175 * event is not expected to be raised in runtime suspend
5176 * callback as it allows the urgent bkops.
5177 * During system suspend, we are anyway forcefully
5178 * disabling the bkops and if urgent bkops is needed
5179 * it will be enabled on system resume. Long term
5180 * solution could be to abort the system suspend if
5181 * UFS device needs urgent BKOPs.
5182 */
5183 if (!hba->pm_op_in_progress &&
5184 !ufshcd_eh_in_progress(hba) &&
5185 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5186 /* Flushed in suspend */
5187 schedule_work(&hba->eeh_work);
5188
5189 if (scsi_status == SAM_STAT_GOOD)
5190 ufshpb_rsp_upiu(hba, lrbp);
5191 break;
5192 case UPIU_TRANSACTION_REJECT_UPIU:
5193 /* TODO: handle Reject UPIU Response */
5194 result = DID_ERROR << 16;
5195 dev_err(hba->dev,
5196 "Reject UPIU not fully implemented\n");
5197 break;
5198 default:
5199 dev_err(hba->dev,
5200 "Unexpected request response code = %x\n",
5201 result);
5202 result = DID_ERROR << 16;
5203 break;
5204 }
5205 break;
5206 case OCS_ABORTED:
5207 result |= DID_ABORT << 16;
5208 break;
5209 case OCS_INVALID_COMMAND_STATUS:
5210 result |= DID_REQUEUE << 16;
5211 break;
5212 case OCS_INVALID_CMD_TABLE_ATTR:
5213 case OCS_INVALID_PRDT_ATTR:
5214 case OCS_MISMATCH_DATA_BUF_SIZE:
5215 case OCS_MISMATCH_RESP_UPIU_SIZE:
5216 case OCS_PEER_COMM_FAILURE:
5217 case OCS_FATAL_ERROR:
5218 case OCS_DEVICE_FATAL_ERROR:
5219 case OCS_INVALID_CRYPTO_CONFIG:
5220 case OCS_GENERAL_CRYPTO_ERROR:
5221 default:
5222 result |= DID_ERROR << 16;
5223 dev_err(hba->dev,
5224 "OCS error from controller = %x for tag %d\n",
5225 ocs, lrbp->task_tag);
5226 ufshcd_print_evt_hist(hba);
5227 ufshcd_print_host_state(hba);
5228 break;
5229 } /* end of switch */
5230
5231 if ((host_byte(result) != DID_OK) &&
5232 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5233 ufshcd_print_trs(hba, 1 << lrbp->task_tag, true);
5234 return result;
5235}
5236
5237static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5238 u32 intr_mask)
5239{
5240 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5241 !ufshcd_is_auto_hibern8_enabled(hba))
5242 return false;
5243
5244 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5245 return false;
5246
5247 if (hba->active_uic_cmd &&
5248 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5249 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5250 return false;
5251
5252 return true;
5253}
5254
5255/**
5256 * ufshcd_uic_cmd_compl - handle completion of uic command
5257 * @hba: per adapter instance
5258 * @intr_status: interrupt status generated by the controller
5259 *
5260 * Returns
5261 * IRQ_HANDLED - If interrupt is valid
5262 * IRQ_NONE - If invalid interrupt
5263 */
5264static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5265{
5266 irqreturn_t retval = IRQ_NONE;
5267
5268 spin_lock(hba->host->host_lock);
5269 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5270 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5271
5272 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5273 hba->active_uic_cmd->argument2 |=
5274 ufshcd_get_uic_cmd_result(hba);
5275 hba->active_uic_cmd->argument3 =
5276 ufshcd_get_dme_attr_val(hba);
5277 if (!hba->uic_async_done)
5278 hba->active_uic_cmd->cmd_active = 0;
5279 complete(&hba->active_uic_cmd->done);
5280 retval = IRQ_HANDLED;
5281 }
5282
5283 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5284 hba->active_uic_cmd->cmd_active = 0;
5285 complete(hba->uic_async_done);
5286 retval = IRQ_HANDLED;
5287 }
5288
5289 if (retval == IRQ_HANDLED)
5290 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5291 UFS_CMD_COMP);
5292 spin_unlock(hba->host->host_lock);
5293 return retval;
5294}
5295
5296/* Release the resources allocated for processing a SCSI command. */
5297static void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5298 struct ufshcd_lrb *lrbp)
5299{
5300 struct scsi_cmnd *cmd = lrbp->cmd;
5301
5302 scsi_dma_unmap(cmd);
5303 lrbp->cmd = NULL; /* Mark the command as completed. */
5304 ufshcd_release(hba);
5305 ufshcd_clk_scaling_update_busy(hba);
5306}
5307
5308/**
5309 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5310 * @hba: per adapter instance
5311 * @completed_reqs: bitmask that indicates which requests to complete
5312 */
5313static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5314 unsigned long completed_reqs)
5315{
5316 struct ufshcd_lrb *lrbp;
5317 struct scsi_cmnd *cmd;
5318 int index;
5319
5320 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
5321 lrbp = &hba->lrb[index];
5322 lrbp->compl_time_stamp = ktime_get();
5323 lrbp->compl_time_stamp_local_clock = local_clock();
5324 cmd = lrbp->cmd;
5325 if (cmd) {
5326 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5327 ufshcd_update_monitor(hba, lrbp);
5328 ufshcd_add_command_trace(hba, index, UFS_CMD_COMP);
5329 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp);
5330 ufshcd_release_scsi_cmd(hba, lrbp);
5331 /* Do not touch lrbp after scsi done */
5332 scsi_done(cmd);
5333 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5334 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5335 if (hba->dev_cmd.complete) {
5336 ufshcd_add_command_trace(hba, index,
5337 UFS_DEV_COMP);
5338 complete(hba->dev_cmd.complete);
5339 ufshcd_clk_scaling_update_busy(hba);
5340 }
5341 }
5342 }
5343}
5344
5345/* Any value that is not an existing queue number is fine for this constant. */
5346enum {
5347 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5348};
5349
5350static void ufshcd_clear_polled(struct ufs_hba *hba,
5351 unsigned long *completed_reqs)
5352{
5353 int tag;
5354
5355 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5356 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5357
5358 if (!cmd)
5359 continue;
5360 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5361 __clear_bit(tag, completed_reqs);
5362 }
5363}
5364
5365/*
5366 * Returns > 0 if one or more commands have been completed or 0 if no
5367 * requests have been completed.
5368 */
5369static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5370{
5371 struct ufs_hba *hba = shost_priv(shost);
5372 unsigned long completed_reqs, flags;
5373 u32 tr_doorbell;
5374
5375 spin_lock_irqsave(&hba->outstanding_lock, flags);
5376 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5377 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5378 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5379 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5380 hba->outstanding_reqs);
5381 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5382 /* Do not complete polled requests from interrupt context. */
5383 ufshcd_clear_polled(hba, &completed_reqs);
5384 }
5385 hba->outstanding_reqs &= ~completed_reqs;
5386 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5387
5388 if (completed_reqs)
5389 __ufshcd_transfer_req_compl(hba, completed_reqs);
5390
5391 return completed_reqs != 0;
5392}
5393
5394/**
5395 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5396 * @hba: per adapter instance
5397 *
5398 * Returns
5399 * IRQ_HANDLED - If interrupt is valid
5400 * IRQ_NONE - If invalid interrupt
5401 */
5402static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5403{
5404 /* Resetting interrupt aggregation counters first and reading the
5405 * DOOR_BELL afterward allows us to handle all the completed requests.
5406 * In order to prevent other interrupts starvation the DB is read once
5407 * after reset. The down side of this solution is the possibility of
5408 * false interrupt if device completes another request after resetting
5409 * aggregation and before reading the DB.
5410 */
5411 if (ufshcd_is_intr_aggr_allowed(hba) &&
5412 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5413 ufshcd_reset_intr_aggr(hba);
5414
5415 if (ufs_fail_completion())
5416 return IRQ_HANDLED;
5417
5418 /*
5419 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5420 * do not want polling to trigger spurious interrupt complaints.
5421 */
5422 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5423
5424 return IRQ_HANDLED;
5425}
5426
5427int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5428{
5429 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5430 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5431 &ee_ctrl_mask);
5432}
5433
5434int ufshcd_write_ee_control(struct ufs_hba *hba)
5435{
5436 int err;
5437
5438 mutex_lock(&hba->ee_ctrl_mutex);
5439 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5440 mutex_unlock(&hba->ee_ctrl_mutex);
5441 if (err)
5442 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5443 __func__, err);
5444 return err;
5445}
5446
5447int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5448 const u16 *other_mask, u16 set, u16 clr)
5449{
5450 u16 new_mask, ee_ctrl_mask;
5451 int err = 0;
5452
5453 mutex_lock(&hba->ee_ctrl_mutex);
5454 new_mask = (*mask & ~clr) | set;
5455 ee_ctrl_mask = new_mask | *other_mask;
5456 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5457 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5458 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5459 if (!err) {
5460 hba->ee_ctrl_mask = ee_ctrl_mask;
5461 *mask = new_mask;
5462 }
5463 mutex_unlock(&hba->ee_ctrl_mutex);
5464 return err;
5465}
5466
5467/**
5468 * ufshcd_disable_ee - disable exception event
5469 * @hba: per-adapter instance
5470 * @mask: exception event to disable
5471 *
5472 * Disables exception event in the device so that the EVENT_ALERT
5473 * bit is not set.
5474 *
5475 * Returns zero on success, non-zero error value on failure.
5476 */
5477static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5478{
5479 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5480}
5481
5482/**
5483 * ufshcd_enable_ee - enable exception event
5484 * @hba: per-adapter instance
5485 * @mask: exception event to enable
5486 *
5487 * Enable corresponding exception event in the device to allow
5488 * device to alert host in critical scenarios.
5489 *
5490 * Returns zero on success, non-zero error value on failure.
5491 */
5492static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5493{
5494 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5495}
5496
5497/**
5498 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5499 * @hba: per-adapter instance
5500 *
5501 * Allow device to manage background operations on its own. Enabling
5502 * this might lead to inconsistent latencies during normal data transfers
5503 * as the device is allowed to manage its own way of handling background
5504 * operations.
5505 *
5506 * Returns zero on success, non-zero on failure.
5507 */
5508static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5509{
5510 int err = 0;
5511
5512 if (hba->auto_bkops_enabled)
5513 goto out;
5514
5515 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5516 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5517 if (err) {
5518 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5519 __func__, err);
5520 goto out;
5521 }
5522
5523 hba->auto_bkops_enabled = true;
5524 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5525
5526 /* No need of URGENT_BKOPS exception from the device */
5527 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5528 if (err)
5529 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5530 __func__, err);
5531out:
5532 return err;
5533}
5534
5535/**
5536 * ufshcd_disable_auto_bkops - block device in doing background operations
5537 * @hba: per-adapter instance
5538 *
5539 * Disabling background operations improves command response latency but
5540 * has drawback of device moving into critical state where the device is
5541 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5542 * host is idle so that BKOPS are managed effectively without any negative
5543 * impacts.
5544 *
5545 * Returns zero on success, non-zero on failure.
5546 */
5547static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5548{
5549 int err = 0;
5550
5551 if (!hba->auto_bkops_enabled)
5552 goto out;
5553
5554 /*
5555 * If host assisted BKOPs is to be enabled, make sure
5556 * urgent bkops exception is allowed.
5557 */
5558 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5559 if (err) {
5560 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5561 __func__, err);
5562 goto out;
5563 }
5564
5565 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5566 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5567 if (err) {
5568 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5569 __func__, err);
5570 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5571 goto out;
5572 }
5573
5574 hba->auto_bkops_enabled = false;
5575 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5576 hba->is_urgent_bkops_lvl_checked = false;
5577out:
5578 return err;
5579}
5580
5581/**
5582 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5583 * @hba: per adapter instance
5584 *
5585 * After a device reset the device may toggle the BKOPS_EN flag
5586 * to default value. The s/w tracking variables should be updated
5587 * as well. This function would change the auto-bkops state based on
5588 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5589 */
5590static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5591{
5592 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5593 hba->auto_bkops_enabled = false;
5594 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5595 ufshcd_enable_auto_bkops(hba);
5596 } else {
5597 hba->auto_bkops_enabled = true;
5598 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5599 ufshcd_disable_auto_bkops(hba);
5600 }
5601 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5602 hba->is_urgent_bkops_lvl_checked = false;
5603}
5604
5605static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5606{
5607 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5608 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5609}
5610
5611/**
5612 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5613 * @hba: per-adapter instance
5614 * @status: bkops_status value
5615 *
5616 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5617 * flag in the device to permit background operations if the device
5618 * bkops_status is greater than or equal to "status" argument passed to
5619 * this function, disable otherwise.
5620 *
5621 * Returns 0 for success, non-zero in case of failure.
5622 *
5623 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5624 * to know whether auto bkops is enabled or disabled after this function
5625 * returns control to it.
5626 */
5627static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5628 enum bkops_status status)
5629{
5630 int err;
5631 u32 curr_status = 0;
5632
5633 err = ufshcd_get_bkops_status(hba, &curr_status);
5634 if (err) {
5635 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5636 __func__, err);
5637 goto out;
5638 } else if (curr_status > BKOPS_STATUS_MAX) {
5639 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5640 __func__, curr_status);
5641 err = -EINVAL;
5642 goto out;
5643 }
5644
5645 if (curr_status >= status)
5646 err = ufshcd_enable_auto_bkops(hba);
5647 else
5648 err = ufshcd_disable_auto_bkops(hba);
5649out:
5650 return err;
5651}
5652
5653/**
5654 * ufshcd_urgent_bkops - handle urgent bkops exception event
5655 * @hba: per-adapter instance
5656 *
5657 * Enable fBackgroundOpsEn flag in the device to permit background
5658 * operations.
5659 *
5660 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5661 * and negative error value for any other failure.
5662 */
5663static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5664{
5665 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5666}
5667
5668static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5669{
5670 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5671 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5672}
5673
5674static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5675{
5676 int err;
5677 u32 curr_status = 0;
5678
5679 if (hba->is_urgent_bkops_lvl_checked)
5680 goto enable_auto_bkops;
5681
5682 err = ufshcd_get_bkops_status(hba, &curr_status);
5683 if (err) {
5684 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5685 __func__, err);
5686 goto out;
5687 }
5688
5689 /*
5690 * We are seeing that some devices are raising the urgent bkops
5691 * exception events even when BKOPS status doesn't indicate performace
5692 * impacted or critical. Handle these device by determining their urgent
5693 * bkops status at runtime.
5694 */
5695 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5696 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5697 __func__, curr_status);
5698 /* update the current status as the urgent bkops level */
5699 hba->urgent_bkops_lvl = curr_status;
5700 hba->is_urgent_bkops_lvl_checked = true;
5701 }
5702
5703enable_auto_bkops:
5704 err = ufshcd_enable_auto_bkops(hba);
5705out:
5706 if (err < 0)
5707 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5708 __func__, err);
5709}
5710
5711static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5712{
5713 u32 value;
5714
5715 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5716 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5717 return;
5718
5719 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5720
5721 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5722
5723 /*
5724 * A placeholder for the platform vendors to add whatever additional
5725 * steps required
5726 */
5727}
5728
5729static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5730{
5731 u8 index;
5732 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5733 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5734
5735 index = ufshcd_wb_get_query_index(hba);
5736 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5737}
5738
5739int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5740{
5741 int ret;
5742
5743 if (!ufshcd_is_wb_allowed(hba) ||
5744 hba->dev_info.wb_enabled == enable)
5745 return 0;
5746
5747 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5748 if (ret) {
5749 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5750 __func__, enable ? "enabling" : "disabling", ret);
5751 return ret;
5752 }
5753
5754 hba->dev_info.wb_enabled = enable;
5755 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5756 __func__, enable ? "enabled" : "disabled");
5757
5758 return ret;
5759}
5760
5761static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5762 bool enable)
5763{
5764 int ret;
5765
5766 ret = __ufshcd_wb_toggle(hba, enable,
5767 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5768 if (ret) {
5769 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5770 __func__, enable ? "enabling" : "disabling", ret);
5771 return;
5772 }
5773 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5774 __func__, enable ? "enabled" : "disabled");
5775}
5776
5777int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5778{
5779 int ret;
5780
5781 if (!ufshcd_is_wb_allowed(hba) ||
5782 hba->dev_info.wb_buf_flush_enabled == enable)
5783 return 0;
5784
5785 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5786 if (ret) {
5787 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
5788 __func__, enable ? "enabling" : "disabling", ret);
5789 return ret;
5790 }
5791
5792 hba->dev_info.wb_buf_flush_enabled = enable;
5793 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
5794 __func__, enable ? "enabled" : "disabled");
5795
5796 return ret;
5797}
5798
5799static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
5800 u32 avail_buf)
5801{
5802 u32 cur_buf;
5803 int ret;
5804 u8 index;
5805
5806 index = ufshcd_wb_get_query_index(hba);
5807 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5808 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
5809 index, 0, &cur_buf);
5810 if (ret) {
5811 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
5812 __func__, ret);
5813 return false;
5814 }
5815
5816 if (!cur_buf) {
5817 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
5818 cur_buf);
5819 return false;
5820 }
5821 /* Let it continue to flush when available buffer exceeds threshold */
5822 return avail_buf < hba->vps->wb_flush_threshold;
5823}
5824
5825static void ufshcd_wb_force_disable(struct ufs_hba *hba)
5826{
5827 if (ufshcd_is_wb_buf_flush_allowed(hba))
5828 ufshcd_wb_toggle_buf_flush(hba, false);
5829
5830 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
5831 ufshcd_wb_toggle(hba, false);
5832 hba->caps &= ~UFSHCD_CAP_WB_EN;
5833
5834 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
5835}
5836
5837static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
5838{
5839 u32 lifetime;
5840 int ret;
5841 u8 index;
5842
5843 index = ufshcd_wb_get_query_index(hba);
5844 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5845 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
5846 index, 0, &lifetime);
5847 if (ret) {
5848 dev_err(hba->dev,
5849 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
5850 __func__, ret);
5851 return false;
5852 }
5853
5854 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
5855 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
5856 __func__, lifetime);
5857 return false;
5858 }
5859
5860 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
5861 __func__, lifetime);
5862
5863 return true;
5864}
5865
5866static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
5867{
5868 int ret;
5869 u32 avail_buf;
5870 u8 index;
5871
5872 if (!ufshcd_is_wb_allowed(hba))
5873 return false;
5874
5875 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
5876 ufshcd_wb_force_disable(hba);
5877 return false;
5878 }
5879
5880 /*
5881 * The ufs device needs the vcc to be ON to flush.
5882 * With user-space reduction enabled, it's enough to enable flush
5883 * by checking only the available buffer. The threshold
5884 * defined here is > 90% full.
5885 * With user-space preserved enabled, the current-buffer
5886 * should be checked too because the wb buffer size can reduce
5887 * when disk tends to be full. This info is provided by current
5888 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
5889 * keeping vcc on when current buffer is empty.
5890 */
5891 index = ufshcd_wb_get_query_index(hba);
5892 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5893 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
5894 index, 0, &avail_buf);
5895 if (ret) {
5896 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
5897 __func__, ret);
5898 return false;
5899 }
5900
5901 if (!hba->dev_info.b_presrv_uspc_en)
5902 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
5903
5904 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
5905}
5906
5907static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
5908{
5909 struct ufs_hba *hba = container_of(to_delayed_work(work),
5910 struct ufs_hba,
5911 rpm_dev_flush_recheck_work);
5912 /*
5913 * To prevent unnecessary VCC power drain after device finishes
5914 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
5915 * after a certain delay to recheck the threshold by next runtime
5916 * suspend.
5917 */
5918 ufshcd_rpm_get_sync(hba);
5919 ufshcd_rpm_put_sync(hba);
5920}
5921
5922/**
5923 * ufshcd_exception_event_handler - handle exceptions raised by device
5924 * @work: pointer to work data
5925 *
5926 * Read bExceptionEventStatus attribute from the device and handle the
5927 * exception event accordingly.
5928 */
5929static void ufshcd_exception_event_handler(struct work_struct *work)
5930{
5931 struct ufs_hba *hba;
5932 int err;
5933 u32 status = 0;
5934 hba = container_of(work, struct ufs_hba, eeh_work);
5935
5936 ufshcd_scsi_block_requests(hba);
5937 err = ufshcd_get_ee_status(hba, &status);
5938 if (err) {
5939 dev_err(hba->dev, "%s: failed to get exception status %d\n",
5940 __func__, err);
5941 goto out;
5942 }
5943
5944 trace_ufshcd_exception_event(dev_name(hba->dev), status);
5945
5946 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
5947 ufshcd_bkops_exception_event_handler(hba);
5948
5949 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
5950 ufshcd_temp_exception_event_handler(hba, status);
5951
5952 ufs_debugfs_exception_event(hba, status);
5953out:
5954 ufshcd_scsi_unblock_requests(hba);
5955}
5956
5957/* Complete requests that have door-bell cleared */
5958static void ufshcd_complete_requests(struct ufs_hba *hba)
5959{
5960 ufshcd_transfer_req_compl(hba);
5961 ufshcd_tmc_handler(hba);
5962}
5963
5964/**
5965 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
5966 * to recover from the DL NAC errors or not.
5967 * @hba: per-adapter instance
5968 *
5969 * Returns true if error handling is required, false otherwise
5970 */
5971static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
5972{
5973 unsigned long flags;
5974 bool err_handling = true;
5975
5976 spin_lock_irqsave(hba->host->host_lock, flags);
5977 /*
5978 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
5979 * device fatal error and/or DL NAC & REPLAY timeout errors.
5980 */
5981 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
5982 goto out;
5983
5984 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
5985 ((hba->saved_err & UIC_ERROR) &&
5986 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
5987 goto out;
5988
5989 if ((hba->saved_err & UIC_ERROR) &&
5990 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
5991 int err;
5992 /*
5993 * wait for 50ms to see if we can get any other errors or not.
5994 */
5995 spin_unlock_irqrestore(hba->host->host_lock, flags);
5996 msleep(50);
5997 spin_lock_irqsave(hba->host->host_lock, flags);
5998
5999 /*
6000 * now check if we have got any other severe errors other than
6001 * DL NAC error?
6002 */
6003 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6004 ((hba->saved_err & UIC_ERROR) &&
6005 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6006 goto out;
6007
6008 /*
6009 * As DL NAC is the only error received so far, send out NOP
6010 * command to confirm if link is still active or not.
6011 * - If we don't get any response then do error recovery.
6012 * - If we get response then clear the DL NAC error bit.
6013 */
6014
6015 spin_unlock_irqrestore(hba->host->host_lock, flags);
6016 err = ufshcd_verify_dev_init(hba);
6017 spin_lock_irqsave(hba->host->host_lock, flags);
6018
6019 if (err)
6020 goto out;
6021
6022 /* Link seems to be alive hence ignore the DL NAC errors */
6023 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6024 hba->saved_err &= ~UIC_ERROR;
6025 /* clear NAC error */
6026 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6027 if (!hba->saved_uic_err)
6028 err_handling = false;
6029 }
6030out:
6031 spin_unlock_irqrestore(hba->host->host_lock, flags);
6032 return err_handling;
6033}
6034
6035/* host lock must be held before calling this func */
6036static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6037{
6038 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6039 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6040}
6041
6042void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6043{
6044 lockdep_assert_held(hba->host->host_lock);
6045
6046 /* handle fatal errors only when link is not in error state */
6047 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6048 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6049 ufshcd_is_saved_err_fatal(hba))
6050 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6051 else
6052 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6053 queue_work(hba->eh_wq, &hba->eh_work);
6054 }
6055}
6056
6057static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6058{
6059 spin_lock_irq(hba->host->host_lock);
6060 hba->force_reset = true;
6061 ufshcd_schedule_eh_work(hba);
6062 spin_unlock_irq(hba->host->host_lock);
6063}
6064
6065static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6066{
6067 mutex_lock(&hba->wb_mutex);
6068 down_write(&hba->clk_scaling_lock);
6069 hba->clk_scaling.is_allowed = allow;
6070 up_write(&hba->clk_scaling_lock);
6071 mutex_unlock(&hba->wb_mutex);
6072}
6073
6074static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6075{
6076 if (suspend) {
6077 if (hba->clk_scaling.is_enabled)
6078 ufshcd_suspend_clkscaling(hba);
6079 ufshcd_clk_scaling_allow(hba, false);
6080 } else {
6081 ufshcd_clk_scaling_allow(hba, true);
6082 if (hba->clk_scaling.is_enabled)
6083 ufshcd_resume_clkscaling(hba);
6084 }
6085}
6086
6087static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6088{
6089 ufshcd_rpm_get_sync(hba);
6090 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6091 hba->is_sys_suspended) {
6092 enum ufs_pm_op pm_op;
6093
6094 /*
6095 * Don't assume anything of resume, if
6096 * resume fails, irq and clocks can be OFF, and powers
6097 * can be OFF or in LPM.
6098 */
6099 ufshcd_setup_hba_vreg(hba, true);
6100 ufshcd_enable_irq(hba);
6101 ufshcd_setup_vreg(hba, true);
6102 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6103 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6104 ufshcd_hold(hba, false);
6105 if (!ufshcd_is_clkgating_allowed(hba))
6106 ufshcd_setup_clocks(hba, true);
6107 ufshcd_release(hba);
6108 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6109 ufshcd_vops_resume(hba, pm_op);
6110 } else {
6111 ufshcd_hold(hba, false);
6112 if (ufshcd_is_clkscaling_supported(hba) &&
6113 hba->clk_scaling.is_enabled)
6114 ufshcd_suspend_clkscaling(hba);
6115 ufshcd_clk_scaling_allow(hba, false);
6116 }
6117 ufshcd_scsi_block_requests(hba);
6118 /* Drain ufshcd_queuecommand() */
6119 synchronize_rcu();
6120 cancel_work_sync(&hba->eeh_work);
6121}
6122
6123static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6124{
6125 ufshcd_scsi_unblock_requests(hba);
6126 ufshcd_release(hba);
6127 if (ufshcd_is_clkscaling_supported(hba))
6128 ufshcd_clk_scaling_suspend(hba, false);
6129 ufshcd_rpm_put(hba);
6130}
6131
6132static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6133{
6134 return (!hba->is_powered || hba->shutting_down ||
6135 !hba->ufs_device_wlun ||
6136 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6137 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6138 ufshcd_is_link_broken(hba))));
6139}
6140
6141#ifdef CONFIG_PM
6142static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6143{
6144 struct Scsi_Host *shost = hba->host;
6145 struct scsi_device *sdev;
6146 struct request_queue *q;
6147 int ret;
6148
6149 hba->is_sys_suspended = false;
6150 /*
6151 * Set RPM status of wlun device to RPM_ACTIVE,
6152 * this also clears its runtime error.
6153 */
6154 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6155
6156 /* hba device might have a runtime error otherwise */
6157 if (ret)
6158 ret = pm_runtime_set_active(hba->dev);
6159 /*
6160 * If wlun device had runtime error, we also need to resume those
6161 * consumer scsi devices in case any of them has failed to be
6162 * resumed due to supplier runtime resume failure. This is to unblock
6163 * blk_queue_enter in case there are bios waiting inside it.
6164 */
6165 if (!ret) {
6166 shost_for_each_device(sdev, shost) {
6167 q = sdev->request_queue;
6168 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6169 q->rpm_status == RPM_SUSPENDING))
6170 pm_request_resume(q->dev);
6171 }
6172 }
6173}
6174#else
6175static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6176{
6177}
6178#endif
6179
6180static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6181{
6182 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6183 u32 mode;
6184
6185 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6186
6187 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6188 return true;
6189
6190 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6191 return true;
6192
6193 return false;
6194}
6195
6196static bool ufshcd_abort_all(struct ufs_hba *hba)
6197{
6198 bool needs_reset = false;
6199 int tag, ret;
6200
6201 /* Clear pending transfer requests */
6202 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
6203 ret = ufshcd_try_to_abort_task(hba, tag);
6204 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6205 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6206 ret ? "failed" : "succeeded");
6207 if (ret) {
6208 needs_reset = true;
6209 goto out;
6210 }
6211 }
6212
6213 /* Clear pending task management requests */
6214 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6215 if (ufshcd_clear_tm_cmd(hba, tag)) {
6216 needs_reset = true;
6217 goto out;
6218 }
6219 }
6220
6221out:
6222 /* Complete the requests that are cleared by s/w */
6223 ufshcd_complete_requests(hba);
6224
6225 return needs_reset;
6226}
6227
6228/**
6229 * ufshcd_err_handler - handle UFS errors that require s/w attention
6230 * @work: pointer to work structure
6231 */
6232static void ufshcd_err_handler(struct work_struct *work)
6233{
6234 int retries = MAX_ERR_HANDLER_RETRIES;
6235 struct ufs_hba *hba;
6236 unsigned long flags;
6237 bool needs_restore;
6238 bool needs_reset;
6239 int pmc_err;
6240
6241 hba = container_of(work, struct ufs_hba, eh_work);
6242
6243 dev_info(hba->dev,
6244 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6245 __func__, ufshcd_state_name[hba->ufshcd_state],
6246 hba->is_powered, hba->shutting_down, hba->saved_err,
6247 hba->saved_uic_err, hba->force_reset,
6248 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6249
6250 down(&hba->host_sem);
6251 spin_lock_irqsave(hba->host->host_lock, flags);
6252 if (ufshcd_err_handling_should_stop(hba)) {
6253 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6254 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6255 spin_unlock_irqrestore(hba->host->host_lock, flags);
6256 up(&hba->host_sem);
6257 return;
6258 }
6259 ufshcd_set_eh_in_progress(hba);
6260 spin_unlock_irqrestore(hba->host->host_lock, flags);
6261 ufshcd_err_handling_prepare(hba);
6262 /* Complete requests that have door-bell cleared by h/w */
6263 ufshcd_complete_requests(hba);
6264 spin_lock_irqsave(hba->host->host_lock, flags);
6265again:
6266 needs_restore = false;
6267 needs_reset = false;
6268
6269 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6270 hba->ufshcd_state = UFSHCD_STATE_RESET;
6271 /*
6272 * A full reset and restore might have happened after preparation
6273 * is finished, double check whether we should stop.
6274 */
6275 if (ufshcd_err_handling_should_stop(hba))
6276 goto skip_err_handling;
6277
6278 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6279 bool ret;
6280
6281 spin_unlock_irqrestore(hba->host->host_lock, flags);
6282 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6283 ret = ufshcd_quirk_dl_nac_errors(hba);
6284 spin_lock_irqsave(hba->host->host_lock, flags);
6285 if (!ret && ufshcd_err_handling_should_stop(hba))
6286 goto skip_err_handling;
6287 }
6288
6289 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6290 (hba->saved_uic_err &&
6291 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6292 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6293
6294 spin_unlock_irqrestore(hba->host->host_lock, flags);
6295 ufshcd_print_host_state(hba);
6296 ufshcd_print_pwr_info(hba);
6297 ufshcd_print_evt_hist(hba);
6298 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6299 ufshcd_print_trs(hba, hba->outstanding_reqs, pr_prdt);
6300 spin_lock_irqsave(hba->host->host_lock, flags);
6301 }
6302
6303 /*
6304 * if host reset is required then skip clearing the pending
6305 * transfers forcefully because they will get cleared during
6306 * host reset and restore
6307 */
6308 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6309 ufshcd_is_saved_err_fatal(hba) ||
6310 ((hba->saved_err & UIC_ERROR) &&
6311 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6312 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6313 needs_reset = true;
6314 goto do_reset;
6315 }
6316
6317 /*
6318 * If LINERESET was caught, UFS might have been put to PWM mode,
6319 * check if power mode restore is needed.
6320 */
6321 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6322 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6323 if (!hba->saved_uic_err)
6324 hba->saved_err &= ~UIC_ERROR;
6325 spin_unlock_irqrestore(hba->host->host_lock, flags);
6326 if (ufshcd_is_pwr_mode_restore_needed(hba))
6327 needs_restore = true;
6328 spin_lock_irqsave(hba->host->host_lock, flags);
6329 if (!hba->saved_err && !needs_restore)
6330 goto skip_err_handling;
6331 }
6332
6333 hba->silence_err_logs = true;
6334 /* release lock as clear command might sleep */
6335 spin_unlock_irqrestore(hba->host->host_lock, flags);
6336
6337 needs_reset = ufshcd_abort_all(hba);
6338
6339 spin_lock_irqsave(hba->host->host_lock, flags);
6340 hba->silence_err_logs = false;
6341 if (needs_reset)
6342 goto do_reset;
6343
6344 /*
6345 * After all reqs and tasks are cleared from doorbell,
6346 * now it is safe to retore power mode.
6347 */
6348 if (needs_restore) {
6349 spin_unlock_irqrestore(hba->host->host_lock, flags);
6350 /*
6351 * Hold the scaling lock just in case dev cmds
6352 * are sent via bsg and/or sysfs.
6353 */
6354 down_write(&hba->clk_scaling_lock);
6355 hba->force_pmc = true;
6356 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6357 if (pmc_err) {
6358 needs_reset = true;
6359 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6360 __func__, pmc_err);
6361 }
6362 hba->force_pmc = false;
6363 ufshcd_print_pwr_info(hba);
6364 up_write(&hba->clk_scaling_lock);
6365 spin_lock_irqsave(hba->host->host_lock, flags);
6366 }
6367
6368do_reset:
6369 /* Fatal errors need reset */
6370 if (needs_reset) {
6371 int err;
6372
6373 hba->force_reset = false;
6374 spin_unlock_irqrestore(hba->host->host_lock, flags);
6375 err = ufshcd_reset_and_restore(hba);
6376 if (err)
6377 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6378 __func__, err);
6379 else
6380 ufshcd_recover_pm_error(hba);
6381 spin_lock_irqsave(hba->host->host_lock, flags);
6382 }
6383
6384skip_err_handling:
6385 if (!needs_reset) {
6386 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6387 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6388 if (hba->saved_err || hba->saved_uic_err)
6389 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6390 __func__, hba->saved_err, hba->saved_uic_err);
6391 }
6392 /* Exit in an operational state or dead */
6393 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6394 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6395 if (--retries)
6396 goto again;
6397 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6398 }
6399 ufshcd_clear_eh_in_progress(hba);
6400 spin_unlock_irqrestore(hba->host->host_lock, flags);
6401 ufshcd_err_handling_unprepare(hba);
6402 up(&hba->host_sem);
6403
6404 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6405 ufshcd_state_name[hba->ufshcd_state]);
6406}
6407
6408/**
6409 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6410 * @hba: per-adapter instance
6411 *
6412 * Returns
6413 * IRQ_HANDLED - If interrupt is valid
6414 * IRQ_NONE - If invalid interrupt
6415 */
6416static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6417{
6418 u32 reg;
6419 irqreturn_t retval = IRQ_NONE;
6420
6421 /* PHY layer error */
6422 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6423 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6424 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6425 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6426 /*
6427 * To know whether this error is fatal or not, DB timeout
6428 * must be checked but this error is handled separately.
6429 */
6430 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6431 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6432 __func__);
6433
6434 /* Got a LINERESET indication. */
6435 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6436 struct uic_command *cmd = NULL;
6437
6438 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6439 if (hba->uic_async_done && hba->active_uic_cmd)
6440 cmd = hba->active_uic_cmd;
6441 /*
6442 * Ignore the LINERESET during power mode change
6443 * operation via DME_SET command.
6444 */
6445 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6446 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6447 }
6448 retval |= IRQ_HANDLED;
6449 }
6450
6451 /* PA_INIT_ERROR is fatal and needs UIC reset */
6452 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6453 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6454 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6455 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6456
6457 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6458 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6459 else if (hba->dev_quirks &
6460 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6461 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6462 hba->uic_error |=
6463 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6464 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6465 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6466 }
6467 retval |= IRQ_HANDLED;
6468 }
6469
6470 /* UIC NL/TL/DME errors needs software retry */
6471 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6472 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6473 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6474 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6475 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6476 retval |= IRQ_HANDLED;
6477 }
6478
6479 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6480 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6481 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6482 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6483 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6484 retval |= IRQ_HANDLED;
6485 }
6486
6487 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6488 if ((reg & UIC_DME_ERROR) &&
6489 (reg & UIC_DME_ERROR_CODE_MASK)) {
6490 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6491 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6492 retval |= IRQ_HANDLED;
6493 }
6494
6495 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6496 __func__, hba->uic_error);
6497 return retval;
6498}
6499
6500/**
6501 * ufshcd_check_errors - Check for errors that need s/w attention
6502 * @hba: per-adapter instance
6503 * @intr_status: interrupt status generated by the controller
6504 *
6505 * Returns
6506 * IRQ_HANDLED - If interrupt is valid
6507 * IRQ_NONE - If invalid interrupt
6508 */
6509static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6510{
6511 bool queue_eh_work = false;
6512 irqreturn_t retval = IRQ_NONE;
6513
6514 spin_lock(hba->host->host_lock);
6515 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6516
6517 if (hba->errors & INT_FATAL_ERRORS) {
6518 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6519 hba->errors);
6520 queue_eh_work = true;
6521 }
6522
6523 if (hba->errors & UIC_ERROR) {
6524 hba->uic_error = 0;
6525 retval = ufshcd_update_uic_error(hba);
6526 if (hba->uic_error)
6527 queue_eh_work = true;
6528 }
6529
6530 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6531 dev_err(hba->dev,
6532 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6533 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6534 "Enter" : "Exit",
6535 hba->errors, ufshcd_get_upmcrs(hba));
6536 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6537 hba->errors);
6538 ufshcd_set_link_broken(hba);
6539 queue_eh_work = true;
6540 }
6541
6542 if (queue_eh_work) {
6543 /*
6544 * update the transfer error masks to sticky bits, let's do this
6545 * irrespective of current ufshcd_state.
6546 */
6547 hba->saved_err |= hba->errors;
6548 hba->saved_uic_err |= hba->uic_error;
6549
6550 /* dump controller state before resetting */
6551 if ((hba->saved_err &
6552 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6553 (hba->saved_uic_err &&
6554 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6555 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6556 __func__, hba->saved_err,
6557 hba->saved_uic_err);
6558 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6559 "host_regs: ");
6560 ufshcd_print_pwr_info(hba);
6561 }
6562 ufshcd_schedule_eh_work(hba);
6563 retval |= IRQ_HANDLED;
6564 }
6565 /*
6566 * if (!queue_eh_work) -
6567 * Other errors are either non-fatal where host recovers
6568 * itself without s/w intervention or errors that will be
6569 * handled by the SCSI core layer.
6570 */
6571 hba->errors = 0;
6572 hba->uic_error = 0;
6573 spin_unlock(hba->host->host_lock);
6574 return retval;
6575}
6576
6577/**
6578 * ufshcd_tmc_handler - handle task management function completion
6579 * @hba: per adapter instance
6580 *
6581 * Returns
6582 * IRQ_HANDLED - If interrupt is valid
6583 * IRQ_NONE - If invalid interrupt
6584 */
6585static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6586{
6587 unsigned long flags, pending, issued;
6588 irqreturn_t ret = IRQ_NONE;
6589 int tag;
6590
6591 spin_lock_irqsave(hba->host->host_lock, flags);
6592 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6593 issued = hba->outstanding_tasks & ~pending;
6594 for_each_set_bit(tag, &issued, hba->nutmrs) {
6595 struct request *req = hba->tmf_rqs[tag];
6596 struct completion *c = req->end_io_data;
6597
6598 complete(c);
6599 ret = IRQ_HANDLED;
6600 }
6601 spin_unlock_irqrestore(hba->host->host_lock, flags);
6602
6603 return ret;
6604}
6605
6606/**
6607 * ufshcd_sl_intr - Interrupt service routine
6608 * @hba: per adapter instance
6609 * @intr_status: contains interrupts generated by the controller
6610 *
6611 * Returns
6612 * IRQ_HANDLED - If interrupt is valid
6613 * IRQ_NONE - If invalid interrupt
6614 */
6615static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6616{
6617 irqreturn_t retval = IRQ_NONE;
6618
6619 if (intr_status & UFSHCD_UIC_MASK)
6620 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6621
6622 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6623 retval |= ufshcd_check_errors(hba, intr_status);
6624
6625 if (intr_status & UTP_TASK_REQ_COMPL)
6626 retval |= ufshcd_tmc_handler(hba);
6627
6628 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6629 retval |= ufshcd_transfer_req_compl(hba);
6630
6631 return retval;
6632}
6633
6634/**
6635 * ufshcd_intr - Main interrupt service routine
6636 * @irq: irq number
6637 * @__hba: pointer to adapter instance
6638 *
6639 * Returns
6640 * IRQ_HANDLED - If interrupt is valid
6641 * IRQ_NONE - If invalid interrupt
6642 */
6643static irqreturn_t ufshcd_intr(int irq, void *__hba)
6644{
6645 u32 intr_status, enabled_intr_status = 0;
6646 irqreturn_t retval = IRQ_NONE;
6647 struct ufs_hba *hba = __hba;
6648 int retries = hba->nutrs;
6649
6650 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6651 hba->ufs_stats.last_intr_status = intr_status;
6652 hba->ufs_stats.last_intr_ts = local_clock();
6653
6654 /*
6655 * There could be max of hba->nutrs reqs in flight and in worst case
6656 * if the reqs get finished 1 by 1 after the interrupt status is
6657 * read, make sure we handle them by checking the interrupt status
6658 * again in a loop until we process all of the reqs before returning.
6659 */
6660 while (intr_status && retries--) {
6661 enabled_intr_status =
6662 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6663 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6664 if (enabled_intr_status)
6665 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6666
6667 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6668 }
6669
6670 if (enabled_intr_status && retval == IRQ_NONE &&
6671 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6672 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6673 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6674 __func__,
6675 intr_status,
6676 hba->ufs_stats.last_intr_status,
6677 enabled_intr_status);
6678 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6679 }
6680
6681 return retval;
6682}
6683
6684static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6685{
6686 int err = 0;
6687 u32 mask = 1 << tag;
6688 unsigned long flags;
6689
6690 if (!test_bit(tag, &hba->outstanding_tasks))
6691 goto out;
6692
6693 spin_lock_irqsave(hba->host->host_lock, flags);
6694 ufshcd_utmrl_clear(hba, tag);
6695 spin_unlock_irqrestore(hba->host->host_lock, flags);
6696
6697 /* poll for max. 1 sec to clear door bell register by h/w */
6698 err = ufshcd_wait_for_register(hba,
6699 REG_UTP_TASK_REQ_DOOR_BELL,
6700 mask, 0, 1000, 1000);
6701
6702 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6703 tag, err ? "succeeded" : "failed");
6704
6705out:
6706 return err;
6707}
6708
6709static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6710 struct utp_task_req_desc *treq, u8 tm_function)
6711{
6712 struct request_queue *q = hba->tmf_queue;
6713 struct Scsi_Host *host = hba->host;
6714 DECLARE_COMPLETION_ONSTACK(wait);
6715 struct request *req;
6716 unsigned long flags;
6717 int task_tag, err;
6718
6719 /*
6720 * blk_mq_alloc_request() is used here only to get a free tag.
6721 */
6722 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
6723 if (IS_ERR(req))
6724 return PTR_ERR(req);
6725
6726 req->end_io_data = &wait;
6727 ufshcd_hold(hba, false);
6728
6729 spin_lock_irqsave(host->host_lock, flags);
6730
6731 task_tag = req->tag;
6732 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
6733 task_tag);
6734 hba->tmf_rqs[req->tag] = req;
6735 treq->upiu_req.req_header.dword_0 |= cpu_to_be32(task_tag);
6736
6737 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
6738 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
6739
6740 /* send command to the controller */
6741 __set_bit(task_tag, &hba->outstanding_tasks);
6742
6743 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
6744 /* Make sure that doorbell is committed immediately */
6745 wmb();
6746
6747 spin_unlock_irqrestore(host->host_lock, flags);
6748
6749 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
6750
6751 /* wait until the task management command is completed */
6752 err = wait_for_completion_io_timeout(&wait,
6753 msecs_to_jiffies(TM_CMD_TIMEOUT));
6754 if (!err) {
6755 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
6756 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
6757 __func__, tm_function);
6758 if (ufshcd_clear_tm_cmd(hba, task_tag))
6759 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
6760 __func__, task_tag);
6761 err = -ETIMEDOUT;
6762 } else {
6763 err = 0;
6764 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
6765
6766 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
6767 }
6768
6769 spin_lock_irqsave(hba->host->host_lock, flags);
6770 hba->tmf_rqs[req->tag] = NULL;
6771 __clear_bit(task_tag, &hba->outstanding_tasks);
6772 spin_unlock_irqrestore(hba->host->host_lock, flags);
6773
6774 ufshcd_release(hba);
6775 blk_mq_free_request(req);
6776
6777 return err;
6778}
6779
6780/**
6781 * ufshcd_issue_tm_cmd - issues task management commands to controller
6782 * @hba: per adapter instance
6783 * @lun_id: LUN ID to which TM command is sent
6784 * @task_id: task ID to which the TM command is applicable
6785 * @tm_function: task management function opcode
6786 * @tm_response: task management service response return value
6787 *
6788 * Returns non-zero value on error, zero on success.
6789 */
6790static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
6791 u8 tm_function, u8 *tm_response)
6792{
6793 struct utp_task_req_desc treq = { { 0 }, };
6794 enum utp_ocs ocs_value;
6795 int err;
6796
6797 /* Configure task request descriptor */
6798 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6799 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6800
6801 /* Configure task request UPIU */
6802 treq.upiu_req.req_header.dword_0 = cpu_to_be32(lun_id << 8) |
6803 cpu_to_be32(UPIU_TRANSACTION_TASK_REQ << 24);
6804 treq.upiu_req.req_header.dword_1 = cpu_to_be32(tm_function << 16);
6805
6806 /*
6807 * The host shall provide the same value for LUN field in the basic
6808 * header and for Input Parameter.
6809 */
6810 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
6811 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
6812
6813 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
6814 if (err == -ETIMEDOUT)
6815 return err;
6816
6817 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6818 if (ocs_value != OCS_SUCCESS)
6819 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
6820 __func__, ocs_value);
6821 else if (tm_response)
6822 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
6823 MASK_TM_SERVICE_RESP;
6824 return err;
6825}
6826
6827/**
6828 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
6829 * @hba: per-adapter instance
6830 * @req_upiu: upiu request
6831 * @rsp_upiu: upiu reply
6832 * @desc_buff: pointer to descriptor buffer, NULL if NA
6833 * @buff_len: descriptor size, 0 if NA
6834 * @cmd_type: specifies the type (NOP, Query...)
6835 * @desc_op: descriptor operation
6836 *
6837 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
6838 * Therefore, it "rides" the device management infrastructure: uses its tag and
6839 * tasks work queues.
6840 *
6841 * Since there is only one available tag for device management commands,
6842 * the caller is expected to hold the hba->dev_cmd.lock mutex.
6843 */
6844static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
6845 struct utp_upiu_req *req_upiu,
6846 struct utp_upiu_req *rsp_upiu,
6847 u8 *desc_buff, int *buff_len,
6848 enum dev_cmd_type cmd_type,
6849 enum query_opcode desc_op)
6850{
6851 DECLARE_COMPLETION_ONSTACK(wait);
6852 const u32 tag = hba->reserved_slot;
6853 struct ufshcd_lrb *lrbp;
6854 int err = 0;
6855 u8 upiu_flags;
6856
6857 /* Protects use of hba->reserved_slot. */
6858 lockdep_assert_held(&hba->dev_cmd.lock);
6859
6860 down_read(&hba->clk_scaling_lock);
6861
6862 lrbp = &hba->lrb[tag];
6863 WARN_ON(lrbp->cmd);
6864 lrbp->cmd = NULL;
6865 lrbp->task_tag = tag;
6866 lrbp->lun = 0;
6867 lrbp->intr_cmd = true;
6868 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
6869 hba->dev_cmd.type = cmd_type;
6870
6871 if (hba->ufs_version <= ufshci_version(1, 1))
6872 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
6873 else
6874 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
6875
6876 /* update the task tag in the request upiu */
6877 req_upiu->header.dword_0 |= cpu_to_be32(tag);
6878
6879 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
6880
6881 /* just copy the upiu request as it is */
6882 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
6883 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
6884 /* The Data Segment Area is optional depending upon the query
6885 * function value. for WRITE DESCRIPTOR, the data segment
6886 * follows right after the tsf.
6887 */
6888 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
6889 *buff_len = 0;
6890 }
6891
6892 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
6893
6894 hba->dev_cmd.complete = &wait;
6895
6896 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
6897
6898 ufshcd_send_command(hba, tag);
6899 /*
6900 * ignore the returning value here - ufshcd_check_query_response is
6901 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
6902 * read the response directly ignoring all errors.
6903 */
6904 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
6905
6906 /* just copy the upiu response as it is */
6907 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
6908 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
6909 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
6910 u16 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
6911 MASK_QUERY_DATA_SEG_LEN;
6912
6913 if (*buff_len >= resp_len) {
6914 memcpy(desc_buff, descp, resp_len);
6915 *buff_len = resp_len;
6916 } else {
6917 dev_warn(hba->dev,
6918 "%s: rsp size %d is bigger than buffer size %d",
6919 __func__, resp_len, *buff_len);
6920 *buff_len = 0;
6921 err = -EINVAL;
6922 }
6923 }
6924 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
6925 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
6926
6927 up_read(&hba->clk_scaling_lock);
6928 return err;
6929}
6930
6931/**
6932 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
6933 * @hba: per-adapter instance
6934 * @req_upiu: upiu request
6935 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
6936 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
6937 * @desc_buff: pointer to descriptor buffer, NULL if NA
6938 * @buff_len: descriptor size, 0 if NA
6939 * @desc_op: descriptor operation
6940 *
6941 * Supports UTP Transfer requests (nop and query), and UTP Task
6942 * Management requests.
6943 * It is up to the caller to fill the upiu conent properly, as it will
6944 * be copied without any further input validations.
6945 */
6946int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
6947 struct utp_upiu_req *req_upiu,
6948 struct utp_upiu_req *rsp_upiu,
6949 int msgcode,
6950 u8 *desc_buff, int *buff_len,
6951 enum query_opcode desc_op)
6952{
6953 int err;
6954 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
6955 struct utp_task_req_desc treq = { { 0 }, };
6956 enum utp_ocs ocs_value;
6957 u8 tm_f = be32_to_cpu(req_upiu->header.dword_1) >> 16 & MASK_TM_FUNC;
6958
6959 switch (msgcode) {
6960 case UPIU_TRANSACTION_NOP_OUT:
6961 cmd_type = DEV_CMD_TYPE_NOP;
6962 fallthrough;
6963 case UPIU_TRANSACTION_QUERY_REQ:
6964 ufshcd_hold(hba, false);
6965 mutex_lock(&hba->dev_cmd.lock);
6966 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
6967 desc_buff, buff_len,
6968 cmd_type, desc_op);
6969 mutex_unlock(&hba->dev_cmd.lock);
6970 ufshcd_release(hba);
6971
6972 break;
6973 case UPIU_TRANSACTION_TASK_REQ:
6974 treq.header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
6975 treq.header.dword_2 = cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
6976
6977 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
6978
6979 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
6980 if (err == -ETIMEDOUT)
6981 break;
6982
6983 ocs_value = le32_to_cpu(treq.header.dword_2) & MASK_OCS;
6984 if (ocs_value != OCS_SUCCESS) {
6985 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
6986 ocs_value);
6987 break;
6988 }
6989
6990 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
6991
6992 break;
6993 default:
6994 err = -EINVAL;
6995
6996 break;
6997 }
6998
6999 return err;
7000}
7001
7002/**
7003 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7004 * @cmd: SCSI command pointer
7005 *
7006 * Returns SUCCESS/FAILED
7007 */
7008static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7009{
7010 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7011 struct Scsi_Host *host;
7012 struct ufs_hba *hba;
7013 u32 pos;
7014 int err;
7015 u8 resp = 0xF, lun;
7016
7017 host = cmd->device->host;
7018 hba = shost_priv(host);
7019
7020 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7021 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7022 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7023 if (!err)
7024 err = resp;
7025 goto out;
7026 }
7027
7028 /* clear the commands that were pending for corresponding LUN */
7029 spin_lock_irqsave(&hba->outstanding_lock, flags);
7030 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7031 if (hba->lrb[pos].lun == lun)
7032 __set_bit(pos, &pending_reqs);
7033 hba->outstanding_reqs &= ~pending_reqs;
7034 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7035
7036 if (ufshcd_clear_cmds(hba, pending_reqs) < 0) {
7037 spin_lock_irqsave(&hba->outstanding_lock, flags);
7038 not_cleared = pending_reqs &
7039 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7040 hba->outstanding_reqs |= not_cleared;
7041 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7042
7043 dev_err(hba->dev, "%s: failed to clear requests %#lx\n",
7044 __func__, not_cleared);
7045 }
7046 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared);
7047
7048out:
7049 hba->req_abort_count = 0;
7050 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7051 if (!err) {
7052 err = SUCCESS;
7053 } else {
7054 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7055 err = FAILED;
7056 }
7057 return err;
7058}
7059
7060static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7061{
7062 struct ufshcd_lrb *lrbp;
7063 int tag;
7064
7065 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7066 lrbp = &hba->lrb[tag];
7067 lrbp->req_abort_skip = true;
7068 }
7069}
7070
7071/**
7072 * ufshcd_try_to_abort_task - abort a specific task
7073 * @hba: Pointer to adapter instance
7074 * @tag: Task tag/index to be aborted
7075 *
7076 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7077 * command, and in host controller by clearing the door-bell register. There can
7078 * be race between controller sending the command to the device while abort is
7079 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7080 * really issued and then try to abort it.
7081 *
7082 * Returns zero on success, non-zero on failure
7083 */
7084static int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7085{
7086 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7087 int err = 0;
7088 int poll_cnt;
7089 u8 resp = 0xF;
7090 u32 reg;
7091
7092 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7093 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7094 UFS_QUERY_TASK, &resp);
7095 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7096 /* cmd pending in the device */
7097 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7098 __func__, tag);
7099 break;
7100 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7101 /*
7102 * cmd not pending in the device, check if it is
7103 * in transition.
7104 */
7105 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7106 __func__, tag);
7107 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7108 if (reg & (1 << tag)) {
7109 /* sleep for max. 200us to stabilize */
7110 usleep_range(100, 200);
7111 continue;
7112 }
7113 /* command completed already */
7114 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7115 __func__, tag);
7116 goto out;
7117 } else {
7118 dev_err(hba->dev,
7119 "%s: no response from device. tag = %d, err %d\n",
7120 __func__, tag, err);
7121 if (!err)
7122 err = resp; /* service response error */
7123 goto out;
7124 }
7125 }
7126
7127 if (!poll_cnt) {
7128 err = -EBUSY;
7129 goto out;
7130 }
7131
7132 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7133 UFS_ABORT_TASK, &resp);
7134 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7135 if (!err) {
7136 err = resp; /* service response error */
7137 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7138 __func__, tag, err);
7139 }
7140 goto out;
7141 }
7142
7143 err = ufshcd_clear_cmds(hba, 1U << tag);
7144 if (err)
7145 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7146 __func__, tag, err);
7147
7148out:
7149 return err;
7150}
7151
7152/**
7153 * ufshcd_abort - scsi host template eh_abort_handler callback
7154 * @cmd: SCSI command pointer
7155 *
7156 * Returns SUCCESS/FAILED
7157 */
7158static int ufshcd_abort(struct scsi_cmnd *cmd)
7159{
7160 struct Scsi_Host *host = cmd->device->host;
7161 struct ufs_hba *hba = shost_priv(host);
7162 int tag = scsi_cmd_to_rq(cmd)->tag;
7163 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7164 unsigned long flags;
7165 int err = FAILED;
7166 bool outstanding;
7167 u32 reg;
7168
7169 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7170
7171 ufshcd_hold(hba, false);
7172 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7173 /* If command is already aborted/completed, return FAILED. */
7174 if (!(test_bit(tag, &hba->outstanding_reqs))) {
7175 dev_err(hba->dev,
7176 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7177 __func__, tag, hba->outstanding_reqs, reg);
7178 goto release;
7179 }
7180
7181 /* Print Transfer Request of aborted task */
7182 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7183
7184 /*
7185 * Print detailed info about aborted request.
7186 * As more than one request might get aborted at the same time,
7187 * print full information only for the first aborted request in order
7188 * to reduce repeated printouts. For other aborted requests only print
7189 * basic details.
7190 */
7191 scsi_print_command(cmd);
7192 if (!hba->req_abort_count) {
7193 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7194 ufshcd_print_evt_hist(hba);
7195 ufshcd_print_host_state(hba);
7196 ufshcd_print_pwr_info(hba);
7197 ufshcd_print_trs(hba, 1 << tag, true);
7198 } else {
7199 ufshcd_print_trs(hba, 1 << tag, false);
7200 }
7201 hba->req_abort_count++;
7202
7203 if (!(reg & (1 << tag))) {
7204 dev_err(hba->dev,
7205 "%s: cmd was completed, but without a notifying intr, tag = %d",
7206 __func__, tag);
7207 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7208 goto release;
7209 }
7210
7211 /*
7212 * Task abort to the device W-LUN is illegal. When this command
7213 * will fail, due to spec violation, scsi err handling next step
7214 * will be to send LU reset which, again, is a spec violation.
7215 * To avoid these unnecessary/illegal steps, first we clean up
7216 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7217 * then queue the eh_work and bail.
7218 */
7219 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7220 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7221
7222 spin_lock_irqsave(host->host_lock, flags);
7223 hba->force_reset = true;
7224 ufshcd_schedule_eh_work(hba);
7225 spin_unlock_irqrestore(host->host_lock, flags);
7226 goto release;
7227 }
7228
7229 /* Skip task abort in case previous aborts failed and report failure */
7230 if (lrbp->req_abort_skip) {
7231 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7232 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7233 goto release;
7234 }
7235
7236 err = ufshcd_try_to_abort_task(hba, tag);
7237 if (err) {
7238 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7239 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7240 err = FAILED;
7241 goto release;
7242 }
7243
7244 /*
7245 * Clear the corresponding bit from outstanding_reqs since the command
7246 * has been aborted successfully.
7247 */
7248 spin_lock_irqsave(&hba->outstanding_lock, flags);
7249 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7250 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7251
7252 if (outstanding)
7253 ufshcd_release_scsi_cmd(hba, lrbp);
7254
7255 err = SUCCESS;
7256
7257release:
7258 /* Matches the ufshcd_hold() call at the start of this function. */
7259 ufshcd_release(hba);
7260 return err;
7261}
7262
7263/**
7264 * ufshcd_host_reset_and_restore - reset and restore host controller
7265 * @hba: per-adapter instance
7266 *
7267 * Note that host controller reset may issue DME_RESET to
7268 * local and remote (device) Uni-Pro stack and the attributes
7269 * are reset to default state.
7270 *
7271 * Returns zero on success, non-zero on failure
7272 */
7273static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7274{
7275 int err;
7276
7277 /*
7278 * Stop the host controller and complete the requests
7279 * cleared by h/w
7280 */
7281 ufshpb_toggle_state(hba, HPB_PRESENT, HPB_RESET);
7282 ufshcd_hba_stop(hba);
7283 hba->silence_err_logs = true;
7284 ufshcd_complete_requests(hba);
7285 hba->silence_err_logs = false;
7286
7287 /* scale up clocks to max frequency before full reinitialization */
7288 ufshcd_scale_clks(hba, true);
7289
7290 err = ufshcd_hba_enable(hba);
7291
7292 /* Establish the link again and restore the device */
7293 if (!err)
7294 err = ufshcd_probe_hba(hba, false);
7295
7296 if (err)
7297 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7298 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7299 return err;
7300}
7301
7302/**
7303 * ufshcd_reset_and_restore - reset and re-initialize host/device
7304 * @hba: per-adapter instance
7305 *
7306 * Reset and recover device, host and re-establish link. This
7307 * is helpful to recover the communication in fatal error conditions.
7308 *
7309 * Returns zero on success, non-zero on failure
7310 */
7311static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7312{
7313 u32 saved_err = 0;
7314 u32 saved_uic_err = 0;
7315 int err = 0;
7316 unsigned long flags;
7317 int retries = MAX_HOST_RESET_RETRIES;
7318
7319 spin_lock_irqsave(hba->host->host_lock, flags);
7320 do {
7321 /*
7322 * This is a fresh start, cache and clear saved error first,
7323 * in case new error generated during reset and restore.
7324 */
7325 saved_err |= hba->saved_err;
7326 saved_uic_err |= hba->saved_uic_err;
7327 hba->saved_err = 0;
7328 hba->saved_uic_err = 0;
7329 hba->force_reset = false;
7330 hba->ufshcd_state = UFSHCD_STATE_RESET;
7331 spin_unlock_irqrestore(hba->host->host_lock, flags);
7332
7333 /* Reset the attached device */
7334 ufshcd_device_reset(hba);
7335
7336 err = ufshcd_host_reset_and_restore(hba);
7337
7338 spin_lock_irqsave(hba->host->host_lock, flags);
7339 if (err)
7340 continue;
7341 /* Do not exit unless operational or dead */
7342 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7343 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7344 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7345 err = -EAGAIN;
7346 } while (err && --retries);
7347
7348 /*
7349 * Inform scsi mid-layer that we did reset and allow to handle
7350 * Unit Attention properly.
7351 */
7352 scsi_report_bus_reset(hba->host, 0);
7353 if (err) {
7354 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7355 hba->saved_err |= saved_err;
7356 hba->saved_uic_err |= saved_uic_err;
7357 }
7358 spin_unlock_irqrestore(hba->host->host_lock, flags);
7359
7360 return err;
7361}
7362
7363/**
7364 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7365 * @cmd: SCSI command pointer
7366 *
7367 * Returns SUCCESS/FAILED
7368 */
7369static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7370{
7371 int err = SUCCESS;
7372 unsigned long flags;
7373 struct ufs_hba *hba;
7374
7375 hba = shost_priv(cmd->device->host);
7376
7377 spin_lock_irqsave(hba->host->host_lock, flags);
7378 hba->force_reset = true;
7379 ufshcd_schedule_eh_work(hba);
7380 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7381 spin_unlock_irqrestore(hba->host->host_lock, flags);
7382
7383 flush_work(&hba->eh_work);
7384
7385 spin_lock_irqsave(hba->host->host_lock, flags);
7386 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7387 err = FAILED;
7388 spin_unlock_irqrestore(hba->host->host_lock, flags);
7389
7390 return err;
7391}
7392
7393/**
7394 * ufshcd_get_max_icc_level - calculate the ICC level
7395 * @sup_curr_uA: max. current supported by the regulator
7396 * @start_scan: row at the desc table to start scan from
7397 * @buff: power descriptor buffer
7398 *
7399 * Returns calculated max ICC level for specific regulator
7400 */
7401static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7402 const char *buff)
7403{
7404 int i;
7405 int curr_uA;
7406 u16 data;
7407 u16 unit;
7408
7409 for (i = start_scan; i >= 0; i--) {
7410 data = get_unaligned_be16(&buff[2 * i]);
7411 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7412 ATTR_ICC_LVL_UNIT_OFFSET;
7413 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7414 switch (unit) {
7415 case UFSHCD_NANO_AMP:
7416 curr_uA = curr_uA / 1000;
7417 break;
7418 case UFSHCD_MILI_AMP:
7419 curr_uA = curr_uA * 1000;
7420 break;
7421 case UFSHCD_AMP:
7422 curr_uA = curr_uA * 1000 * 1000;
7423 break;
7424 case UFSHCD_MICRO_AMP:
7425 default:
7426 break;
7427 }
7428 if (sup_curr_uA >= curr_uA)
7429 break;
7430 }
7431 if (i < 0) {
7432 i = 0;
7433 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7434 }
7435
7436 return (u32)i;
7437}
7438
7439/**
7440 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7441 * In case regulators are not initialized we'll return 0
7442 * @hba: per-adapter instance
7443 * @desc_buf: power descriptor buffer to extract ICC levels from.
7444 * @len: length of desc_buff
7445 *
7446 * Returns calculated ICC level
7447 */
7448static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7449 const u8 *desc_buf, int len)
7450{
7451 u32 icc_level = 0;
7452
7453 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7454 !hba->vreg_info.vccq2) {
7455 /*
7456 * Using dev_dbg to avoid messages during runtime PM to avoid
7457 * never-ending cycles of messages written back to storage by
7458 * user space causing runtime resume, causing more messages and
7459 * so on.
7460 */
7461 dev_dbg(hba->dev,
7462 "%s: Regulator capability was not set, actvIccLevel=%d",
7463 __func__, icc_level);
7464 goto out;
7465 }
7466
7467 if (hba->vreg_info.vcc->max_uA)
7468 icc_level = ufshcd_get_max_icc_level(
7469 hba->vreg_info.vcc->max_uA,
7470 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7471 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7472
7473 if (hba->vreg_info.vccq->max_uA)
7474 icc_level = ufshcd_get_max_icc_level(
7475 hba->vreg_info.vccq->max_uA,
7476 icc_level,
7477 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7478
7479 if (hba->vreg_info.vccq2->max_uA)
7480 icc_level = ufshcd_get_max_icc_level(
7481 hba->vreg_info.vccq2->max_uA,
7482 icc_level,
7483 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7484out:
7485 return icc_level;
7486}
7487
7488static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7489{
7490 int ret;
7491 int buff_len = hba->desc_size[QUERY_DESC_IDN_POWER];
7492 u8 *desc_buf;
7493 u32 icc_level;
7494
7495 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7496 if (!desc_buf)
7497 return;
7498
7499 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7500 desc_buf, buff_len);
7501 if (ret) {
7502 dev_err(hba->dev,
7503 "%s: Failed reading power descriptor.len = %d ret = %d",
7504 __func__, buff_len, ret);
7505 goto out;
7506 }
7507
7508 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf,
7509 buff_len);
7510 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7511
7512 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7513 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7514
7515 if (ret)
7516 dev_err(hba->dev,
7517 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7518 __func__, icc_level, ret);
7519
7520out:
7521 kfree(desc_buf);
7522}
7523
7524static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7525{
7526 scsi_autopm_get_device(sdev);
7527 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7528 if (sdev->rpm_autosuspend)
7529 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7530 RPM_AUTOSUSPEND_DELAY_MS);
7531 scsi_autopm_put_device(sdev);
7532}
7533
7534/**
7535 * ufshcd_scsi_add_wlus - Adds required W-LUs
7536 * @hba: per-adapter instance
7537 *
7538 * UFS device specification requires the UFS devices to support 4 well known
7539 * logical units:
7540 * "REPORT_LUNS" (address: 01h)
7541 * "UFS Device" (address: 50h)
7542 * "RPMB" (address: 44h)
7543 * "BOOT" (address: 30h)
7544 * UFS device's power management needs to be controlled by "POWER CONDITION"
7545 * field of SSU (START STOP UNIT) command. But this "power condition" field
7546 * will take effect only when its sent to "UFS device" well known logical unit
7547 * hence we require the scsi_device instance to represent this logical unit in
7548 * order for the UFS host driver to send the SSU command for power management.
7549 *
7550 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7551 * Block) LU so user space process can control this LU. User space may also
7552 * want to have access to BOOT LU.
7553 *
7554 * This function adds scsi device instances for each of all well known LUs
7555 * (except "REPORT LUNS" LU).
7556 *
7557 * Returns zero on success (all required W-LUs are added successfully),
7558 * non-zero error value on failure (if failed to add any of the required W-LU).
7559 */
7560static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7561{
7562 int ret = 0;
7563 struct scsi_device *sdev_boot, *sdev_rpmb;
7564
7565 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7566 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7567 if (IS_ERR(hba->ufs_device_wlun)) {
7568 ret = PTR_ERR(hba->ufs_device_wlun);
7569 hba->ufs_device_wlun = NULL;
7570 goto out;
7571 }
7572 scsi_device_put(hba->ufs_device_wlun);
7573
7574 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
7575 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7576 if (IS_ERR(sdev_rpmb)) {
7577 ret = PTR_ERR(sdev_rpmb);
7578 goto remove_ufs_device_wlun;
7579 }
7580 ufshcd_blk_pm_runtime_init(sdev_rpmb);
7581 scsi_device_put(sdev_rpmb);
7582
7583 sdev_boot = __scsi_add_device(hba->host, 0, 0,
7584 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7585 if (IS_ERR(sdev_boot)) {
7586 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
7587 } else {
7588 ufshcd_blk_pm_runtime_init(sdev_boot);
7589 scsi_device_put(sdev_boot);
7590 }
7591 goto out;
7592
7593remove_ufs_device_wlun:
7594 scsi_remove_device(hba->ufs_device_wlun);
7595out:
7596 return ret;
7597}
7598
7599static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
7600{
7601 struct ufs_dev_info *dev_info = &hba->dev_info;
7602 u8 lun;
7603 u32 d_lu_wb_buf_alloc;
7604 u32 ext_ufs_feature;
7605
7606 if (!ufshcd_is_wb_allowed(hba))
7607 return;
7608
7609 /*
7610 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
7611 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
7612 * enabled
7613 */
7614 if (!(dev_info->wspecversion >= 0x310 ||
7615 dev_info->wspecversion == 0x220 ||
7616 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
7617 goto wb_disabled;
7618
7619 if (hba->desc_size[QUERY_DESC_IDN_DEVICE] <
7620 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP + 4)
7621 goto wb_disabled;
7622
7623 ext_ufs_feature = get_unaligned_be32(desc_buf +
7624 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7625
7626 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
7627 goto wb_disabled;
7628
7629 /*
7630 * WB may be supported but not configured while provisioning. The spec
7631 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
7632 * buffer configured.
7633 */
7634 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
7635
7636 dev_info->b_presrv_uspc_en =
7637 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
7638
7639 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
7640 if (!get_unaligned_be32(desc_buf +
7641 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
7642 goto wb_disabled;
7643 } else {
7644 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
7645 d_lu_wb_buf_alloc = 0;
7646 ufshcd_read_unit_desc_param(hba,
7647 lun,
7648 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
7649 (u8 *)&d_lu_wb_buf_alloc,
7650 sizeof(d_lu_wb_buf_alloc));
7651 if (d_lu_wb_buf_alloc) {
7652 dev_info->wb_dedicated_lu = lun;
7653 break;
7654 }
7655 }
7656
7657 if (!d_lu_wb_buf_alloc)
7658 goto wb_disabled;
7659 }
7660
7661 if (!ufshcd_is_wb_buf_lifetime_available(hba))
7662 goto wb_disabled;
7663
7664 return;
7665
7666wb_disabled:
7667 hba->caps &= ~UFSHCD_CAP_WB_EN;
7668}
7669
7670static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
7671{
7672 struct ufs_dev_info *dev_info = &hba->dev_info;
7673 u32 ext_ufs_feature;
7674 u8 mask = 0;
7675
7676 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
7677 return;
7678
7679 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
7680
7681 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
7682 mask |= MASK_EE_TOO_LOW_TEMP;
7683
7684 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
7685 mask |= MASK_EE_TOO_HIGH_TEMP;
7686
7687 if (mask) {
7688 ufshcd_enable_ee(hba, mask);
7689 ufs_hwmon_probe(hba, mask);
7690 }
7691}
7692
7693void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
7694 const struct ufs_dev_quirk *fixups)
7695{
7696 const struct ufs_dev_quirk *f;
7697 struct ufs_dev_info *dev_info = &hba->dev_info;
7698
7699 if (!fixups)
7700 return;
7701
7702 for (f = fixups; f->quirk; f++) {
7703 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
7704 f->wmanufacturerid == UFS_ANY_VENDOR) &&
7705 ((dev_info->model &&
7706 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
7707 !strcmp(f->model, UFS_ANY_MODEL)))
7708 hba->dev_quirks |= f->quirk;
7709 }
7710}
7711EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
7712
7713static void ufs_fixup_device_setup(struct ufs_hba *hba)
7714{
7715 /* fix by general quirk table */
7716 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
7717
7718 /* allow vendors to fix quirks */
7719 ufshcd_vops_fixup_dev_quirks(hba);
7720}
7721
7722static int ufs_get_device_desc(struct ufs_hba *hba)
7723{
7724 int err;
7725 u8 model_index;
7726 u8 b_ufs_feature_sup;
7727 u8 *desc_buf;
7728 struct ufs_dev_info *dev_info = &hba->dev_info;
7729
7730 desc_buf = kmalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7731 if (!desc_buf) {
7732 err = -ENOMEM;
7733 goto out;
7734 }
7735
7736 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
7737 hba->desc_size[QUERY_DESC_IDN_DEVICE]);
7738 if (err) {
7739 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
7740 __func__, err);
7741 goto out;
7742 }
7743
7744 /*
7745 * getting vendor (manufacturerID) and Bank Index in big endian
7746 * format
7747 */
7748 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
7749 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
7750
7751 /* getting Specification Version in big endian format */
7752 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
7753 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
7754 b_ufs_feature_sup = desc_buf[DEVICE_DESC_PARAM_UFS_FEAT];
7755
7756 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
7757
7758 if (dev_info->wspecversion >= UFS_DEV_HPB_SUPPORT_VERSION &&
7759 (b_ufs_feature_sup & UFS_DEV_HPB_SUPPORT)) {
7760 bool hpb_en = false;
7761
7762 ufshpb_get_dev_info(hba, desc_buf);
7763
7764 if (!ufshpb_is_legacy(hba))
7765 err = ufshcd_query_flag_retry(hba,
7766 UPIU_QUERY_OPCODE_READ_FLAG,
7767 QUERY_FLAG_IDN_HPB_EN, 0,
7768 &hpb_en);
7769
7770 if (ufshpb_is_legacy(hba) || (!err && hpb_en))
7771 dev_info->hpb_enabled = true;
7772 }
7773
7774 err = ufshcd_read_string_desc(hba, model_index,
7775 &dev_info->model, SD_ASCII_STD);
7776 if (err < 0) {
7777 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
7778 __func__, err);
7779 goto out;
7780 }
7781
7782 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
7783 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
7784
7785 ufs_fixup_device_setup(hba);
7786
7787 ufshcd_wb_probe(hba, desc_buf);
7788
7789 ufshcd_temp_notif_probe(hba, desc_buf);
7790
7791 /*
7792 * ufshcd_read_string_desc returns size of the string
7793 * reset the error value
7794 */
7795 err = 0;
7796
7797out:
7798 kfree(desc_buf);
7799 return err;
7800}
7801
7802static void ufs_put_device_desc(struct ufs_hba *hba)
7803{
7804 struct ufs_dev_info *dev_info = &hba->dev_info;
7805
7806 kfree(dev_info->model);
7807 dev_info->model = NULL;
7808}
7809
7810/**
7811 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
7812 * @hba: per-adapter instance
7813 *
7814 * PA_TActivate parameter can be tuned manually if UniPro version is less than
7815 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
7816 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
7817 * the hibern8 exit latency.
7818 *
7819 * Returns zero on success, non-zero error value on failure.
7820 */
7821static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
7822{
7823 int ret = 0;
7824 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
7825
7826 ret = ufshcd_dme_peer_get(hba,
7827 UIC_ARG_MIB_SEL(
7828 RX_MIN_ACTIVATETIME_CAPABILITY,
7829 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7830 &peer_rx_min_activatetime);
7831 if (ret)
7832 goto out;
7833
7834 /* make sure proper unit conversion is applied */
7835 tuned_pa_tactivate =
7836 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
7837 / PA_TACTIVATE_TIME_UNIT_US);
7838 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7839 tuned_pa_tactivate);
7840
7841out:
7842 return ret;
7843}
7844
7845/**
7846 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
7847 * @hba: per-adapter instance
7848 *
7849 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
7850 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
7851 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
7852 * This optimal value can help reduce the hibern8 exit latency.
7853 *
7854 * Returns zero on success, non-zero error value on failure.
7855 */
7856static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
7857{
7858 int ret = 0;
7859 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
7860 u32 max_hibern8_time, tuned_pa_hibern8time;
7861
7862 ret = ufshcd_dme_get(hba,
7863 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
7864 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
7865 &local_tx_hibern8_time_cap);
7866 if (ret)
7867 goto out;
7868
7869 ret = ufshcd_dme_peer_get(hba,
7870 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
7871 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
7872 &peer_rx_hibern8_time_cap);
7873 if (ret)
7874 goto out;
7875
7876 max_hibern8_time = max(local_tx_hibern8_time_cap,
7877 peer_rx_hibern8_time_cap);
7878 /* make sure proper unit conversion is applied */
7879 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
7880 / PA_HIBERN8_TIME_UNIT_US);
7881 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
7882 tuned_pa_hibern8time);
7883out:
7884 return ret;
7885}
7886
7887/**
7888 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
7889 * less than device PA_TACTIVATE time.
7890 * @hba: per-adapter instance
7891 *
7892 * Some UFS devices require host PA_TACTIVATE to be lower than device
7893 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
7894 * for such devices.
7895 *
7896 * Returns zero on success, non-zero error value on failure.
7897 */
7898static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
7899{
7900 int ret = 0;
7901 u32 granularity, peer_granularity;
7902 u32 pa_tactivate, peer_pa_tactivate;
7903 u32 pa_tactivate_us, peer_pa_tactivate_us;
7904 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
7905
7906 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7907 &granularity);
7908 if (ret)
7909 goto out;
7910
7911 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
7912 &peer_granularity);
7913 if (ret)
7914 goto out;
7915
7916 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
7917 (granularity > PA_GRANULARITY_MAX_VAL)) {
7918 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
7919 __func__, granularity);
7920 return -EINVAL;
7921 }
7922
7923 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
7924 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
7925 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
7926 __func__, peer_granularity);
7927 return -EINVAL;
7928 }
7929
7930 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
7931 if (ret)
7932 goto out;
7933
7934 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
7935 &peer_pa_tactivate);
7936 if (ret)
7937 goto out;
7938
7939 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
7940 peer_pa_tactivate_us = peer_pa_tactivate *
7941 gran_to_us_table[peer_granularity - 1];
7942
7943 if (pa_tactivate_us >= peer_pa_tactivate_us) {
7944 u32 new_peer_pa_tactivate;
7945
7946 new_peer_pa_tactivate = pa_tactivate_us /
7947 gran_to_us_table[peer_granularity - 1];
7948 new_peer_pa_tactivate++;
7949 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
7950 new_peer_pa_tactivate);
7951 }
7952
7953out:
7954 return ret;
7955}
7956
7957static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
7958{
7959 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
7960 ufshcd_tune_pa_tactivate(hba);
7961 ufshcd_tune_pa_hibern8time(hba);
7962 }
7963
7964 ufshcd_vops_apply_dev_quirks(hba);
7965
7966 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
7967 /* set 1ms timeout for PA_TACTIVATE */
7968 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
7969
7970 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
7971 ufshcd_quirk_tune_host_pa_tactivate(hba);
7972}
7973
7974static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
7975{
7976 hba->ufs_stats.hibern8_exit_cnt = 0;
7977 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
7978 hba->req_abort_count = 0;
7979}
7980
7981static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
7982{
7983 int err;
7984 size_t buff_len;
7985 u8 *desc_buf;
7986
7987 buff_len = hba->desc_size[QUERY_DESC_IDN_GEOMETRY];
7988 desc_buf = kmalloc(buff_len, GFP_KERNEL);
7989 if (!desc_buf) {
7990 err = -ENOMEM;
7991 goto out;
7992 }
7993
7994 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
7995 desc_buf, buff_len);
7996 if (err) {
7997 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
7998 __func__, err);
7999 goto out;
8000 }
8001
8002 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8003 hba->dev_info.max_lu_supported = 32;
8004 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8005 hba->dev_info.max_lu_supported = 8;
8006
8007 if (hba->desc_size[QUERY_DESC_IDN_GEOMETRY] >=
8008 GEOMETRY_DESC_PARAM_HPB_MAX_ACTIVE_REGS)
8009 ufshpb_get_geo_info(hba, desc_buf);
8010
8011out:
8012 kfree(desc_buf);
8013 return err;
8014}
8015
8016struct ufs_ref_clk {
8017 unsigned long freq_hz;
8018 enum ufs_ref_clk_freq val;
8019};
8020
8021static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8022 {19200000, REF_CLK_FREQ_19_2_MHZ},
8023 {26000000, REF_CLK_FREQ_26_MHZ},
8024 {38400000, REF_CLK_FREQ_38_4_MHZ},
8025 {52000000, REF_CLK_FREQ_52_MHZ},
8026 {0, REF_CLK_FREQ_INVAL},
8027};
8028
8029static enum ufs_ref_clk_freq
8030ufs_get_bref_clk_from_hz(unsigned long freq)
8031{
8032 int i;
8033
8034 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8035 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8036 return ufs_ref_clk_freqs[i].val;
8037
8038 return REF_CLK_FREQ_INVAL;
8039}
8040
8041void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8042{
8043 unsigned long freq;
8044
8045 freq = clk_get_rate(refclk);
8046
8047 hba->dev_ref_clk_freq =
8048 ufs_get_bref_clk_from_hz(freq);
8049
8050 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8051 dev_err(hba->dev,
8052 "invalid ref_clk setting = %ld\n", freq);
8053}
8054
8055static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8056{
8057 int err;
8058 u32 ref_clk;
8059 u32 freq = hba->dev_ref_clk_freq;
8060
8061 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8062 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8063
8064 if (err) {
8065 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8066 err);
8067 goto out;
8068 }
8069
8070 if (ref_clk == freq)
8071 goto out; /* nothing to update */
8072
8073 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8074 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8075
8076 if (err) {
8077 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8078 ufs_ref_clk_freqs[freq].freq_hz);
8079 goto out;
8080 }
8081
8082 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8083 ufs_ref_clk_freqs[freq].freq_hz);
8084
8085out:
8086 return err;
8087}
8088
8089static int ufshcd_device_params_init(struct ufs_hba *hba)
8090{
8091 bool flag;
8092 int ret, i;
8093
8094 /* Init device descriptor sizes */
8095 for (i = 0; i < QUERY_DESC_IDN_MAX; i++)
8096 hba->desc_size[i] = QUERY_DESC_MAX_SIZE;
8097
8098 /* Init UFS geometry descriptor related parameters */
8099 ret = ufshcd_device_geo_params_init(hba);
8100 if (ret)
8101 goto out;
8102
8103 /* Check and apply UFS device quirks */
8104 ret = ufs_get_device_desc(hba);
8105 if (ret) {
8106 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8107 __func__, ret);
8108 goto out;
8109 }
8110
8111 ufshcd_get_ref_clk_gating_wait(hba);
8112
8113 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8114 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8115 hba->dev_info.f_power_on_wp_en = flag;
8116
8117 /* Probe maximum power mode co-supported by both UFS host and device */
8118 if (ufshcd_get_max_pwr_mode(hba))
8119 dev_err(hba->dev,
8120 "%s: Failed getting max supported power mode\n",
8121 __func__);
8122out:
8123 return ret;
8124}
8125
8126/**
8127 * ufshcd_add_lus - probe and add UFS logical units
8128 * @hba: per-adapter instance
8129 */
8130static int ufshcd_add_lus(struct ufs_hba *hba)
8131{
8132 int ret;
8133
8134 /* Add required well known logical units to scsi mid layer */
8135 ret = ufshcd_scsi_add_wlus(hba);
8136 if (ret)
8137 goto out;
8138
8139 /* Initialize devfreq after UFS device is detected */
8140 if (ufshcd_is_clkscaling_supported(hba)) {
8141 memcpy(&hba->clk_scaling.saved_pwr_info.info,
8142 &hba->pwr_info,
8143 sizeof(struct ufs_pa_layer_attr));
8144 hba->clk_scaling.saved_pwr_info.is_valid = true;
8145 hba->clk_scaling.is_allowed = true;
8146
8147 ret = ufshcd_devfreq_init(hba);
8148 if (ret)
8149 goto out;
8150
8151 hba->clk_scaling.is_enabled = true;
8152 ufshcd_init_clk_scaling_sysfs(hba);
8153 }
8154
8155 ufs_bsg_probe(hba);
8156 ufshpb_init(hba);
8157 scsi_scan_host(hba->host);
8158 pm_runtime_put_sync(hba->dev);
8159
8160out:
8161 return ret;
8162}
8163
8164/**
8165 * ufshcd_probe_hba - probe hba to detect device and initialize it
8166 * @hba: per-adapter instance
8167 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8168 *
8169 * Execute link-startup and verify device initialization
8170 */
8171static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8172{
8173 int ret;
8174 unsigned long flags;
8175 ktime_t start = ktime_get();
8176
8177 hba->ufshcd_state = UFSHCD_STATE_RESET;
8178
8179 ret = ufshcd_link_startup(hba);
8180 if (ret)
8181 goto out;
8182
8183 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8184 goto out;
8185
8186 /* Debug counters initialization */
8187 ufshcd_clear_dbg_ufs_stats(hba);
8188
8189 /* UniPro link is active now */
8190 ufshcd_set_link_active(hba);
8191
8192 /* Verify device initialization by sending NOP OUT UPIU */
8193 ret = ufshcd_verify_dev_init(hba);
8194 if (ret)
8195 goto out;
8196
8197 /* Initiate UFS initialization, and waiting until completion */
8198 ret = ufshcd_complete_dev_init(hba);
8199 if (ret)
8200 goto out;
8201
8202 /*
8203 * Initialize UFS device parameters used by driver, these
8204 * parameters are associated with UFS descriptors.
8205 */
8206 if (init_dev_params) {
8207 ret = ufshcd_device_params_init(hba);
8208 if (ret)
8209 goto out;
8210 }
8211
8212 ufshcd_tune_unipro_params(hba);
8213
8214 /* UFS device is also active now */
8215 ufshcd_set_ufs_dev_active(hba);
8216 ufshcd_force_reset_auto_bkops(hba);
8217
8218 /* Gear up to HS gear if supported */
8219 if (hba->max_pwr_info.is_valid) {
8220 /*
8221 * Set the right value to bRefClkFreq before attempting to
8222 * switch to HS gears.
8223 */
8224 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8225 ufshcd_set_dev_ref_clk(hba);
8226 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8227 if (ret) {
8228 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8229 __func__, ret);
8230 goto out;
8231 }
8232 ufshcd_print_pwr_info(hba);
8233 }
8234
8235 /*
8236 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8237 * and for removable UFS card as well, hence always set the parameter.
8238 * Note: Error handler may issue the device reset hence resetting
8239 * bActiveICCLevel as well so it is always safe to set this here.
8240 */
8241 ufshcd_set_active_icc_lvl(hba);
8242
8243 /* Enable UFS Write Booster if supported */
8244 ufshcd_configure_wb(hba);
8245
8246 if (hba->ee_usr_mask)
8247 ufshcd_write_ee_control(hba);
8248 /* Enable Auto-Hibernate if configured */
8249 ufshcd_auto_hibern8_enable(hba);
8250
8251 ufshpb_toggle_state(hba, HPB_RESET, HPB_PRESENT);
8252out:
8253 spin_lock_irqsave(hba->host->host_lock, flags);
8254 if (ret)
8255 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8256 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8257 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8258 spin_unlock_irqrestore(hba->host->host_lock, flags);
8259
8260 trace_ufshcd_init(dev_name(hba->dev), ret,
8261 ktime_to_us(ktime_sub(ktime_get(), start)),
8262 hba->curr_dev_pwr_mode, hba->uic_link_state);
8263 return ret;
8264}
8265
8266/**
8267 * ufshcd_async_scan - asynchronous execution for probing hba
8268 * @data: data pointer to pass to this function
8269 * @cookie: cookie data
8270 */
8271static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8272{
8273 struct ufs_hba *hba = (struct ufs_hba *)data;
8274 int ret;
8275
8276 down(&hba->host_sem);
8277 /* Initialize hba, detect and initialize UFS device */
8278 ret = ufshcd_probe_hba(hba, true);
8279 up(&hba->host_sem);
8280 if (ret)
8281 goto out;
8282
8283 /* Probe and add UFS logical units */
8284 ret = ufshcd_add_lus(hba);
8285out:
8286 /*
8287 * If we failed to initialize the device or the device is not
8288 * present, turn off the power/clocks etc.
8289 */
8290 if (ret) {
8291 pm_runtime_put_sync(hba->dev);
8292 ufshcd_hba_exit(hba);
8293 }
8294}
8295
8296static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8297{
8298 struct ufs_hba *hba = shost_priv(scmd->device->host);
8299
8300 if (!hba->system_suspending) {
8301 /* Activate the error handler in the SCSI core. */
8302 return SCSI_EH_NOT_HANDLED;
8303 }
8304
8305 /*
8306 * If we get here we know that no TMFs are outstanding and also that
8307 * the only pending command is a START STOP UNIT command. Handle the
8308 * timeout of that command directly to prevent a deadlock between
8309 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8310 */
8311 ufshcd_link_recovery(hba);
8312 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8313 __func__, hba->outstanding_tasks);
8314
8315 return hba->outstanding_reqs ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8316}
8317
8318static const struct attribute_group *ufshcd_driver_groups[] = {
8319 &ufs_sysfs_unit_descriptor_group,
8320 &ufs_sysfs_lun_attributes_group,
8321#ifdef CONFIG_SCSI_UFS_HPB
8322 &ufs_sysfs_hpb_stat_group,
8323 &ufs_sysfs_hpb_param_group,
8324#endif
8325 NULL,
8326};
8327
8328static struct ufs_hba_variant_params ufs_hba_vps = {
8329 .hba_enable_delay_us = 1000,
8330 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
8331 .devfreq_profile.polling_ms = 100,
8332 .devfreq_profile.target = ufshcd_devfreq_target,
8333 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
8334 .ondemand_data.upthreshold = 70,
8335 .ondemand_data.downdifferential = 5,
8336};
8337
8338static struct scsi_host_template ufshcd_driver_template = {
8339 .module = THIS_MODULE,
8340 .name = UFSHCD,
8341 .proc_name = UFSHCD,
8342 .map_queues = ufshcd_map_queues,
8343 .queuecommand = ufshcd_queuecommand,
8344 .mq_poll = ufshcd_poll,
8345 .slave_alloc = ufshcd_slave_alloc,
8346 .slave_configure = ufshcd_slave_configure,
8347 .slave_destroy = ufshcd_slave_destroy,
8348 .change_queue_depth = ufshcd_change_queue_depth,
8349 .eh_abort_handler = ufshcd_abort,
8350 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
8351 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
8352 .eh_timed_out = ufshcd_eh_timed_out,
8353 .this_id = -1,
8354 .sg_tablesize = SG_ALL,
8355 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
8356 .can_queue = UFSHCD_CAN_QUEUE,
8357 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
8358 .max_sectors = (1 << 20) / SECTOR_SIZE, /* 1 MiB */
8359 .max_host_blocked = 1,
8360 .track_queue_depth = 1,
8361 .sdev_groups = ufshcd_driver_groups,
8362 .dma_boundary = PAGE_SIZE - 1,
8363 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
8364};
8365
8366static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
8367 int ua)
8368{
8369 int ret;
8370
8371 if (!vreg)
8372 return 0;
8373
8374 /*
8375 * "set_load" operation shall be required on those regulators
8376 * which specifically configured current limitation. Otherwise
8377 * zero max_uA may cause unexpected behavior when regulator is
8378 * enabled or set as high power mode.
8379 */
8380 if (!vreg->max_uA)
8381 return 0;
8382
8383 ret = regulator_set_load(vreg->reg, ua);
8384 if (ret < 0) {
8385 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
8386 __func__, vreg->name, ua, ret);
8387 }
8388
8389 return ret;
8390}
8391
8392static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
8393 struct ufs_vreg *vreg)
8394{
8395 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
8396}
8397
8398static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
8399 struct ufs_vreg *vreg)
8400{
8401 if (!vreg)
8402 return 0;
8403
8404 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
8405}
8406
8407static int ufshcd_config_vreg(struct device *dev,
8408 struct ufs_vreg *vreg, bool on)
8409{
8410 if (regulator_count_voltages(vreg->reg) <= 0)
8411 return 0;
8412
8413 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
8414}
8415
8416static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
8417{
8418 int ret = 0;
8419
8420 if (!vreg || vreg->enabled)
8421 goto out;
8422
8423 ret = ufshcd_config_vreg(dev, vreg, true);
8424 if (!ret)
8425 ret = regulator_enable(vreg->reg);
8426
8427 if (!ret)
8428 vreg->enabled = true;
8429 else
8430 dev_err(dev, "%s: %s enable failed, err=%d\n",
8431 __func__, vreg->name, ret);
8432out:
8433 return ret;
8434}
8435
8436static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
8437{
8438 int ret = 0;
8439
8440 if (!vreg || !vreg->enabled || vreg->always_on)
8441 goto out;
8442
8443 ret = regulator_disable(vreg->reg);
8444
8445 if (!ret) {
8446 /* ignore errors on applying disable config */
8447 ufshcd_config_vreg(dev, vreg, false);
8448 vreg->enabled = false;
8449 } else {
8450 dev_err(dev, "%s: %s disable failed, err=%d\n",
8451 __func__, vreg->name, ret);
8452 }
8453out:
8454 return ret;
8455}
8456
8457static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
8458{
8459 int ret = 0;
8460 struct device *dev = hba->dev;
8461 struct ufs_vreg_info *info = &hba->vreg_info;
8462
8463 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
8464 if (ret)
8465 goto out;
8466
8467 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
8468 if (ret)
8469 goto out;
8470
8471 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
8472
8473out:
8474 if (ret) {
8475 ufshcd_toggle_vreg(dev, info->vccq2, false);
8476 ufshcd_toggle_vreg(dev, info->vccq, false);
8477 ufshcd_toggle_vreg(dev, info->vcc, false);
8478 }
8479 return ret;
8480}
8481
8482static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
8483{
8484 struct ufs_vreg_info *info = &hba->vreg_info;
8485
8486 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
8487}
8488
8489int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
8490{
8491 int ret = 0;
8492
8493 if (!vreg)
8494 goto out;
8495
8496 vreg->reg = devm_regulator_get(dev, vreg->name);
8497 if (IS_ERR(vreg->reg)) {
8498 ret = PTR_ERR(vreg->reg);
8499 dev_err(dev, "%s: %s get failed, err=%d\n",
8500 __func__, vreg->name, ret);
8501 }
8502out:
8503 return ret;
8504}
8505EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
8506
8507static int ufshcd_init_vreg(struct ufs_hba *hba)
8508{
8509 int ret = 0;
8510 struct device *dev = hba->dev;
8511 struct ufs_vreg_info *info = &hba->vreg_info;
8512
8513 ret = ufshcd_get_vreg(dev, info->vcc);
8514 if (ret)
8515 goto out;
8516
8517 ret = ufshcd_get_vreg(dev, info->vccq);
8518 if (!ret)
8519 ret = ufshcd_get_vreg(dev, info->vccq2);
8520out:
8521 return ret;
8522}
8523
8524static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
8525{
8526 struct ufs_vreg_info *info = &hba->vreg_info;
8527
8528 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
8529}
8530
8531static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
8532{
8533 int ret = 0;
8534 struct ufs_clk_info *clki;
8535 struct list_head *head = &hba->clk_list_head;
8536 unsigned long flags;
8537 ktime_t start = ktime_get();
8538 bool clk_state_changed = false;
8539
8540 if (list_empty(head))
8541 goto out;
8542
8543 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
8544 if (ret)
8545 return ret;
8546
8547 list_for_each_entry(clki, head, list) {
8548 if (!IS_ERR_OR_NULL(clki->clk)) {
8549 /*
8550 * Don't disable clocks which are needed
8551 * to keep the link active.
8552 */
8553 if (ufshcd_is_link_active(hba) &&
8554 clki->keep_link_active)
8555 continue;
8556
8557 clk_state_changed = on ^ clki->enabled;
8558 if (on && !clki->enabled) {
8559 ret = clk_prepare_enable(clki->clk);
8560 if (ret) {
8561 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
8562 __func__, clki->name, ret);
8563 goto out;
8564 }
8565 } else if (!on && clki->enabled) {
8566 clk_disable_unprepare(clki->clk);
8567 }
8568 clki->enabled = on;
8569 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
8570 clki->name, on ? "en" : "dis");
8571 }
8572 }
8573
8574 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
8575 if (ret)
8576 return ret;
8577
8578out:
8579 if (ret) {
8580 list_for_each_entry(clki, head, list) {
8581 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
8582 clk_disable_unprepare(clki->clk);
8583 }
8584 } else if (!ret && on) {
8585 spin_lock_irqsave(hba->host->host_lock, flags);
8586 hba->clk_gating.state = CLKS_ON;
8587 trace_ufshcd_clk_gating(dev_name(hba->dev),
8588 hba->clk_gating.state);
8589 spin_unlock_irqrestore(hba->host->host_lock, flags);
8590 }
8591
8592 if (clk_state_changed)
8593 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
8594 (on ? "on" : "off"),
8595 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
8596 return ret;
8597}
8598
8599static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
8600{
8601 u32 freq;
8602 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
8603
8604 if (ret) {
8605 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
8606 return REF_CLK_FREQ_INVAL;
8607 }
8608
8609 return ufs_get_bref_clk_from_hz(freq);
8610}
8611
8612static int ufshcd_init_clocks(struct ufs_hba *hba)
8613{
8614 int ret = 0;
8615 struct ufs_clk_info *clki;
8616 struct device *dev = hba->dev;
8617 struct list_head *head = &hba->clk_list_head;
8618
8619 if (list_empty(head))
8620 goto out;
8621
8622 list_for_each_entry(clki, head, list) {
8623 if (!clki->name)
8624 continue;
8625
8626 clki->clk = devm_clk_get(dev, clki->name);
8627 if (IS_ERR(clki->clk)) {
8628 ret = PTR_ERR(clki->clk);
8629 dev_err(dev, "%s: %s clk get failed, %d\n",
8630 __func__, clki->name, ret);
8631 goto out;
8632 }
8633
8634 /*
8635 * Parse device ref clk freq as per device tree "ref_clk".
8636 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
8637 * in ufshcd_alloc_host().
8638 */
8639 if (!strcmp(clki->name, "ref_clk"))
8640 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
8641
8642 if (clki->max_freq) {
8643 ret = clk_set_rate(clki->clk, clki->max_freq);
8644 if (ret) {
8645 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
8646 __func__, clki->name,
8647 clki->max_freq, ret);
8648 goto out;
8649 }
8650 clki->curr_freq = clki->max_freq;
8651 }
8652 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
8653 clki->name, clk_get_rate(clki->clk));
8654 }
8655out:
8656 return ret;
8657}
8658
8659static int ufshcd_variant_hba_init(struct ufs_hba *hba)
8660{
8661 int err = 0;
8662
8663 if (!hba->vops)
8664 goto out;
8665
8666 err = ufshcd_vops_init(hba);
8667 if (err)
8668 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
8669 __func__, ufshcd_get_var_name(hba), err);
8670out:
8671 return err;
8672}
8673
8674static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
8675{
8676 if (!hba->vops)
8677 return;
8678
8679 ufshcd_vops_exit(hba);
8680}
8681
8682static int ufshcd_hba_init(struct ufs_hba *hba)
8683{
8684 int err;
8685
8686 /*
8687 * Handle host controller power separately from the UFS device power
8688 * rails as it will help controlling the UFS host controller power
8689 * collapse easily which is different than UFS device power collapse.
8690 * Also, enable the host controller power before we go ahead with rest
8691 * of the initialization here.
8692 */
8693 err = ufshcd_init_hba_vreg(hba);
8694 if (err)
8695 goto out;
8696
8697 err = ufshcd_setup_hba_vreg(hba, true);
8698 if (err)
8699 goto out;
8700
8701 err = ufshcd_init_clocks(hba);
8702 if (err)
8703 goto out_disable_hba_vreg;
8704
8705 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8706 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
8707
8708 err = ufshcd_setup_clocks(hba, true);
8709 if (err)
8710 goto out_disable_hba_vreg;
8711
8712 err = ufshcd_init_vreg(hba);
8713 if (err)
8714 goto out_disable_clks;
8715
8716 err = ufshcd_setup_vreg(hba, true);
8717 if (err)
8718 goto out_disable_clks;
8719
8720 err = ufshcd_variant_hba_init(hba);
8721 if (err)
8722 goto out_disable_vreg;
8723
8724 ufs_debugfs_hba_init(hba);
8725
8726 hba->is_powered = true;
8727 goto out;
8728
8729out_disable_vreg:
8730 ufshcd_setup_vreg(hba, false);
8731out_disable_clks:
8732 ufshcd_setup_clocks(hba, false);
8733out_disable_hba_vreg:
8734 ufshcd_setup_hba_vreg(hba, false);
8735out:
8736 return err;
8737}
8738
8739static void ufshcd_hba_exit(struct ufs_hba *hba)
8740{
8741 if (hba->is_powered) {
8742 ufshcd_exit_clk_scaling(hba);
8743 ufshcd_exit_clk_gating(hba);
8744 if (hba->eh_wq)
8745 destroy_workqueue(hba->eh_wq);
8746 ufs_debugfs_hba_exit(hba);
8747 ufshcd_variant_hba_exit(hba);
8748 ufshcd_setup_vreg(hba, false);
8749 ufshcd_setup_clocks(hba, false);
8750 ufshcd_setup_hba_vreg(hba, false);
8751 hba->is_powered = false;
8752 ufs_put_device_desc(hba);
8753 }
8754}
8755
8756static int ufshcd_execute_start_stop(struct scsi_device *sdev,
8757 enum ufs_dev_pwr_mode pwr_mode,
8758 struct scsi_sense_hdr *sshdr)
8759{
8760 unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
8761 struct request *req;
8762 struct scsi_cmnd *scmd;
8763 int ret;
8764
8765 req = scsi_alloc_request(sdev->request_queue, REQ_OP_DRV_IN,
8766 BLK_MQ_REQ_PM);
8767 if (IS_ERR(req))
8768 return PTR_ERR(req);
8769
8770 scmd = blk_mq_rq_to_pdu(req);
8771 scmd->cmd_len = COMMAND_SIZE(cdb[0]);
8772 memcpy(scmd->cmnd, cdb, scmd->cmd_len);
8773 scmd->allowed = 0/*retries*/;
8774 scmd->flags |= SCMD_FAIL_IF_RECOVERING;
8775 req->timeout = 1 * HZ;
8776 req->rq_flags |= RQF_PM | RQF_QUIET;
8777
8778 blk_execute_rq(req, /*at_head=*/true);
8779
8780 if (sshdr)
8781 scsi_normalize_sense(scmd->sense_buffer, scmd->sense_len,
8782 sshdr);
8783 ret = scmd->result;
8784
8785 blk_mq_free_request(req);
8786
8787 return ret;
8788}
8789
8790/**
8791 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
8792 * power mode
8793 * @hba: per adapter instance
8794 * @pwr_mode: device power mode to set
8795 *
8796 * Returns 0 if requested power mode is set successfully
8797 * Returns < 0 if failed to set the requested power mode
8798 */
8799static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
8800 enum ufs_dev_pwr_mode pwr_mode)
8801{
8802 struct scsi_sense_hdr sshdr;
8803 struct scsi_device *sdp;
8804 unsigned long flags;
8805 int ret, retries;
8806
8807 spin_lock_irqsave(hba->host->host_lock, flags);
8808 sdp = hba->ufs_device_wlun;
8809 if (sdp && scsi_device_online(sdp))
8810 ret = scsi_device_get(sdp);
8811 else
8812 ret = -ENODEV;
8813 spin_unlock_irqrestore(hba->host->host_lock, flags);
8814
8815 if (ret)
8816 return ret;
8817
8818 /*
8819 * If scsi commands fail, the scsi mid-layer schedules scsi error-
8820 * handling, which would wait for host to be resumed. Since we know
8821 * we are functional while we are here, skip host resume in error
8822 * handling context.
8823 */
8824 hba->host->eh_noresume = 1;
8825
8826 /*
8827 * Current function would be generally called from the power management
8828 * callbacks hence set the RQF_PM flag so that it doesn't resume the
8829 * already suspended childs.
8830 */
8831 for (retries = 3; retries > 0; --retries) {
8832 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
8833 /*
8834 * scsi_execute() only returns a negative value if the request
8835 * queue is dying.
8836 */
8837 if (ret <= 0)
8838 break;
8839 }
8840 if (ret) {
8841 sdev_printk(KERN_WARNING, sdp,
8842 "START_STOP failed for power mode: %d, result %x\n",
8843 pwr_mode, ret);
8844 if (ret > 0) {
8845 if (scsi_sense_valid(&sshdr))
8846 scsi_print_sense_hdr(sdp, NULL, &sshdr);
8847 ret = -EIO;
8848 }
8849 } else {
8850 hba->curr_dev_pwr_mode = pwr_mode;
8851 }
8852
8853 scsi_device_put(sdp);
8854 hba->host->eh_noresume = 0;
8855 return ret;
8856}
8857
8858static int ufshcd_link_state_transition(struct ufs_hba *hba,
8859 enum uic_link_state req_link_state,
8860 bool check_for_bkops)
8861{
8862 int ret = 0;
8863
8864 if (req_link_state == hba->uic_link_state)
8865 return 0;
8866
8867 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
8868 ret = ufshcd_uic_hibern8_enter(hba);
8869 if (!ret) {
8870 ufshcd_set_link_hibern8(hba);
8871 } else {
8872 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8873 __func__, ret);
8874 goto out;
8875 }
8876 }
8877 /*
8878 * If autobkops is enabled, link can't be turned off because
8879 * turning off the link would also turn off the device, except in the
8880 * case of DeepSleep where the device is expected to remain powered.
8881 */
8882 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
8883 (!check_for_bkops || !hba->auto_bkops_enabled)) {
8884 /*
8885 * Let's make sure that link is in low power mode, we are doing
8886 * this currently by putting the link in Hibern8. Otherway to
8887 * put the link in low power mode is to send the DME end point
8888 * to device and then send the DME reset command to local
8889 * unipro. But putting the link in hibern8 is much faster.
8890 *
8891 * Note also that putting the link in Hibern8 is a requirement
8892 * for entering DeepSleep.
8893 */
8894 ret = ufshcd_uic_hibern8_enter(hba);
8895 if (ret) {
8896 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
8897 __func__, ret);
8898 goto out;
8899 }
8900 /*
8901 * Change controller state to "reset state" which
8902 * should also put the link in off/reset state
8903 */
8904 ufshcd_hba_stop(hba);
8905 /*
8906 * TODO: Check if we need any delay to make sure that
8907 * controller is reset
8908 */
8909 ufshcd_set_link_off(hba);
8910 }
8911
8912out:
8913 return ret;
8914}
8915
8916static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
8917{
8918 bool vcc_off = false;
8919
8920 /*
8921 * It seems some UFS devices may keep drawing more than sleep current
8922 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
8923 * To avoid this situation, add 2ms delay before putting these UFS
8924 * rails in LPM mode.
8925 */
8926 if (!ufshcd_is_link_active(hba) &&
8927 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
8928 usleep_range(2000, 2100);
8929
8930 /*
8931 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
8932 * power.
8933 *
8934 * If UFS device and link is in OFF state, all power supplies (VCC,
8935 * VCCQ, VCCQ2) can be turned off if power on write protect is not
8936 * required. If UFS link is inactive (Hibern8 or OFF state) and device
8937 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
8938 *
8939 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
8940 * in low power state which would save some power.
8941 *
8942 * If Write Booster is enabled and the device needs to flush the WB
8943 * buffer OR if bkops status is urgent for WB, keep Vcc on.
8944 */
8945 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8946 !hba->dev_info.is_lu_power_on_wp) {
8947 ufshcd_setup_vreg(hba, false);
8948 vcc_off = true;
8949 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8950 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8951 vcc_off = true;
8952 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
8953 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8954 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
8955 }
8956 }
8957
8958 /*
8959 * Some UFS devices require delay after VCC power rail is turned-off.
8960 */
8961 if (vcc_off && hba->vreg_info.vcc &&
8962 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
8963 usleep_range(5000, 5100);
8964}
8965
8966#ifdef CONFIG_PM
8967static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
8968{
8969 int ret = 0;
8970
8971 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
8972 !hba->dev_info.is_lu_power_on_wp) {
8973 ret = ufshcd_setup_vreg(hba, true);
8974 } else if (!ufshcd_is_ufs_dev_active(hba)) {
8975 if (!ufshcd_is_link_active(hba)) {
8976 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
8977 if (ret)
8978 goto vcc_disable;
8979 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
8980 if (ret)
8981 goto vccq_lpm;
8982 }
8983 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
8984 }
8985 goto out;
8986
8987vccq_lpm:
8988 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
8989vcc_disable:
8990 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
8991out:
8992 return ret;
8993}
8994#endif /* CONFIG_PM */
8995
8996static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
8997{
8998 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
8999 ufshcd_setup_hba_vreg(hba, false);
9000}
9001
9002static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9003{
9004 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9005 ufshcd_setup_hba_vreg(hba, true);
9006}
9007
9008static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9009{
9010 int ret = 0;
9011 bool check_for_bkops;
9012 enum ufs_pm_level pm_lvl;
9013 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9014 enum uic_link_state req_link_state;
9015
9016 hba->pm_op_in_progress = true;
9017 if (pm_op != UFS_SHUTDOWN_PM) {
9018 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9019 hba->rpm_lvl : hba->spm_lvl;
9020 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9021 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9022 } else {
9023 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9024 req_link_state = UIC_LINK_OFF_STATE;
9025 }
9026
9027 ufshpb_suspend(hba);
9028
9029 /*
9030 * If we can't transition into any of the low power modes
9031 * just gate the clocks.
9032 */
9033 ufshcd_hold(hba, false);
9034 hba->clk_gating.is_suspended = true;
9035
9036 if (ufshcd_is_clkscaling_supported(hba))
9037 ufshcd_clk_scaling_suspend(hba, true);
9038
9039 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9040 req_link_state == UIC_LINK_ACTIVE_STATE) {
9041 goto vops_suspend;
9042 }
9043
9044 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9045 (req_link_state == hba->uic_link_state))
9046 goto enable_scaling;
9047
9048 /* UFS device & link must be active before we enter in this function */
9049 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9050 ret = -EINVAL;
9051 goto enable_scaling;
9052 }
9053
9054 if (pm_op == UFS_RUNTIME_PM) {
9055 if (ufshcd_can_autobkops_during_suspend(hba)) {
9056 /*
9057 * The device is idle with no requests in the queue,
9058 * allow background operations if bkops status shows
9059 * that performance might be impacted.
9060 */
9061 ret = ufshcd_urgent_bkops(hba);
9062 if (ret)
9063 goto enable_scaling;
9064 } else {
9065 /* make sure that auto bkops is disabled */
9066 ufshcd_disable_auto_bkops(hba);
9067 }
9068 /*
9069 * If device needs to do BKOP or WB buffer flush during
9070 * Hibern8, keep device power mode as "active power mode"
9071 * and VCC supply.
9072 */
9073 hba->dev_info.b_rpm_dev_flush_capable =
9074 hba->auto_bkops_enabled ||
9075 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9076 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9077 ufshcd_is_auto_hibern8_enabled(hba))) &&
9078 ufshcd_wb_need_flush(hba));
9079 }
9080
9081 flush_work(&hba->eeh_work);
9082
9083 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9084 if (ret)
9085 goto enable_scaling;
9086
9087 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9088 if (pm_op != UFS_RUNTIME_PM)
9089 /* ensure that bkops is disabled */
9090 ufshcd_disable_auto_bkops(hba);
9091
9092 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9093 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9094 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9095 /*
9096 * If return err in suspend flow, IO will hang.
9097 * Trigger error handler and break suspend for
9098 * error recovery.
9099 */
9100 ufshcd_force_error_recovery(hba);
9101 ret = -EBUSY;
9102 }
9103 if (ret)
9104 goto enable_scaling;
9105 }
9106 }
9107
9108 /*
9109 * In the case of DeepSleep, the device is expected to remain powered
9110 * with the link off, so do not check for bkops.
9111 */
9112 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9113 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9114 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9115 /*
9116 * If return err in suspend flow, IO will hang.
9117 * Trigger error handler and break suspend for
9118 * error recovery.
9119 */
9120 ufshcd_force_error_recovery(hba);
9121 ret = -EBUSY;
9122 }
9123 if (ret)
9124 goto set_dev_active;
9125
9126vops_suspend:
9127 /*
9128 * Call vendor specific suspend callback. As these callbacks may access
9129 * vendor specific host controller register space call them before the
9130 * host clocks are ON.
9131 */
9132 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9133 if (ret)
9134 goto set_link_active;
9135 goto out;
9136
9137set_link_active:
9138 /*
9139 * Device hardware reset is required to exit DeepSleep. Also, for
9140 * DeepSleep, the link is off so host reset and restore will be done
9141 * further below.
9142 */
9143 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9144 ufshcd_device_reset(hba);
9145 WARN_ON(!ufshcd_is_link_off(hba));
9146 }
9147 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9148 ufshcd_set_link_active(hba);
9149 else if (ufshcd_is_link_off(hba))
9150 ufshcd_host_reset_and_restore(hba);
9151set_dev_active:
9152 /* Can also get here needing to exit DeepSleep */
9153 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9154 ufshcd_device_reset(hba);
9155 ufshcd_host_reset_and_restore(hba);
9156 }
9157 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9158 ufshcd_disable_auto_bkops(hba);
9159enable_scaling:
9160 if (ufshcd_is_clkscaling_supported(hba))
9161 ufshcd_clk_scaling_suspend(hba, false);
9162
9163 hba->dev_info.b_rpm_dev_flush_capable = false;
9164out:
9165 if (hba->dev_info.b_rpm_dev_flush_capable) {
9166 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9167 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9168 }
9169
9170 if (ret) {
9171 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9172 hba->clk_gating.is_suspended = false;
9173 ufshcd_release(hba);
9174 ufshpb_resume(hba);
9175 }
9176 hba->pm_op_in_progress = false;
9177 return ret;
9178}
9179
9180#ifdef CONFIG_PM
9181static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9182{
9183 int ret;
9184 enum uic_link_state old_link_state = hba->uic_link_state;
9185
9186 hba->pm_op_in_progress = true;
9187
9188 /*
9189 * Call vendor specific resume callback. As these callbacks may access
9190 * vendor specific host controller register space call them when the
9191 * host clocks are ON.
9192 */
9193 ret = ufshcd_vops_resume(hba, pm_op);
9194 if (ret)
9195 goto out;
9196
9197 /* For DeepSleep, the only supported option is to have the link off */
9198 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9199
9200 if (ufshcd_is_link_hibern8(hba)) {
9201 ret = ufshcd_uic_hibern8_exit(hba);
9202 if (!ret) {
9203 ufshcd_set_link_active(hba);
9204 } else {
9205 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9206 __func__, ret);
9207 goto vendor_suspend;
9208 }
9209 } else if (ufshcd_is_link_off(hba)) {
9210 /*
9211 * A full initialization of the host and the device is
9212 * required since the link was put to off during suspend.
9213 * Note, in the case of DeepSleep, the device will exit
9214 * DeepSleep due to device reset.
9215 */
9216 ret = ufshcd_reset_and_restore(hba);
9217 /*
9218 * ufshcd_reset_and_restore() should have already
9219 * set the link state as active
9220 */
9221 if (ret || !ufshcd_is_link_active(hba))
9222 goto vendor_suspend;
9223 }
9224
9225 if (!ufshcd_is_ufs_dev_active(hba)) {
9226 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9227 if (ret)
9228 goto set_old_link_state;
9229 }
9230
9231 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9232 ufshcd_enable_auto_bkops(hba);
9233 else
9234 /*
9235 * If BKOPs operations are urgently needed at this moment then
9236 * keep auto-bkops enabled or else disable it.
9237 */
9238 ufshcd_urgent_bkops(hba);
9239
9240 if (hba->ee_usr_mask)
9241 ufshcd_write_ee_control(hba);
9242
9243 if (ufshcd_is_clkscaling_supported(hba))
9244 ufshcd_clk_scaling_suspend(hba, false);
9245
9246 if (hba->dev_info.b_rpm_dev_flush_capable) {
9247 hba->dev_info.b_rpm_dev_flush_capable = false;
9248 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9249 }
9250
9251 /* Enable Auto-Hibernate if configured */
9252 ufshcd_auto_hibern8_enable(hba);
9253
9254 ufshpb_resume(hba);
9255 goto out;
9256
9257set_old_link_state:
9258 ufshcd_link_state_transition(hba, old_link_state, 0);
9259vendor_suspend:
9260 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9261 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9262out:
9263 if (ret)
9264 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9265 hba->clk_gating.is_suspended = false;
9266 ufshcd_release(hba);
9267 hba->pm_op_in_progress = false;
9268 return ret;
9269}
9270
9271static int ufshcd_wl_runtime_suspend(struct device *dev)
9272{
9273 struct scsi_device *sdev = to_scsi_device(dev);
9274 struct ufs_hba *hba;
9275 int ret;
9276 ktime_t start = ktime_get();
9277
9278 hba = shost_priv(sdev->host);
9279
9280 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9281 if (ret)
9282 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9283
9284 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9285 ktime_to_us(ktime_sub(ktime_get(), start)),
9286 hba->curr_dev_pwr_mode, hba->uic_link_state);
9287
9288 return ret;
9289}
9290
9291static int ufshcd_wl_runtime_resume(struct device *dev)
9292{
9293 struct scsi_device *sdev = to_scsi_device(dev);
9294 struct ufs_hba *hba;
9295 int ret = 0;
9296 ktime_t start = ktime_get();
9297
9298 hba = shost_priv(sdev->host);
9299
9300 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9301 if (ret)
9302 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9303
9304 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9305 ktime_to_us(ktime_sub(ktime_get(), start)),
9306 hba->curr_dev_pwr_mode, hba->uic_link_state);
9307
9308 return ret;
9309}
9310#endif
9311
9312#ifdef CONFIG_PM_SLEEP
9313static int ufshcd_wl_suspend(struct device *dev)
9314{
9315 struct scsi_device *sdev = to_scsi_device(dev);
9316 struct ufs_hba *hba;
9317 int ret = 0;
9318 ktime_t start = ktime_get();
9319
9320 hba = shost_priv(sdev->host);
9321 down(&hba->host_sem);
9322 hba->system_suspending = true;
9323
9324 if (pm_runtime_suspended(dev))
9325 goto out;
9326
9327 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9328 if (ret) {
9329 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9330 up(&hba->host_sem);
9331 }
9332
9333out:
9334 if (!ret)
9335 hba->is_sys_suspended = true;
9336 trace_ufshcd_wl_suspend(dev_name(dev), ret,
9337 ktime_to_us(ktime_sub(ktime_get(), start)),
9338 hba->curr_dev_pwr_mode, hba->uic_link_state);
9339
9340 return ret;
9341}
9342
9343static int ufshcd_wl_resume(struct device *dev)
9344{
9345 struct scsi_device *sdev = to_scsi_device(dev);
9346 struct ufs_hba *hba;
9347 int ret = 0;
9348 ktime_t start = ktime_get();
9349
9350 hba = shost_priv(sdev->host);
9351
9352 if (pm_runtime_suspended(dev))
9353 goto out;
9354
9355 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
9356 if (ret)
9357 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9358out:
9359 trace_ufshcd_wl_resume(dev_name(dev), ret,
9360 ktime_to_us(ktime_sub(ktime_get(), start)),
9361 hba->curr_dev_pwr_mode, hba->uic_link_state);
9362 if (!ret)
9363 hba->is_sys_suspended = false;
9364 hba->system_suspending = false;
9365 up(&hba->host_sem);
9366 return ret;
9367}
9368#endif
9369
9370static void ufshcd_wl_shutdown(struct device *dev)
9371{
9372 struct scsi_device *sdev = to_scsi_device(dev);
9373 struct ufs_hba *hba;
9374
9375 hba = shost_priv(sdev->host);
9376
9377 down(&hba->host_sem);
9378 hba->shutting_down = true;
9379 up(&hba->host_sem);
9380
9381 /* Turn on everything while shutting down */
9382 ufshcd_rpm_get_sync(hba);
9383 scsi_device_quiesce(sdev);
9384 shost_for_each_device(sdev, hba->host) {
9385 if (sdev == hba->ufs_device_wlun)
9386 continue;
9387 scsi_device_quiesce(sdev);
9388 }
9389 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9390}
9391
9392/**
9393 * ufshcd_suspend - helper function for suspend operations
9394 * @hba: per adapter instance
9395 *
9396 * This function will put disable irqs, turn off clocks
9397 * and set vreg and hba-vreg in lpm mode.
9398 */
9399static int ufshcd_suspend(struct ufs_hba *hba)
9400{
9401 int ret;
9402
9403 if (!hba->is_powered)
9404 return 0;
9405 /*
9406 * Disable the host irq as host controller as there won't be any
9407 * host controller transaction expected till resume.
9408 */
9409 ufshcd_disable_irq(hba);
9410 ret = ufshcd_setup_clocks(hba, false);
9411 if (ret) {
9412 ufshcd_enable_irq(hba);
9413 return ret;
9414 }
9415 if (ufshcd_is_clkgating_allowed(hba)) {
9416 hba->clk_gating.state = CLKS_OFF;
9417 trace_ufshcd_clk_gating(dev_name(hba->dev),
9418 hba->clk_gating.state);
9419 }
9420
9421 ufshcd_vreg_set_lpm(hba);
9422 /* Put the host controller in low power mode if possible */
9423 ufshcd_hba_vreg_set_lpm(hba);
9424 return ret;
9425}
9426
9427#ifdef CONFIG_PM
9428/**
9429 * ufshcd_resume - helper function for resume operations
9430 * @hba: per adapter instance
9431 *
9432 * This function basically turns on the regulators, clocks and
9433 * irqs of the hba.
9434 *
9435 * Returns 0 for success and non-zero for failure
9436 */
9437static int ufshcd_resume(struct ufs_hba *hba)
9438{
9439 int ret;
9440
9441 if (!hba->is_powered)
9442 return 0;
9443
9444 ufshcd_hba_vreg_set_hpm(hba);
9445 ret = ufshcd_vreg_set_hpm(hba);
9446 if (ret)
9447 goto out;
9448
9449 /* Make sure clocks are enabled before accessing controller */
9450 ret = ufshcd_setup_clocks(hba, true);
9451 if (ret)
9452 goto disable_vreg;
9453
9454 /* enable the host irq as host controller would be active soon */
9455 ufshcd_enable_irq(hba);
9456 goto out;
9457
9458disable_vreg:
9459 ufshcd_vreg_set_lpm(hba);
9460out:
9461 if (ret)
9462 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
9463 return ret;
9464}
9465#endif /* CONFIG_PM */
9466
9467#ifdef CONFIG_PM_SLEEP
9468/**
9469 * ufshcd_system_suspend - system suspend callback
9470 * @dev: Device associated with the UFS controller.
9471 *
9472 * Executed before putting the system into a sleep state in which the contents
9473 * of main memory are preserved.
9474 *
9475 * Returns 0 for success and non-zero for failure
9476 */
9477int ufshcd_system_suspend(struct device *dev)
9478{
9479 struct ufs_hba *hba = dev_get_drvdata(dev);
9480 int ret = 0;
9481 ktime_t start = ktime_get();
9482
9483 if (pm_runtime_suspended(hba->dev))
9484 goto out;
9485
9486 ret = ufshcd_suspend(hba);
9487out:
9488 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
9489 ktime_to_us(ktime_sub(ktime_get(), start)),
9490 hba->curr_dev_pwr_mode, hba->uic_link_state);
9491 return ret;
9492}
9493EXPORT_SYMBOL(ufshcd_system_suspend);
9494
9495/**
9496 * ufshcd_system_resume - system resume callback
9497 * @dev: Device associated with the UFS controller.
9498 *
9499 * Executed after waking the system up from a sleep state in which the contents
9500 * of main memory were preserved.
9501 *
9502 * Returns 0 for success and non-zero for failure
9503 */
9504int ufshcd_system_resume(struct device *dev)
9505{
9506 struct ufs_hba *hba = dev_get_drvdata(dev);
9507 ktime_t start = ktime_get();
9508 int ret = 0;
9509
9510 if (pm_runtime_suspended(hba->dev))
9511 goto out;
9512
9513 ret = ufshcd_resume(hba);
9514
9515out:
9516 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
9517 ktime_to_us(ktime_sub(ktime_get(), start)),
9518 hba->curr_dev_pwr_mode, hba->uic_link_state);
9519
9520 return ret;
9521}
9522EXPORT_SYMBOL(ufshcd_system_resume);
9523#endif /* CONFIG_PM_SLEEP */
9524
9525#ifdef CONFIG_PM
9526/**
9527 * ufshcd_runtime_suspend - runtime suspend callback
9528 * @dev: Device associated with the UFS controller.
9529 *
9530 * Check the description of ufshcd_suspend() function for more details.
9531 *
9532 * Returns 0 for success and non-zero for failure
9533 */
9534int ufshcd_runtime_suspend(struct device *dev)
9535{
9536 struct ufs_hba *hba = dev_get_drvdata(dev);
9537 int ret;
9538 ktime_t start = ktime_get();
9539
9540 ret = ufshcd_suspend(hba);
9541
9542 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
9543 ktime_to_us(ktime_sub(ktime_get(), start)),
9544 hba->curr_dev_pwr_mode, hba->uic_link_state);
9545 return ret;
9546}
9547EXPORT_SYMBOL(ufshcd_runtime_suspend);
9548
9549/**
9550 * ufshcd_runtime_resume - runtime resume routine
9551 * @dev: Device associated with the UFS controller.
9552 *
9553 * This function basically brings controller
9554 * to active state. Following operations are done in this function:
9555 *
9556 * 1. Turn on all the controller related clocks
9557 * 2. Turn ON VCC rail
9558 */
9559int ufshcd_runtime_resume(struct device *dev)
9560{
9561 struct ufs_hba *hba = dev_get_drvdata(dev);
9562 int ret;
9563 ktime_t start = ktime_get();
9564
9565 ret = ufshcd_resume(hba);
9566
9567 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
9568 ktime_to_us(ktime_sub(ktime_get(), start)),
9569 hba->curr_dev_pwr_mode, hba->uic_link_state);
9570 return ret;
9571}
9572EXPORT_SYMBOL(ufshcd_runtime_resume);
9573#endif /* CONFIG_PM */
9574
9575/**
9576 * ufshcd_shutdown - shutdown routine
9577 * @hba: per adapter instance
9578 *
9579 * This function would turn off both UFS device and UFS hba
9580 * regulators. It would also disable clocks.
9581 *
9582 * Returns 0 always to allow force shutdown even in case of errors.
9583 */
9584int ufshcd_shutdown(struct ufs_hba *hba)
9585{
9586 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
9587 ufshcd_suspend(hba);
9588
9589 hba->is_powered = false;
9590 /* allow force shutdown even in case of errors */
9591 return 0;
9592}
9593EXPORT_SYMBOL(ufshcd_shutdown);
9594
9595/**
9596 * ufshcd_remove - de-allocate SCSI host and host memory space
9597 * data structure memory
9598 * @hba: per adapter instance
9599 */
9600void ufshcd_remove(struct ufs_hba *hba)
9601{
9602 if (hba->ufs_device_wlun)
9603 ufshcd_rpm_get_sync(hba);
9604 ufs_hwmon_remove(hba);
9605 ufs_bsg_remove(hba);
9606 ufshpb_remove(hba);
9607 ufs_sysfs_remove_nodes(hba->dev);
9608 blk_mq_destroy_queue(hba->tmf_queue);
9609 blk_put_queue(hba->tmf_queue);
9610 blk_mq_free_tag_set(&hba->tmf_tag_set);
9611 scsi_remove_host(hba->host);
9612 /* disable interrupts */
9613 ufshcd_disable_intr(hba, hba->intr_mask);
9614 ufshcd_hba_stop(hba);
9615 ufshcd_hba_exit(hba);
9616}
9617EXPORT_SYMBOL_GPL(ufshcd_remove);
9618
9619/**
9620 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
9621 * @hba: pointer to Host Bus Adapter (HBA)
9622 */
9623void ufshcd_dealloc_host(struct ufs_hba *hba)
9624{
9625 scsi_host_put(hba->host);
9626}
9627EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
9628
9629/**
9630 * ufshcd_set_dma_mask - Set dma mask based on the controller
9631 * addressing capability
9632 * @hba: per adapter instance
9633 *
9634 * Returns 0 for success, non-zero for failure
9635 */
9636static int ufshcd_set_dma_mask(struct ufs_hba *hba)
9637{
9638 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
9639 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
9640 return 0;
9641 }
9642 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
9643}
9644
9645/**
9646 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
9647 * @dev: pointer to device handle
9648 * @hba_handle: driver private handle
9649 * Returns 0 on success, non-zero value on failure
9650 */
9651int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
9652{
9653 struct Scsi_Host *host;
9654 struct ufs_hba *hba;
9655 int err = 0;
9656
9657 if (!dev) {
9658 dev_err(dev,
9659 "Invalid memory reference for dev is NULL\n");
9660 err = -ENODEV;
9661 goto out_error;
9662 }
9663
9664 host = scsi_host_alloc(&ufshcd_driver_template,
9665 sizeof(struct ufs_hba));
9666 if (!host) {
9667 dev_err(dev, "scsi_host_alloc failed\n");
9668 err = -ENOMEM;
9669 goto out_error;
9670 }
9671 host->nr_maps = HCTX_TYPE_POLL + 1;
9672 hba = shost_priv(host);
9673 hba->host = host;
9674 hba->dev = dev;
9675 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
9676 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
9677 INIT_LIST_HEAD(&hba->clk_list_head);
9678 spin_lock_init(&hba->outstanding_lock);
9679
9680 *hba_handle = hba;
9681
9682out_error:
9683 return err;
9684}
9685EXPORT_SYMBOL(ufshcd_alloc_host);
9686
9687/* This function exists because blk_mq_alloc_tag_set() requires this. */
9688static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
9689 const struct blk_mq_queue_data *qd)
9690{
9691 WARN_ON_ONCE(true);
9692 return BLK_STS_NOTSUPP;
9693}
9694
9695static const struct blk_mq_ops ufshcd_tmf_ops = {
9696 .queue_rq = ufshcd_queue_tmf,
9697};
9698
9699/**
9700 * ufshcd_init - Driver initialization routine
9701 * @hba: per-adapter instance
9702 * @mmio_base: base register address
9703 * @irq: Interrupt line of device
9704 * Returns 0 on success, non-zero value on failure
9705 */
9706int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
9707{
9708 int err;
9709 struct Scsi_Host *host = hba->host;
9710 struct device *dev = hba->dev;
9711 char eh_wq_name[sizeof("ufs_eh_wq_00")];
9712
9713 /*
9714 * dev_set_drvdata() must be called before any callbacks are registered
9715 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
9716 * sysfs).
9717 */
9718 dev_set_drvdata(dev, hba);
9719
9720 if (!mmio_base) {
9721 dev_err(hba->dev,
9722 "Invalid memory reference for mmio_base is NULL\n");
9723 err = -ENODEV;
9724 goto out_error;
9725 }
9726
9727 hba->mmio_base = mmio_base;
9728 hba->irq = irq;
9729 hba->vps = &ufs_hba_vps;
9730
9731 err = ufshcd_hba_init(hba);
9732 if (err)
9733 goto out_error;
9734
9735 /* Read capabilities registers */
9736 err = ufshcd_hba_capabilities(hba);
9737 if (err)
9738 goto out_disable;
9739
9740 /* Get UFS version supported by the controller */
9741 hba->ufs_version = ufshcd_get_ufs_version(hba);
9742
9743 /* Get Interrupt bit mask per version */
9744 hba->intr_mask = ufshcd_get_intr_mask(hba);
9745
9746 err = ufshcd_set_dma_mask(hba);
9747 if (err) {
9748 dev_err(hba->dev, "set dma mask failed\n");
9749 goto out_disable;
9750 }
9751
9752 /* Allocate memory for host memory space */
9753 err = ufshcd_memory_alloc(hba);
9754 if (err) {
9755 dev_err(hba->dev, "Memory allocation failed\n");
9756 goto out_disable;
9757 }
9758
9759 /* Configure LRB */
9760 ufshcd_host_memory_configure(hba);
9761
9762 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
9763 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
9764 host->max_id = UFSHCD_MAX_ID;
9765 host->max_lun = UFS_MAX_LUNS;
9766 host->max_channel = UFSHCD_MAX_CHANNEL;
9767 host->unique_id = host->host_no;
9768 host->max_cmd_len = UFS_CDB_SIZE;
9769
9770 hba->max_pwr_info.is_valid = false;
9771
9772 /* Initialize work queues */
9773 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
9774 hba->host->host_no);
9775 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
9776 if (!hba->eh_wq) {
9777 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
9778 __func__);
9779 err = -ENOMEM;
9780 goto out_disable;
9781 }
9782 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
9783 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
9784
9785 sema_init(&hba->host_sem, 1);
9786
9787 /* Initialize UIC command mutex */
9788 mutex_init(&hba->uic_cmd_mutex);
9789
9790 /* Initialize mutex for device management commands */
9791 mutex_init(&hba->dev_cmd.lock);
9792
9793 /* Initialize mutex for exception event control */
9794 mutex_init(&hba->ee_ctrl_mutex);
9795
9796 mutex_init(&hba->wb_mutex);
9797 init_rwsem(&hba->clk_scaling_lock);
9798
9799 ufshcd_init_clk_gating(hba);
9800
9801 ufshcd_init_clk_scaling(hba);
9802
9803 /*
9804 * In order to avoid any spurious interrupt immediately after
9805 * registering UFS controller interrupt handler, clear any pending UFS
9806 * interrupt status and disable all the UFS interrupts.
9807 */
9808 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
9809 REG_INTERRUPT_STATUS);
9810 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
9811 /*
9812 * Make sure that UFS interrupts are disabled and any pending interrupt
9813 * status is cleared before registering UFS interrupt handler.
9814 */
9815 mb();
9816
9817 /* IRQ registration */
9818 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
9819 if (err) {
9820 dev_err(hba->dev, "request irq failed\n");
9821 goto out_disable;
9822 } else {
9823 hba->is_irq_enabled = true;
9824 }
9825
9826 err = scsi_add_host(host, hba->dev);
9827 if (err) {
9828 dev_err(hba->dev, "scsi_add_host failed\n");
9829 goto out_disable;
9830 }
9831
9832 hba->tmf_tag_set = (struct blk_mq_tag_set) {
9833 .nr_hw_queues = 1,
9834 .queue_depth = hba->nutmrs,
9835 .ops = &ufshcd_tmf_ops,
9836 .flags = BLK_MQ_F_NO_SCHED,
9837 };
9838 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
9839 if (err < 0)
9840 goto out_remove_scsi_host;
9841 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
9842 if (IS_ERR(hba->tmf_queue)) {
9843 err = PTR_ERR(hba->tmf_queue);
9844 goto free_tmf_tag_set;
9845 }
9846 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
9847 sizeof(*hba->tmf_rqs), GFP_KERNEL);
9848 if (!hba->tmf_rqs) {
9849 err = -ENOMEM;
9850 goto free_tmf_queue;
9851 }
9852
9853 /* Reset the attached device */
9854 ufshcd_device_reset(hba);
9855
9856 ufshcd_init_crypto(hba);
9857
9858 /* Host controller enable */
9859 err = ufshcd_hba_enable(hba);
9860 if (err) {
9861 dev_err(hba->dev, "Host controller enable failed\n");
9862 ufshcd_print_evt_hist(hba);
9863 ufshcd_print_host_state(hba);
9864 goto free_tmf_queue;
9865 }
9866
9867 /*
9868 * Set the default power management level for runtime and system PM.
9869 * Default power saving mode is to keep UFS link in Hibern8 state
9870 * and UFS device in sleep state.
9871 */
9872 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9873 UFS_SLEEP_PWR_MODE,
9874 UIC_LINK_HIBERN8_STATE);
9875 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
9876 UFS_SLEEP_PWR_MODE,
9877 UIC_LINK_HIBERN8_STATE);
9878
9879 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work,
9880 ufshcd_rpm_dev_flush_recheck_work);
9881
9882 /* Set the default auto-hiberate idle timer value to 150 ms */
9883 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
9884 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
9885 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
9886 }
9887
9888 /* Hold auto suspend until async scan completes */
9889 pm_runtime_get_sync(dev);
9890 atomic_set(&hba->scsi_block_reqs_cnt, 0);
9891 /*
9892 * We are assuming that device wasn't put in sleep/power-down
9893 * state exclusively during the boot stage before kernel.
9894 * This assumption helps avoid doing link startup twice during
9895 * ufshcd_probe_hba().
9896 */
9897 ufshcd_set_ufs_dev_active(hba);
9898
9899 async_schedule(ufshcd_async_scan, hba);
9900 ufs_sysfs_add_nodes(hba->dev);
9901
9902 device_enable_async_suspend(dev);
9903 return 0;
9904
9905free_tmf_queue:
9906 blk_mq_destroy_queue(hba->tmf_queue);
9907 blk_put_queue(hba->tmf_queue);
9908free_tmf_tag_set:
9909 blk_mq_free_tag_set(&hba->tmf_tag_set);
9910out_remove_scsi_host:
9911 scsi_remove_host(hba->host);
9912out_disable:
9913 hba->is_irq_enabled = false;
9914 ufshcd_hba_exit(hba);
9915out_error:
9916 return err;
9917}
9918EXPORT_SYMBOL_GPL(ufshcd_init);
9919
9920void ufshcd_resume_complete(struct device *dev)
9921{
9922 struct ufs_hba *hba = dev_get_drvdata(dev);
9923
9924 if (hba->complete_put) {
9925 ufshcd_rpm_put(hba);
9926 hba->complete_put = false;
9927 }
9928}
9929EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
9930
9931static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
9932{
9933 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
9934 enum ufs_dev_pwr_mode dev_pwr_mode;
9935 enum uic_link_state link_state;
9936 unsigned long flags;
9937 bool res;
9938
9939 spin_lock_irqsave(&dev->power.lock, flags);
9940 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
9941 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
9942 res = pm_runtime_suspended(dev) &&
9943 hba->curr_dev_pwr_mode == dev_pwr_mode &&
9944 hba->uic_link_state == link_state &&
9945 !hba->dev_info.b_rpm_dev_flush_capable;
9946 spin_unlock_irqrestore(&dev->power.lock, flags);
9947
9948 return res;
9949}
9950
9951int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
9952{
9953 struct ufs_hba *hba = dev_get_drvdata(dev);
9954 int ret;
9955
9956 /*
9957 * SCSI assumes that runtime-pm and system-pm for scsi drivers
9958 * are same. And it doesn't wake up the device for system-suspend
9959 * if it's runtime suspended. But ufs doesn't follow that.
9960 * Refer ufshcd_resume_complete()
9961 */
9962 if (hba->ufs_device_wlun) {
9963 /* Prevent runtime suspend */
9964 ufshcd_rpm_get_noresume(hba);
9965 /*
9966 * Check if already runtime suspended in same state as system
9967 * suspend would be.
9968 */
9969 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
9970 /* RPM state is not ok for SPM, so runtime resume */
9971 ret = ufshcd_rpm_resume(hba);
9972 if (ret < 0 && ret != -EACCES) {
9973 ufshcd_rpm_put(hba);
9974 return ret;
9975 }
9976 }
9977 hba->complete_put = true;
9978 }
9979 return 0;
9980}
9981EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
9982
9983int ufshcd_suspend_prepare(struct device *dev)
9984{
9985 return __ufshcd_suspend_prepare(dev, true);
9986}
9987EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
9988
9989#ifdef CONFIG_PM_SLEEP
9990static int ufshcd_wl_poweroff(struct device *dev)
9991{
9992 struct scsi_device *sdev = to_scsi_device(dev);
9993 struct ufs_hba *hba = shost_priv(sdev->host);
9994
9995 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
9996 return 0;
9997}
9998#endif
9999
10000static int ufshcd_wl_probe(struct device *dev)
10001{
10002 struct scsi_device *sdev = to_scsi_device(dev);
10003
10004 if (!is_device_wlun(sdev))
10005 return -ENODEV;
10006
10007 blk_pm_runtime_init(sdev->request_queue, dev);
10008 pm_runtime_set_autosuspend_delay(dev, 0);
10009 pm_runtime_allow(dev);
10010
10011 return 0;
10012}
10013
10014static int ufshcd_wl_remove(struct device *dev)
10015{
10016 pm_runtime_forbid(dev);
10017 return 0;
10018}
10019
10020static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10021#ifdef CONFIG_PM_SLEEP
10022 .suspend = ufshcd_wl_suspend,
10023 .resume = ufshcd_wl_resume,
10024 .freeze = ufshcd_wl_suspend,
10025 .thaw = ufshcd_wl_resume,
10026 .poweroff = ufshcd_wl_poweroff,
10027 .restore = ufshcd_wl_resume,
10028#endif
10029 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10030};
10031
10032/*
10033 * ufs_dev_wlun_template - describes ufs device wlun
10034 * ufs-device wlun - used to send pm commands
10035 * All luns are consumers of ufs-device wlun.
10036 *
10037 * Currently, no sd driver is present for wluns.
10038 * Hence the no specific pm operations are performed.
10039 * With ufs design, SSU should be sent to ufs-device wlun.
10040 * Hence register a scsi driver for ufs wluns only.
10041 */
10042static struct scsi_driver ufs_dev_wlun_template = {
10043 .gendrv = {
10044 .name = "ufs_device_wlun",
10045 .owner = THIS_MODULE,
10046 .probe = ufshcd_wl_probe,
10047 .remove = ufshcd_wl_remove,
10048 .pm = &ufshcd_wl_pm_ops,
10049 .shutdown = ufshcd_wl_shutdown,
10050 },
10051};
10052
10053static int __init ufshcd_core_init(void)
10054{
10055 int ret;
10056
10057 /* Verify that there are no gaps in struct utp_transfer_cmd_desc. */
10058 static_assert(sizeof(struct utp_transfer_cmd_desc) ==
10059 2 * ALIGNED_UPIU_SIZE +
10060 SG_ALL * sizeof(struct ufshcd_sg_entry));
10061
10062 ufs_debugfs_init();
10063
10064 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10065 if (ret)
10066 ufs_debugfs_exit();
10067 return ret;
10068}
10069
10070static void __exit ufshcd_core_exit(void)
10071{
10072 ufs_debugfs_exit();
10073 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10074}
10075
10076module_init(ufshcd_core_init);
10077module_exit(ufshcd_core_exit);
10078
10079MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10080MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10081MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10082MODULE_LICENSE("GPL");