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