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