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