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 } else {
3033 err = -EINVAL;
3034 dev_err(hba->dev, "%s: unexpected response in Query RSP: %x\n",
3035 __func__, response);
3036 }
3037 break;
3038 }
3039 case UPIU_TRANSACTION_REJECT_UPIU:
3040 /* TODO: handle Reject UPIU Response */
3041 err = -EPERM;
3042 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
3043 __func__);
3044 break;
3045 case UPIU_TRANSACTION_RESPONSE:
3046 if (hba->dev_cmd.type != DEV_CMD_TYPE_RPMB) {
3047 err = -EINVAL;
3048 dev_err(hba->dev, "%s: unexpected response %x\n", __func__, resp);
3049 }
3050 break;
3051 default:
3052 err = -EINVAL;
3053 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
3054 __func__, resp);
3055 break;
3056 }
3057
3058 return err;
3059 }
3060
ufshcd_wait_for_dev_cmd(struct ufs_hba * hba,struct ufshcd_lrb * lrbp,int max_timeout)3061 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
3062 struct ufshcd_lrb *lrbp, int max_timeout)
3063 {
3064 unsigned long time_left = msecs_to_jiffies(max_timeout);
3065 unsigned long flags;
3066 bool pending;
3067 int err;
3068
3069 retry:
3070 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
3071 time_left);
3072
3073 if (likely(time_left)) {
3074 /*
3075 * The completion handler called complete() and the caller of
3076 * this function still owns the @lrbp tag so the code below does
3077 * not trigger any race conditions.
3078 */
3079 hba->dev_cmd.complete = NULL;
3080 err = ufshcd_get_tr_ocs(lrbp, NULL);
3081 if (!err)
3082 err = ufshcd_dev_cmd_completion(hba, lrbp);
3083 } else {
3084 err = -ETIMEDOUT;
3085 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
3086 __func__, lrbp->task_tag);
3087
3088 /* MCQ mode */
3089 if (is_mcq_enabled(hba)) {
3090 /* successfully cleared the command, retry if needed */
3091 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0)
3092 err = -EAGAIN;
3093 hba->dev_cmd.complete = NULL;
3094 return err;
3095 }
3096
3097 /* SDB mode */
3098 if (ufshcd_clear_cmd(hba, lrbp->task_tag) == 0) {
3099 /* successfully cleared the command, retry if needed */
3100 err = -EAGAIN;
3101 /*
3102 * Since clearing the command succeeded we also need to
3103 * clear the task tag bit from the outstanding_reqs
3104 * variable.
3105 */
3106 spin_lock_irqsave(&hba->outstanding_lock, flags);
3107 pending = test_bit(lrbp->task_tag,
3108 &hba->outstanding_reqs);
3109 if (pending) {
3110 hba->dev_cmd.complete = NULL;
3111 __clear_bit(lrbp->task_tag,
3112 &hba->outstanding_reqs);
3113 }
3114 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3115
3116 if (!pending) {
3117 /*
3118 * The completion handler ran while we tried to
3119 * clear the command.
3120 */
3121 time_left = 1;
3122 goto retry;
3123 }
3124 } else {
3125 dev_err(hba->dev, "%s: failed to clear tag %d\n",
3126 __func__, lrbp->task_tag);
3127
3128 spin_lock_irqsave(&hba->outstanding_lock, flags);
3129 pending = test_bit(lrbp->task_tag,
3130 &hba->outstanding_reqs);
3131 if (pending)
3132 hba->dev_cmd.complete = NULL;
3133 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
3134
3135 if (!pending) {
3136 /*
3137 * The completion handler ran while we tried to
3138 * clear the command.
3139 */
3140 time_left = 1;
3141 goto retry;
3142 }
3143 }
3144 }
3145
3146 return err;
3147 }
3148
3149 /**
3150 * ufshcd_exec_dev_cmd - API for sending device management requests
3151 * @hba: UFS hba
3152 * @cmd_type: specifies the type (NOP, Query...)
3153 * @timeout: timeout in milliseconds
3154 *
3155 * Return: 0 upon success; < 0 upon failure.
3156 *
3157 * NOTE: Since there is only one available tag for device management commands,
3158 * it is expected you hold the hba->dev_cmd.lock mutex.
3159 */
ufshcd_exec_dev_cmd(struct ufs_hba * hba,enum dev_cmd_type cmd_type,int timeout)3160 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
3161 enum dev_cmd_type cmd_type, int timeout)
3162 {
3163 DECLARE_COMPLETION_ONSTACK(wait);
3164 const u32 tag = hba->reserved_slot;
3165 struct ufshcd_lrb *lrbp;
3166 int err;
3167
3168 /* Protects use of hba->reserved_slot. */
3169 lockdep_assert_held(&hba->dev_cmd.lock);
3170
3171 down_read(&hba->clk_scaling_lock);
3172
3173 lrbp = &hba->lrb[tag];
3174 lrbp->cmd = NULL;
3175 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
3176 if (unlikely(err))
3177 goto out;
3178
3179 hba->dev_cmd.complete = &wait;
3180
3181 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
3182
3183 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
3184 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
3185 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
3186 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
3187
3188 out:
3189 up_read(&hba->clk_scaling_lock);
3190 return err;
3191 }
3192
3193 /**
3194 * ufshcd_init_query() - init the query response and request parameters
3195 * @hba: per-adapter instance
3196 * @request: address of the request pointer to be initialized
3197 * @response: address of the response pointer to be initialized
3198 * @opcode: operation to perform
3199 * @idn: flag idn to access
3200 * @index: LU number to access
3201 * @selector: query/flag/descriptor further identification
3202 */
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)3203 static inline void ufshcd_init_query(struct ufs_hba *hba,
3204 struct ufs_query_req **request, struct ufs_query_res **response,
3205 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
3206 {
3207 *request = &hba->dev_cmd.query.request;
3208 *response = &hba->dev_cmd.query.response;
3209 memset(*request, 0, sizeof(struct ufs_query_req));
3210 memset(*response, 0, sizeof(struct ufs_query_res));
3211 (*request)->upiu_req.opcode = opcode;
3212 (*request)->upiu_req.idn = idn;
3213 (*request)->upiu_req.index = index;
3214 (*request)->upiu_req.selector = selector;
3215 }
3216
ufshcd_query_flag_retry(struct ufs_hba * hba,enum query_opcode opcode,enum flag_idn idn,u8 index,bool * flag_res)3217 static int ufshcd_query_flag_retry(struct ufs_hba *hba,
3218 enum query_opcode opcode, enum flag_idn idn, u8 index, bool *flag_res)
3219 {
3220 int ret;
3221 int retries;
3222
3223 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
3224 ret = ufshcd_query_flag(hba, opcode, idn, index, flag_res);
3225 if (ret)
3226 dev_dbg(hba->dev,
3227 "%s: failed with error %d, retries %d\n",
3228 __func__, ret, retries);
3229 else
3230 break;
3231 }
3232
3233 if (ret)
3234 dev_err(hba->dev,
3235 "%s: query flag, opcode %d, idn %d, failed with error %d after %d retries\n",
3236 __func__, opcode, idn, ret, retries);
3237 return ret;
3238 }
3239
3240 /**
3241 * ufshcd_query_flag() - API function for sending flag query requests
3242 * @hba: per-adapter instance
3243 * @opcode: flag query to perform
3244 * @idn: flag idn to access
3245 * @index: flag index to access
3246 * @flag_res: the flag value after the query request completes
3247 *
3248 * Return: 0 for success, non-zero in case of failure.
3249 */
ufshcd_query_flag(struct ufs_hba * hba,enum query_opcode opcode,enum flag_idn idn,u8 index,bool * flag_res)3250 int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
3251 enum flag_idn idn, u8 index, bool *flag_res)
3252 {
3253 struct ufs_query_req *request = NULL;
3254 struct ufs_query_res *response = NULL;
3255 int err, selector = 0;
3256 int timeout = QUERY_REQ_TIMEOUT;
3257
3258 BUG_ON(!hba);
3259
3260 ufshcd_hold(hba);
3261 mutex_lock(&hba->dev_cmd.lock);
3262 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3263 selector);
3264
3265 switch (opcode) {
3266 case UPIU_QUERY_OPCODE_SET_FLAG:
3267 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
3268 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
3269 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3270 break;
3271 case UPIU_QUERY_OPCODE_READ_FLAG:
3272 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3273 if (!flag_res) {
3274 /* No dummy reads */
3275 dev_err(hba->dev, "%s: Invalid argument for read request\n",
3276 __func__);
3277 err = -EINVAL;
3278 goto out_unlock;
3279 }
3280 break;
3281 default:
3282 dev_err(hba->dev,
3283 "%s: Expected query flag opcode but got = %d\n",
3284 __func__, opcode);
3285 err = -EINVAL;
3286 goto out_unlock;
3287 }
3288
3289 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
3290
3291 if (err) {
3292 dev_err(hba->dev,
3293 "%s: Sending flag query for idn %d failed, err = %d\n",
3294 __func__, idn, err);
3295 goto out_unlock;
3296 }
3297
3298 if (flag_res)
3299 *flag_res = (be32_to_cpu(response->upiu_res.value) &
3300 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
3301
3302 out_unlock:
3303 mutex_unlock(&hba->dev_cmd.lock);
3304 ufshcd_release(hba);
3305 return err;
3306 }
3307
3308 /**
3309 * ufshcd_query_attr - API function for sending attribute requests
3310 * @hba: per-adapter instance
3311 * @opcode: attribute opcode
3312 * @idn: attribute idn to access
3313 * @index: index field
3314 * @selector: selector field
3315 * @attr_val: the attribute value after the query request completes
3316 *
3317 * Return: 0 for success, non-zero in case of failure.
3318 */
ufshcd_query_attr(struct ufs_hba * hba,enum query_opcode opcode,enum attr_idn idn,u8 index,u8 selector,u32 * attr_val)3319 int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
3320 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
3321 {
3322 struct ufs_query_req *request = NULL;
3323 struct ufs_query_res *response = NULL;
3324 int err;
3325
3326 BUG_ON(!hba);
3327
3328 if (!attr_val) {
3329 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
3330 __func__, opcode);
3331 return -EINVAL;
3332 }
3333
3334 ufshcd_hold(hba);
3335
3336 mutex_lock(&hba->dev_cmd.lock);
3337 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3338 selector);
3339
3340 switch (opcode) {
3341 case UPIU_QUERY_OPCODE_WRITE_ATTR:
3342 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3343 request->upiu_req.value = cpu_to_be32(*attr_val);
3344 break;
3345 case UPIU_QUERY_OPCODE_READ_ATTR:
3346 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3347 break;
3348 default:
3349 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
3350 __func__, opcode);
3351 err = -EINVAL;
3352 goto out_unlock;
3353 }
3354
3355 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3356
3357 if (err) {
3358 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3359 __func__, opcode, idn, index, err);
3360 goto out_unlock;
3361 }
3362
3363 *attr_val = be32_to_cpu(response->upiu_res.value);
3364
3365 out_unlock:
3366 mutex_unlock(&hba->dev_cmd.lock);
3367 ufshcd_release(hba);
3368 return err;
3369 }
3370
3371 /**
3372 * ufshcd_query_attr_retry() - API function for sending query
3373 * attribute with retries
3374 * @hba: per-adapter instance
3375 * @opcode: attribute opcode
3376 * @idn: attribute idn to access
3377 * @index: index field
3378 * @selector: selector field
3379 * @attr_val: the attribute value after the query request
3380 * completes
3381 *
3382 * Return: 0 for success, non-zero in case of failure.
3383 */
ufshcd_query_attr_retry(struct ufs_hba * hba,enum query_opcode opcode,enum attr_idn idn,u8 index,u8 selector,u32 * attr_val)3384 int ufshcd_query_attr_retry(struct ufs_hba *hba,
3385 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
3386 u32 *attr_val)
3387 {
3388 int ret = 0;
3389 u32 retries;
3390
3391 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3392 ret = ufshcd_query_attr(hba, opcode, idn, index,
3393 selector, attr_val);
3394 if (ret)
3395 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
3396 __func__, ret, retries);
3397 else
3398 break;
3399 }
3400
3401 if (ret)
3402 dev_err(hba->dev,
3403 "%s: query attribute, idn %d, failed with error %d after %d retries\n",
3404 __func__, idn, ret, QUERY_REQ_RETRIES);
3405 return ret;
3406 }
3407
__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)3408 static int __ufshcd_query_descriptor(struct ufs_hba *hba,
3409 enum query_opcode opcode, enum desc_idn idn, u8 index,
3410 u8 selector, u8 *desc_buf, int *buf_len)
3411 {
3412 struct ufs_query_req *request = NULL;
3413 struct ufs_query_res *response = NULL;
3414 int err;
3415
3416 BUG_ON(!hba);
3417
3418 if (!desc_buf) {
3419 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
3420 __func__, opcode);
3421 return -EINVAL;
3422 }
3423
3424 if (*buf_len < QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
3425 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
3426 __func__, *buf_len);
3427 return -EINVAL;
3428 }
3429
3430 ufshcd_hold(hba);
3431
3432 mutex_lock(&hba->dev_cmd.lock);
3433 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
3434 selector);
3435 hba->dev_cmd.query.descriptor = desc_buf;
3436 request->upiu_req.length = cpu_to_be16(*buf_len);
3437
3438 switch (opcode) {
3439 case UPIU_QUERY_OPCODE_WRITE_DESC:
3440 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
3441 break;
3442 case UPIU_QUERY_OPCODE_READ_DESC:
3443 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
3444 break;
3445 default:
3446 dev_err(hba->dev,
3447 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
3448 __func__, opcode);
3449 err = -EINVAL;
3450 goto out_unlock;
3451 }
3452
3453 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
3454
3455 if (err) {
3456 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, index %d, err = %d\n",
3457 __func__, opcode, idn, index, err);
3458 goto out_unlock;
3459 }
3460
3461 *buf_len = be16_to_cpu(response->upiu_res.length);
3462
3463 out_unlock:
3464 hba->dev_cmd.query.descriptor = NULL;
3465 mutex_unlock(&hba->dev_cmd.lock);
3466 ufshcd_release(hba);
3467 return err;
3468 }
3469
3470 /**
3471 * ufshcd_query_descriptor_retry - API function for sending descriptor requests
3472 * @hba: per-adapter instance
3473 * @opcode: attribute opcode
3474 * @idn: attribute idn to access
3475 * @index: index field
3476 * @selector: selector field
3477 * @desc_buf: the buffer that contains the descriptor
3478 * @buf_len: length parameter passed to the device
3479 *
3480 * The buf_len parameter will contain, on return, the length parameter
3481 * received on the response.
3482 *
3483 * Return: 0 for success, non-zero in case of failure.
3484 */
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)3485 int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
3486 enum query_opcode opcode,
3487 enum desc_idn idn, u8 index,
3488 u8 selector,
3489 u8 *desc_buf, int *buf_len)
3490 {
3491 int err;
3492 int retries;
3493
3494 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
3495 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
3496 selector, desc_buf, buf_len);
3497 if (!err || err == -EINVAL)
3498 break;
3499 }
3500
3501 return err;
3502 }
3503
3504 /**
3505 * ufshcd_read_desc_param - read the specified descriptor parameter
3506 * @hba: Pointer to adapter instance
3507 * @desc_id: descriptor idn value
3508 * @desc_index: descriptor index
3509 * @param_offset: offset of the parameter to read
3510 * @param_read_buf: pointer to buffer where parameter would be read
3511 * @param_size: sizeof(param_read_buf)
3512 *
3513 * Return: 0 in case of success, non-zero otherwise.
3514 */
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)3515 int ufshcd_read_desc_param(struct ufs_hba *hba,
3516 enum desc_idn desc_id,
3517 int desc_index,
3518 u8 param_offset,
3519 u8 *param_read_buf,
3520 u8 param_size)
3521 {
3522 int ret;
3523 u8 *desc_buf;
3524 int buff_len = QUERY_DESC_MAX_SIZE;
3525 bool is_kmalloc = true;
3526
3527 /* Safety check */
3528 if (desc_id >= QUERY_DESC_IDN_MAX || !param_size)
3529 return -EINVAL;
3530
3531 /* Check whether we need temp memory */
3532 if (param_offset != 0 || param_size < buff_len) {
3533 desc_buf = kzalloc(buff_len, GFP_KERNEL);
3534 if (!desc_buf)
3535 return -ENOMEM;
3536 } else {
3537 desc_buf = param_read_buf;
3538 is_kmalloc = false;
3539 }
3540
3541 /* Request for full descriptor */
3542 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
3543 desc_id, desc_index, 0,
3544 desc_buf, &buff_len);
3545 if (ret) {
3546 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d, desc_index %d, param_offset %d, ret %d\n",
3547 __func__, desc_id, desc_index, param_offset, ret);
3548 goto out;
3549 }
3550
3551 /* Update descriptor length */
3552 buff_len = desc_buf[QUERY_DESC_LENGTH_OFFSET];
3553
3554 if (param_offset >= buff_len) {
3555 dev_err(hba->dev, "%s: Invalid offset 0x%x in descriptor IDN 0x%x, length 0x%x\n",
3556 __func__, param_offset, desc_id, buff_len);
3557 ret = -EINVAL;
3558 goto out;
3559 }
3560
3561 /* Sanity check */
3562 if (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id) {
3563 dev_err(hba->dev, "%s: invalid desc_id %d in descriptor header\n",
3564 __func__, desc_buf[QUERY_DESC_DESC_TYPE_OFFSET]);
3565 ret = -EINVAL;
3566 goto out;
3567 }
3568
3569 if (is_kmalloc) {
3570 /* Make sure we don't copy more data than available */
3571 if (param_offset >= buff_len)
3572 ret = -EINVAL;
3573 else
3574 memcpy(param_read_buf, &desc_buf[param_offset],
3575 min_t(u32, param_size, buff_len - param_offset));
3576 }
3577 out:
3578 if (is_kmalloc)
3579 kfree(desc_buf);
3580 return ret;
3581 }
3582
3583 /**
3584 * struct uc_string_id - unicode string
3585 *
3586 * @len: size of this descriptor inclusive
3587 * @type: descriptor type
3588 * @uc: unicode string character
3589 */
3590 struct uc_string_id {
3591 u8 len;
3592 u8 type;
3593 wchar_t uc[];
3594 } __packed;
3595
3596 /* replace non-printable or non-ASCII characters with spaces */
ufshcd_remove_non_printable(u8 ch)3597 static inline char ufshcd_remove_non_printable(u8 ch)
3598 {
3599 return (ch >= 0x20 && ch <= 0x7e) ? ch : ' ';
3600 }
3601
3602 /**
3603 * ufshcd_read_string_desc - read string descriptor
3604 * @hba: pointer to adapter instance
3605 * @desc_index: descriptor index
3606 * @buf: pointer to buffer where descriptor would be read,
3607 * the caller should free the memory.
3608 * @ascii: if true convert from unicode to ascii characters
3609 * null terminated string.
3610 *
3611 * Return:
3612 * * string size on success.
3613 * * -ENOMEM: on allocation failure
3614 * * -EINVAL: on a wrong parameter
3615 */
ufshcd_read_string_desc(struct ufs_hba * hba,u8 desc_index,u8 ** buf,bool ascii)3616 int ufshcd_read_string_desc(struct ufs_hba *hba, u8 desc_index,
3617 u8 **buf, bool ascii)
3618 {
3619 struct uc_string_id *uc_str;
3620 u8 *str;
3621 int ret;
3622
3623 if (!buf)
3624 return -EINVAL;
3625
3626 uc_str = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
3627 if (!uc_str)
3628 return -ENOMEM;
3629
3630 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_STRING, desc_index, 0,
3631 (u8 *)uc_str, QUERY_DESC_MAX_SIZE);
3632 if (ret < 0) {
3633 dev_err(hba->dev, "Reading String Desc failed after %d retries. err = %d\n",
3634 QUERY_REQ_RETRIES, ret);
3635 str = NULL;
3636 goto out;
3637 }
3638
3639 if (uc_str->len <= QUERY_DESC_HDR_SIZE) {
3640 dev_dbg(hba->dev, "String Desc is of zero length\n");
3641 str = NULL;
3642 ret = 0;
3643 goto out;
3644 }
3645
3646 if (ascii) {
3647 ssize_t ascii_len;
3648 int i;
3649 /* remove header and divide by 2 to move from UTF16 to UTF8 */
3650 ascii_len = (uc_str->len - QUERY_DESC_HDR_SIZE) / 2 + 1;
3651 str = kzalloc(ascii_len, GFP_KERNEL);
3652 if (!str) {
3653 ret = -ENOMEM;
3654 goto out;
3655 }
3656
3657 /*
3658 * the descriptor contains string in UTF16 format
3659 * we need to convert to utf-8 so it can be displayed
3660 */
3661 ret = utf16s_to_utf8s(uc_str->uc,
3662 uc_str->len - QUERY_DESC_HDR_SIZE,
3663 UTF16_BIG_ENDIAN, str, ascii_len - 1);
3664
3665 /* replace non-printable or non-ASCII characters with spaces */
3666 for (i = 0; i < ret; i++)
3667 str[i] = ufshcd_remove_non_printable(str[i]);
3668
3669 str[ret++] = '\0';
3670
3671 } else {
3672 str = kmemdup(uc_str, uc_str->len, GFP_KERNEL);
3673 if (!str) {
3674 ret = -ENOMEM;
3675 goto out;
3676 }
3677 ret = uc_str->len;
3678 }
3679 out:
3680 *buf = str;
3681 kfree(uc_str);
3682 return ret;
3683 }
3684
3685 /**
3686 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
3687 * @hba: Pointer to adapter instance
3688 * @lun: lun id
3689 * @param_offset: offset of the parameter to read
3690 * @param_read_buf: pointer to buffer where parameter would be read
3691 * @param_size: sizeof(param_read_buf)
3692 *
3693 * Return: 0 in case of success, non-zero otherwise.
3694 */
ufshcd_read_unit_desc_param(struct ufs_hba * hba,int lun,enum unit_desc_param param_offset,u8 * param_read_buf,u32 param_size)3695 static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
3696 int lun,
3697 enum unit_desc_param param_offset,
3698 u8 *param_read_buf,
3699 u32 param_size)
3700 {
3701 /*
3702 * Unit descriptors are only available for general purpose LUs (LUN id
3703 * from 0 to 7) and RPMB Well known LU.
3704 */
3705 if (!ufs_is_valid_unit_desc_lun(&hba->dev_info, lun))
3706 return -EOPNOTSUPP;
3707
3708 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
3709 param_offset, param_read_buf, param_size);
3710 }
3711
ufshcd_get_ref_clk_gating_wait(struct ufs_hba * hba)3712 static int ufshcd_get_ref_clk_gating_wait(struct ufs_hba *hba)
3713 {
3714 int err = 0;
3715 u32 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3716
3717 if (hba->dev_info.wspecversion >= 0x300) {
3718 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
3719 QUERY_ATTR_IDN_REF_CLK_GATING_WAIT_TIME, 0, 0,
3720 &gating_wait);
3721 if (err)
3722 dev_err(hba->dev, "Failed reading bRefClkGatingWait. err = %d, use default %uus\n",
3723 err, gating_wait);
3724
3725 if (gating_wait == 0) {
3726 gating_wait = UFSHCD_REF_CLK_GATING_WAIT_US;
3727 dev_err(hba->dev, "Undefined ref clk gating wait time, use default %uus\n",
3728 gating_wait);
3729 }
3730
3731 hba->dev_info.clk_gating_wait_us = gating_wait;
3732 }
3733
3734 return err;
3735 }
3736
3737 /**
3738 * ufshcd_memory_alloc - allocate memory for host memory space data structures
3739 * @hba: per adapter instance
3740 *
3741 * 1. Allocate DMA memory for Command Descriptor array
3742 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
3743 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
3744 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
3745 * (UTMRDL)
3746 * 4. Allocate memory for local reference block(lrb).
3747 *
3748 * Return: 0 for success, non-zero in case of failure.
3749 */
ufshcd_memory_alloc(struct ufs_hba * hba)3750 static int ufshcd_memory_alloc(struct ufs_hba *hba)
3751 {
3752 size_t utmrdl_size, utrdl_size, ucdl_size;
3753
3754 /* Allocate memory for UTP command descriptors */
3755 ucdl_size = ufshcd_get_ucd_size(hba) * hba->nutrs;
3756 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
3757 ucdl_size,
3758 &hba->ucdl_dma_addr,
3759 GFP_KERNEL);
3760
3761 /*
3762 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
3763 */
3764 if (!hba->ucdl_base_addr ||
3765 WARN_ON(hba->ucdl_dma_addr & (128 - 1))) {
3766 dev_err(hba->dev,
3767 "Command Descriptor Memory allocation failed\n");
3768 goto out;
3769 }
3770
3771 /*
3772 * Allocate memory for UTP Transfer descriptors
3773 * UFSHCI requires 1KB alignment of UTRD
3774 */
3775 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
3776 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
3777 utrdl_size,
3778 &hba->utrdl_dma_addr,
3779 GFP_KERNEL);
3780 if (!hba->utrdl_base_addr ||
3781 WARN_ON(hba->utrdl_dma_addr & (SZ_1K - 1))) {
3782 dev_err(hba->dev,
3783 "Transfer Descriptor Memory allocation failed\n");
3784 goto out;
3785 }
3786
3787 /*
3788 * Skip utmrdl allocation; it may have been
3789 * allocated during first pass and not released during
3790 * MCQ memory allocation.
3791 * See ufshcd_release_sdb_queue() and ufshcd_config_mcq()
3792 */
3793 if (hba->utmrdl_base_addr)
3794 goto skip_utmrdl;
3795 /*
3796 * Allocate memory for UTP Task Management descriptors
3797 * UFSHCI requires 1KB alignment of UTMRD
3798 */
3799 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
3800 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
3801 utmrdl_size,
3802 &hba->utmrdl_dma_addr,
3803 GFP_KERNEL);
3804 if (!hba->utmrdl_base_addr ||
3805 WARN_ON(hba->utmrdl_dma_addr & (SZ_1K - 1))) {
3806 dev_err(hba->dev,
3807 "Task Management Descriptor Memory allocation failed\n");
3808 goto out;
3809 }
3810
3811 skip_utmrdl:
3812 /* Allocate memory for local reference block */
3813 hba->lrb = devm_kcalloc(hba->dev,
3814 hba->nutrs, sizeof(struct ufshcd_lrb),
3815 GFP_KERNEL);
3816 if (!hba->lrb) {
3817 dev_err(hba->dev, "LRB Memory allocation failed\n");
3818 goto out;
3819 }
3820 return 0;
3821 out:
3822 return -ENOMEM;
3823 }
3824
3825 /**
3826 * ufshcd_host_memory_configure - configure local reference block with
3827 * memory offsets
3828 * @hba: per adapter instance
3829 *
3830 * Configure Host memory space
3831 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
3832 * address.
3833 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
3834 * and PRDT offset.
3835 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
3836 * into local reference block.
3837 */
ufshcd_host_memory_configure(struct ufs_hba * hba)3838 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
3839 {
3840 struct utp_transfer_req_desc *utrdlp;
3841 dma_addr_t cmd_desc_dma_addr;
3842 dma_addr_t cmd_desc_element_addr;
3843 u16 response_offset;
3844 u16 prdt_offset;
3845 int cmd_desc_size;
3846 int i;
3847
3848 utrdlp = hba->utrdl_base_addr;
3849
3850 response_offset =
3851 offsetof(struct utp_transfer_cmd_desc, response_upiu);
3852 prdt_offset =
3853 offsetof(struct utp_transfer_cmd_desc, prd_table);
3854
3855 cmd_desc_size = ufshcd_get_ucd_size(hba);
3856 cmd_desc_dma_addr = hba->ucdl_dma_addr;
3857
3858 for (i = 0; i < hba->nutrs; i++) {
3859 /* Configure UTRD with command descriptor base address */
3860 cmd_desc_element_addr =
3861 (cmd_desc_dma_addr + (cmd_desc_size * i));
3862 utrdlp[i].command_desc_base_addr =
3863 cpu_to_le64(cmd_desc_element_addr);
3864
3865 /* Response upiu and prdt offset should be in double words */
3866 if (hba->quirks & UFSHCD_QUIRK_PRDT_BYTE_GRAN) {
3867 utrdlp[i].response_upiu_offset =
3868 cpu_to_le16(response_offset);
3869 utrdlp[i].prd_table_offset =
3870 cpu_to_le16(prdt_offset);
3871 utrdlp[i].response_upiu_length =
3872 cpu_to_le16(ALIGNED_UPIU_SIZE);
3873 } else {
3874 utrdlp[i].response_upiu_offset =
3875 cpu_to_le16(response_offset >> 2);
3876 utrdlp[i].prd_table_offset =
3877 cpu_to_le16(prdt_offset >> 2);
3878 utrdlp[i].response_upiu_length =
3879 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
3880 }
3881
3882 ufshcd_init_lrb(hba, &hba->lrb[i], i);
3883 }
3884 }
3885
3886 /**
3887 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
3888 * @hba: per adapter instance
3889 *
3890 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
3891 * in order to initialize the Unipro link startup procedure.
3892 * Once the Unipro links are up, the device connected to the controller
3893 * is detected.
3894 *
3895 * Return: 0 on success, non-zero value on failure.
3896 */
ufshcd_dme_link_startup(struct ufs_hba * hba)3897 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
3898 {
3899 struct uic_command uic_cmd = {0};
3900 int ret;
3901
3902 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
3903
3904 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3905 if (ret)
3906 dev_dbg(hba->dev,
3907 "dme-link-startup: error code %d\n", ret);
3908 return ret;
3909 }
3910 /**
3911 * ufshcd_dme_reset - UIC command for DME_RESET
3912 * @hba: per adapter instance
3913 *
3914 * DME_RESET command is issued in order to reset UniPro stack.
3915 * This function now deals with cold reset.
3916 *
3917 * Return: 0 on success, non-zero value on failure.
3918 */
ufshcd_dme_reset(struct ufs_hba * hba)3919 static int ufshcd_dme_reset(struct ufs_hba *hba)
3920 {
3921 struct uic_command uic_cmd = {0};
3922 int ret;
3923
3924 uic_cmd.command = UIC_CMD_DME_RESET;
3925
3926 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3927 if (ret)
3928 dev_err(hba->dev,
3929 "dme-reset: error code %d\n", ret);
3930
3931 return ret;
3932 }
3933
ufshcd_dme_configure_adapt(struct ufs_hba * hba,int agreed_gear,int adapt_val)3934 int ufshcd_dme_configure_adapt(struct ufs_hba *hba,
3935 int agreed_gear,
3936 int adapt_val)
3937 {
3938 int ret;
3939
3940 if (agreed_gear < UFS_HS_G4)
3941 adapt_val = PA_NO_ADAPT;
3942
3943 ret = ufshcd_dme_set(hba,
3944 UIC_ARG_MIB(PA_TXHSADAPTTYPE),
3945 adapt_val);
3946 return ret;
3947 }
3948 EXPORT_SYMBOL_GPL(ufshcd_dme_configure_adapt);
3949
3950 /**
3951 * ufshcd_dme_enable - UIC command for DME_ENABLE
3952 * @hba: per adapter instance
3953 *
3954 * DME_ENABLE command is issued in order to enable UniPro stack.
3955 *
3956 * Return: 0 on success, non-zero value on failure.
3957 */
ufshcd_dme_enable(struct ufs_hba * hba)3958 static int ufshcd_dme_enable(struct ufs_hba *hba)
3959 {
3960 struct uic_command uic_cmd = {0};
3961 int ret;
3962
3963 uic_cmd.command = UIC_CMD_DME_ENABLE;
3964
3965 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
3966 if (ret)
3967 dev_err(hba->dev,
3968 "dme-enable: error code %d\n", ret);
3969
3970 return ret;
3971 }
3972
ufshcd_add_delay_before_dme_cmd(struct ufs_hba * hba)3973 static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
3974 {
3975 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
3976 unsigned long min_sleep_time_us;
3977
3978 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
3979 return;
3980
3981 /*
3982 * last_dme_cmd_tstamp will be 0 only for 1st call to
3983 * this function
3984 */
3985 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
3986 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
3987 } else {
3988 unsigned long delta =
3989 (unsigned long) ktime_to_us(
3990 ktime_sub(ktime_get(),
3991 hba->last_dme_cmd_tstamp));
3992
3993 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
3994 min_sleep_time_us =
3995 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
3996 else
3997 min_sleep_time_us = 0; /* no more delay required */
3998 }
3999
4000 if (min_sleep_time_us > 0) {
4001 /* allow sleep for extra 50us if needed */
4002 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
4003 }
4004
4005 /* update the last_dme_cmd_tstamp */
4006 hba->last_dme_cmd_tstamp = ktime_get();
4007 }
4008
4009 /**
4010 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
4011 * @hba: per adapter instance
4012 * @attr_sel: uic command argument1
4013 * @attr_set: attribute set type as uic command argument2
4014 * @mib_val: setting value as uic command argument3
4015 * @peer: indicate whether peer or local
4016 *
4017 * Return: 0 on success, non-zero value on failure.
4018 */
ufshcd_dme_set_attr(struct ufs_hba * hba,u32 attr_sel,u8 attr_set,u32 mib_val,u8 peer)4019 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
4020 u8 attr_set, u32 mib_val, u8 peer)
4021 {
4022 struct uic_command uic_cmd = {0};
4023 static const char *const action[] = {
4024 "dme-set",
4025 "dme-peer-set"
4026 };
4027 const char *set = action[!!peer];
4028 int ret;
4029 int retries = UFS_UIC_COMMAND_RETRIES;
4030
4031 uic_cmd.command = peer ?
4032 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
4033 uic_cmd.argument1 = attr_sel;
4034 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
4035 uic_cmd.argument3 = mib_val;
4036
4037 do {
4038 /* for peer attributes we retry upon failure */
4039 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4040 if (ret)
4041 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
4042 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
4043 } while (ret && peer && --retries);
4044
4045 if (ret)
4046 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
4047 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
4048 UFS_UIC_COMMAND_RETRIES - retries);
4049
4050 return ret;
4051 }
4052 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
4053
4054 /**
4055 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
4056 * @hba: per adapter instance
4057 * @attr_sel: uic command argument1
4058 * @mib_val: the value of the attribute as returned by the UIC command
4059 * @peer: indicate whether peer or local
4060 *
4061 * Return: 0 on success, non-zero value on failure.
4062 */
ufshcd_dme_get_attr(struct ufs_hba * hba,u32 attr_sel,u32 * mib_val,u8 peer)4063 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
4064 u32 *mib_val, u8 peer)
4065 {
4066 struct uic_command uic_cmd = {0};
4067 static const char *const action[] = {
4068 "dme-get",
4069 "dme-peer-get"
4070 };
4071 const char *get = action[!!peer];
4072 int ret;
4073 int retries = UFS_UIC_COMMAND_RETRIES;
4074 struct ufs_pa_layer_attr orig_pwr_info;
4075 struct ufs_pa_layer_attr temp_pwr_info;
4076 bool pwr_mode_change = false;
4077
4078 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
4079 orig_pwr_info = hba->pwr_info;
4080 temp_pwr_info = orig_pwr_info;
4081
4082 if (orig_pwr_info.pwr_tx == FAST_MODE ||
4083 orig_pwr_info.pwr_rx == FAST_MODE) {
4084 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
4085 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
4086 pwr_mode_change = true;
4087 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
4088 orig_pwr_info.pwr_rx == SLOW_MODE) {
4089 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
4090 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
4091 pwr_mode_change = true;
4092 }
4093 if (pwr_mode_change) {
4094 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
4095 if (ret)
4096 goto out;
4097 }
4098 }
4099
4100 uic_cmd.command = peer ?
4101 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
4102 uic_cmd.argument1 = attr_sel;
4103
4104 do {
4105 /* for peer attributes we retry upon failure */
4106 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
4107 if (ret)
4108 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
4109 get, UIC_GET_ATTR_ID(attr_sel), ret);
4110 } while (ret && peer && --retries);
4111
4112 if (ret)
4113 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
4114 get, UIC_GET_ATTR_ID(attr_sel),
4115 UFS_UIC_COMMAND_RETRIES - retries);
4116
4117 if (mib_val && !ret)
4118 *mib_val = uic_cmd.argument3;
4119
4120 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
4121 && pwr_mode_change)
4122 ufshcd_change_power_mode(hba, &orig_pwr_info);
4123 out:
4124 return ret;
4125 }
4126 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
4127
4128 /**
4129 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
4130 * state) and waits for it to take effect.
4131 *
4132 * @hba: per adapter instance
4133 * @cmd: UIC command to execute
4134 *
4135 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
4136 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
4137 * and device UniPro link and hence it's final completion would be indicated by
4138 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
4139 * addition to normal UIC command completion Status (UCCS). This function only
4140 * returns after the relevant status bits indicate the completion.
4141 *
4142 * Return: 0 on success, non-zero value on failure.
4143 */
ufshcd_uic_pwr_ctrl(struct ufs_hba * hba,struct uic_command * cmd)4144 static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
4145 {
4146 DECLARE_COMPLETION_ONSTACK(uic_async_done);
4147 unsigned long flags;
4148 u8 status;
4149 int ret;
4150 bool reenable_intr = false;
4151
4152 mutex_lock(&hba->uic_cmd_mutex);
4153 ufshcd_add_delay_before_dme_cmd(hba);
4154
4155 spin_lock_irqsave(hba->host->host_lock, flags);
4156 if (ufshcd_is_link_broken(hba)) {
4157 ret = -ENOLINK;
4158 goto out_unlock;
4159 }
4160 hba->uic_async_done = &uic_async_done;
4161 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
4162 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
4163 /*
4164 * Make sure UIC command completion interrupt is disabled before
4165 * issuing UIC command.
4166 */
4167 ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
4168 reenable_intr = true;
4169 }
4170 spin_unlock_irqrestore(hba->host->host_lock, flags);
4171 ret = __ufshcd_send_uic_cmd(hba, cmd);
4172 if (ret) {
4173 dev_err(hba->dev,
4174 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
4175 cmd->command, cmd->argument3, ret);
4176 goto out;
4177 }
4178
4179 if (!wait_for_completion_timeout(hba->uic_async_done,
4180 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
4181 dev_err(hba->dev,
4182 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
4183 cmd->command, cmd->argument3);
4184
4185 if (!cmd->cmd_active) {
4186 dev_err(hba->dev, "%s: Power Mode Change operation has been completed, go check UPMCRS\n",
4187 __func__);
4188 goto check_upmcrs;
4189 }
4190
4191 ret = -ETIMEDOUT;
4192 goto out;
4193 }
4194
4195 check_upmcrs:
4196 status = ufshcd_get_upmcrs(hba);
4197 if (status != PWR_LOCAL) {
4198 dev_err(hba->dev,
4199 "pwr ctrl cmd 0x%x failed, host upmcrs:0x%x\n",
4200 cmd->command, status);
4201 ret = (status != PWR_OK) ? status : -1;
4202 }
4203 out:
4204 if (ret) {
4205 ufshcd_print_host_state(hba);
4206 ufshcd_print_pwr_info(hba);
4207 ufshcd_print_evt_hist(hba);
4208 }
4209
4210 spin_lock_irqsave(hba->host->host_lock, flags);
4211 hba->active_uic_cmd = NULL;
4212 hba->uic_async_done = NULL;
4213 if (reenable_intr)
4214 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
4215 if (ret) {
4216 ufshcd_set_link_broken(hba);
4217 ufshcd_schedule_eh_work(hba);
4218 }
4219 out_unlock:
4220 spin_unlock_irqrestore(hba->host->host_lock, flags);
4221 mutex_unlock(&hba->uic_cmd_mutex);
4222
4223 return ret;
4224 }
4225
4226 /**
4227 * ufshcd_send_bsg_uic_cmd - Send UIC commands requested via BSG layer and retrieve the result
4228 * @hba: per adapter instance
4229 * @uic_cmd: UIC command
4230 *
4231 * Return: 0 only if success.
4232 */
ufshcd_send_bsg_uic_cmd(struct ufs_hba * hba,struct uic_command * uic_cmd)4233 int ufshcd_send_bsg_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
4234 {
4235 int ret;
4236
4237 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UIC_CMD)
4238 return 0;
4239
4240 ufshcd_hold(hba);
4241
4242 if (uic_cmd->argument1 == UIC_ARG_MIB(PA_PWRMODE) &&
4243 uic_cmd->command == UIC_CMD_DME_SET) {
4244 ret = ufshcd_uic_pwr_ctrl(hba, uic_cmd);
4245 goto out;
4246 }
4247
4248 mutex_lock(&hba->uic_cmd_mutex);
4249 ufshcd_add_delay_before_dme_cmd(hba);
4250
4251 ret = __ufshcd_send_uic_cmd(hba, uic_cmd);
4252 if (!ret)
4253 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
4254
4255 mutex_unlock(&hba->uic_cmd_mutex);
4256
4257 out:
4258 ufshcd_release(hba);
4259 return ret;
4260 }
4261
4262 /**
4263 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
4264 * using DME_SET primitives.
4265 * @hba: per adapter instance
4266 * @mode: powr mode value
4267 *
4268 * Return: 0 on success, non-zero value on failure.
4269 */
ufshcd_uic_change_pwr_mode(struct ufs_hba * hba,u8 mode)4270 int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
4271 {
4272 struct uic_command uic_cmd = {0};
4273 int ret;
4274
4275 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
4276 ret = ufshcd_dme_set(hba,
4277 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
4278 if (ret) {
4279 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
4280 __func__, ret);
4281 goto out;
4282 }
4283 }
4284
4285 uic_cmd.command = UIC_CMD_DME_SET;
4286 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
4287 uic_cmd.argument3 = mode;
4288 ufshcd_hold(hba);
4289 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4290 ufshcd_release(hba);
4291
4292 out:
4293 return ret;
4294 }
4295 EXPORT_SYMBOL_GPL(ufshcd_uic_change_pwr_mode);
4296
ufshcd_link_recovery(struct ufs_hba * hba)4297 int ufshcd_link_recovery(struct ufs_hba *hba)
4298 {
4299 int ret;
4300 unsigned long flags;
4301
4302 spin_lock_irqsave(hba->host->host_lock, flags);
4303 hba->ufshcd_state = UFSHCD_STATE_RESET;
4304 ufshcd_set_eh_in_progress(hba);
4305 spin_unlock_irqrestore(hba->host->host_lock, flags);
4306
4307 /* Reset the attached device */
4308 ufshcd_device_reset(hba);
4309
4310 ret = ufshcd_host_reset_and_restore(hba);
4311
4312 spin_lock_irqsave(hba->host->host_lock, flags);
4313 if (ret)
4314 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4315 ufshcd_clear_eh_in_progress(hba);
4316 spin_unlock_irqrestore(hba->host->host_lock, flags);
4317
4318 if (ret)
4319 dev_err(hba->dev, "%s: link recovery failed, err %d",
4320 __func__, ret);
4321
4322 return ret;
4323 }
4324 EXPORT_SYMBOL_GPL(ufshcd_link_recovery);
4325
ufshcd_uic_hibern8_enter(struct ufs_hba * hba)4326 int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
4327 {
4328 int ret;
4329 struct uic_command uic_cmd = {0};
4330 ktime_t start = ktime_get();
4331
4332 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER, PRE_CHANGE);
4333
4334 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
4335 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4336 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "enter",
4337 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4338
4339 if (ret)
4340 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
4341 __func__, ret);
4342 else
4343 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_ENTER,
4344 POST_CHANGE);
4345
4346 return ret;
4347 }
4348 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_enter);
4349
ufshcd_uic_hibern8_exit(struct ufs_hba * hba)4350 int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
4351 {
4352 struct uic_command uic_cmd = {0};
4353 int ret;
4354 ktime_t start = ktime_get();
4355
4356 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT, PRE_CHANGE);
4357
4358 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
4359 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
4360 trace_ufshcd_profile_hibern8(dev_name(hba->dev), "exit",
4361 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
4362
4363 if (ret) {
4364 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
4365 __func__, ret);
4366 } else {
4367 ufshcd_vops_hibern8_notify(hba, UIC_CMD_DME_HIBER_EXIT,
4368 POST_CHANGE);
4369 hba->ufs_stats.last_hibern8_exit_tstamp = local_clock();
4370 hba->ufs_stats.hibern8_exit_cnt++;
4371 }
4372
4373 return ret;
4374 }
4375 EXPORT_SYMBOL_GPL(ufshcd_uic_hibern8_exit);
4376
ufshcd_auto_hibern8_update(struct ufs_hba * hba,u32 ahit)4377 void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit)
4378 {
4379 unsigned long flags;
4380 bool update = false;
4381
4382 if (!ufshcd_is_auto_hibern8_supported(hba))
4383 return;
4384
4385 spin_lock_irqsave(hba->host->host_lock, flags);
4386 if (hba->ahit != ahit) {
4387 hba->ahit = ahit;
4388 update = true;
4389 }
4390 spin_unlock_irqrestore(hba->host->host_lock, flags);
4391
4392 if (update &&
4393 !pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) {
4394 ufshcd_rpm_get_sync(hba);
4395 ufshcd_hold(hba);
4396 ufshcd_auto_hibern8_enable(hba);
4397 ufshcd_release(hba);
4398 ufshcd_rpm_put_sync(hba);
4399 }
4400 }
4401 EXPORT_SYMBOL_GPL(ufshcd_auto_hibern8_update);
4402
ufshcd_auto_hibern8_enable(struct ufs_hba * hba)4403 void ufshcd_auto_hibern8_enable(struct ufs_hba *hba)
4404 {
4405 if (!ufshcd_is_auto_hibern8_supported(hba))
4406 return;
4407
4408 ufshcd_writel(hba, hba->ahit, REG_AUTO_HIBERNATE_IDLE_TIMER);
4409 }
4410
4411 /**
4412 * ufshcd_init_pwr_info - setting the POR (power on reset)
4413 * values in hba power info
4414 * @hba: per-adapter instance
4415 */
ufshcd_init_pwr_info(struct ufs_hba * hba)4416 static void ufshcd_init_pwr_info(struct ufs_hba *hba)
4417 {
4418 hba->pwr_info.gear_rx = UFS_PWM_G1;
4419 hba->pwr_info.gear_tx = UFS_PWM_G1;
4420 hba->pwr_info.lane_rx = UFS_LANE_1;
4421 hba->pwr_info.lane_tx = UFS_LANE_1;
4422 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
4423 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
4424 hba->pwr_info.hs_rate = 0;
4425 }
4426
4427 /**
4428 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
4429 * @hba: per-adapter instance
4430 *
4431 * Return: 0 upon success; < 0 upon failure.
4432 */
ufshcd_get_max_pwr_mode(struct ufs_hba * hba)4433 static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
4434 {
4435 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
4436
4437 if (hba->max_pwr_info.is_valid)
4438 return 0;
4439
4440 if (hba->quirks & UFSHCD_QUIRK_HIBERN_FASTAUTO) {
4441 pwr_info->pwr_tx = FASTAUTO_MODE;
4442 pwr_info->pwr_rx = FASTAUTO_MODE;
4443 } else {
4444 pwr_info->pwr_tx = FAST_MODE;
4445 pwr_info->pwr_rx = FAST_MODE;
4446 }
4447 pwr_info->hs_rate = PA_HS_MODE_B;
4448
4449 /* Get the connected lane count */
4450 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
4451 &pwr_info->lane_rx);
4452 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4453 &pwr_info->lane_tx);
4454
4455 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
4456 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
4457 __func__,
4458 pwr_info->lane_rx,
4459 pwr_info->lane_tx);
4460 return -EINVAL;
4461 }
4462
4463 /*
4464 * First, get the maximum gears of HS speed.
4465 * If a zero value, it means there is no HSGEAR capability.
4466 * Then, get the maximum gears of PWM speed.
4467 */
4468 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
4469 if (!pwr_info->gear_rx) {
4470 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4471 &pwr_info->gear_rx);
4472 if (!pwr_info->gear_rx) {
4473 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
4474 __func__, pwr_info->gear_rx);
4475 return -EINVAL;
4476 }
4477 pwr_info->pwr_rx = SLOW_MODE;
4478 }
4479
4480 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
4481 &pwr_info->gear_tx);
4482 if (!pwr_info->gear_tx) {
4483 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
4484 &pwr_info->gear_tx);
4485 if (!pwr_info->gear_tx) {
4486 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
4487 __func__, pwr_info->gear_tx);
4488 return -EINVAL;
4489 }
4490 pwr_info->pwr_tx = SLOW_MODE;
4491 }
4492
4493 hba->max_pwr_info.is_valid = true;
4494 return 0;
4495 }
4496
ufshcd_change_power_mode(struct ufs_hba * hba,struct ufs_pa_layer_attr * pwr_mode)4497 static int ufshcd_change_power_mode(struct ufs_hba *hba,
4498 struct ufs_pa_layer_attr *pwr_mode)
4499 {
4500 int ret;
4501
4502 /* if already configured to the requested pwr_mode */
4503 if (!hba->force_pmc &&
4504 pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
4505 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
4506 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
4507 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
4508 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
4509 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
4510 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
4511 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
4512 return 0;
4513 }
4514
4515 /*
4516 * Configure attributes for power mode change with below.
4517 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
4518 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
4519 * - PA_HSSERIES
4520 */
4521 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
4522 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
4523 pwr_mode->lane_rx);
4524 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4525 pwr_mode->pwr_rx == FAST_MODE)
4526 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), true);
4527 else
4528 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), false);
4529
4530 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
4531 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
4532 pwr_mode->lane_tx);
4533 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
4534 pwr_mode->pwr_tx == FAST_MODE)
4535 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), true);
4536 else
4537 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), false);
4538
4539 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
4540 pwr_mode->pwr_tx == FASTAUTO_MODE ||
4541 pwr_mode->pwr_rx == FAST_MODE ||
4542 pwr_mode->pwr_tx == FAST_MODE)
4543 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
4544 pwr_mode->hs_rate);
4545
4546 if (!(hba->quirks & UFSHCD_QUIRK_SKIP_DEF_UNIPRO_TIMEOUT_SETTING)) {
4547 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA0),
4548 DL_FC0ProtectionTimeOutVal_Default);
4549 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA1),
4550 DL_TC0ReplayTimeOutVal_Default);
4551 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA2),
4552 DL_AFC0ReqTimeOutVal_Default);
4553 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA3),
4554 DL_FC1ProtectionTimeOutVal_Default);
4555 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA4),
4556 DL_TC1ReplayTimeOutVal_Default);
4557 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_PWRMODEUSERDATA5),
4558 DL_AFC1ReqTimeOutVal_Default);
4559
4560 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalFC0ProtectionTimeOutVal),
4561 DL_FC0ProtectionTimeOutVal_Default);
4562 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalTC0ReplayTimeOutVal),
4563 DL_TC0ReplayTimeOutVal_Default);
4564 ufshcd_dme_set(hba, UIC_ARG_MIB(DME_LocalAFC0ReqTimeOutVal),
4565 DL_AFC0ReqTimeOutVal_Default);
4566 }
4567
4568 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
4569 | pwr_mode->pwr_tx);
4570
4571 if (ret) {
4572 dev_err(hba->dev,
4573 "%s: power mode change failed %d\n", __func__, ret);
4574 } else {
4575 memcpy(&hba->pwr_info, pwr_mode,
4576 sizeof(struct ufs_pa_layer_attr));
4577 }
4578
4579 return ret;
4580 }
4581
4582 /**
4583 * ufshcd_config_pwr_mode - configure a new power mode
4584 * @hba: per-adapter instance
4585 * @desired_pwr_mode: desired power configuration
4586 *
4587 * Return: 0 upon success; < 0 upon failure.
4588 */
ufshcd_config_pwr_mode(struct ufs_hba * hba,struct ufs_pa_layer_attr * desired_pwr_mode)4589 int ufshcd_config_pwr_mode(struct ufs_hba *hba,
4590 struct ufs_pa_layer_attr *desired_pwr_mode)
4591 {
4592 struct ufs_pa_layer_attr final_params = { 0 };
4593 int ret;
4594
4595 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
4596 desired_pwr_mode, &final_params);
4597
4598 if (ret)
4599 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
4600
4601 ret = ufshcd_change_power_mode(hba, &final_params);
4602
4603 if (!ret)
4604 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
4605 &final_params);
4606
4607 return ret;
4608 }
4609 EXPORT_SYMBOL_GPL(ufshcd_config_pwr_mode);
4610
4611 /**
4612 * ufshcd_complete_dev_init() - checks device readiness
4613 * @hba: per-adapter instance
4614 *
4615 * Set fDeviceInit flag and poll until device toggles it.
4616 *
4617 * Return: 0 upon success; < 0 upon failure.
4618 */
ufshcd_complete_dev_init(struct ufs_hba * hba)4619 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
4620 {
4621 int err;
4622 bool flag_res = true;
4623 ktime_t timeout;
4624
4625 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
4626 QUERY_FLAG_IDN_FDEVICEINIT, 0, NULL);
4627 if (err) {
4628 dev_err(hba->dev,
4629 "%s: setting fDeviceInit flag failed with error %d\n",
4630 __func__, err);
4631 goto out;
4632 }
4633
4634 /* Poll fDeviceInit flag to be cleared */
4635 timeout = ktime_add_ms(ktime_get(), FDEVICEINIT_COMPL_TIMEOUT);
4636 do {
4637 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4638 QUERY_FLAG_IDN_FDEVICEINIT, 0, &flag_res);
4639 if (!flag_res)
4640 break;
4641 usleep_range(500, 1000);
4642 } while (ktime_before(ktime_get(), timeout));
4643
4644 if (err) {
4645 dev_err(hba->dev,
4646 "%s: reading fDeviceInit flag failed with error %d\n",
4647 __func__, err);
4648 } else if (flag_res) {
4649 dev_err(hba->dev,
4650 "%s: fDeviceInit was not cleared by the device\n",
4651 __func__);
4652 err = -EBUSY;
4653 }
4654 out:
4655 return err;
4656 }
4657
4658 /**
4659 * ufshcd_make_hba_operational - Make UFS controller operational
4660 * @hba: per adapter instance
4661 *
4662 * To bring UFS host controller to operational state,
4663 * 1. Enable required interrupts
4664 * 2. Configure interrupt aggregation
4665 * 3. Program UTRL and UTMRL base address
4666 * 4. Configure run-stop-registers
4667 *
4668 * Return: 0 on success, non-zero value on failure.
4669 */
ufshcd_make_hba_operational(struct ufs_hba * hba)4670 int ufshcd_make_hba_operational(struct ufs_hba *hba)
4671 {
4672 int err = 0;
4673 u32 reg;
4674
4675 /* Enable required interrupts */
4676 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
4677
4678 /* Configure interrupt aggregation */
4679 if (ufshcd_is_intr_aggr_allowed(hba))
4680 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
4681 else
4682 ufshcd_disable_intr_aggr(hba);
4683
4684 /* Configure UTRL and UTMRL base address registers */
4685 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
4686 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
4687 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
4688 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
4689 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
4690 REG_UTP_TASK_REQ_LIST_BASE_L);
4691 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
4692 REG_UTP_TASK_REQ_LIST_BASE_H);
4693
4694 /*
4695 * Make sure base address and interrupt setup are updated before
4696 * enabling the run/stop registers below.
4697 */
4698 wmb();
4699
4700 /*
4701 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
4702 */
4703 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
4704 if (!(ufshcd_get_lists_status(reg))) {
4705 ufshcd_enable_run_stop_reg(hba);
4706 } else {
4707 dev_err(hba->dev,
4708 "Host controller not ready to process requests");
4709 err = -EIO;
4710 }
4711
4712 return err;
4713 }
4714 EXPORT_SYMBOL_GPL(ufshcd_make_hba_operational);
4715
4716 /**
4717 * ufshcd_hba_stop - Send controller to reset state
4718 * @hba: per adapter instance
4719 */
ufshcd_hba_stop(struct ufs_hba * hba)4720 void ufshcd_hba_stop(struct ufs_hba *hba)
4721 {
4722 unsigned long flags;
4723 int err;
4724
4725 /*
4726 * Obtain the host lock to prevent that the controller is disabled
4727 * while the UFS interrupt handler is active on another CPU.
4728 */
4729 spin_lock_irqsave(hba->host->host_lock, flags);
4730 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
4731 spin_unlock_irqrestore(hba->host->host_lock, flags);
4732
4733 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
4734 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
4735 10, 1);
4736 if (err)
4737 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
4738 }
4739 EXPORT_SYMBOL_GPL(ufshcd_hba_stop);
4740
4741 /**
4742 * ufshcd_hba_execute_hce - initialize the controller
4743 * @hba: per adapter instance
4744 *
4745 * The controller resets itself and controller firmware initialization
4746 * sequence kicks off. When controller is ready it will set
4747 * the Host Controller Enable bit to 1.
4748 *
4749 * Return: 0 on success, non-zero value on failure.
4750 */
ufshcd_hba_execute_hce(struct ufs_hba * hba)4751 static int ufshcd_hba_execute_hce(struct ufs_hba *hba)
4752 {
4753 int retry_outer = 3;
4754 int retry_inner;
4755
4756 start:
4757 if (ufshcd_is_hba_active(hba))
4758 /* change controller state to "reset state" */
4759 ufshcd_hba_stop(hba);
4760
4761 /* UniPro link is disabled at this point */
4762 ufshcd_set_link_off(hba);
4763
4764 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4765
4766 /* start controller initialization sequence */
4767 ufshcd_hba_start(hba);
4768
4769 /*
4770 * To initialize a UFS host controller HCE bit must be set to 1.
4771 * During initialization the HCE bit value changes from 1->0->1.
4772 * When the host controller completes initialization sequence
4773 * it sets the value of HCE bit to 1. The same HCE bit is read back
4774 * to check if the controller has completed initialization sequence.
4775 * So without this delay the value HCE = 1, set in the previous
4776 * instruction might be read back.
4777 * This delay can be changed based on the controller.
4778 */
4779 ufshcd_delay_us(hba->vps->hba_enable_delay_us, 100);
4780
4781 /* wait for the host controller to complete initialization */
4782 retry_inner = 50;
4783 while (!ufshcd_is_hba_active(hba)) {
4784 if (retry_inner) {
4785 retry_inner--;
4786 } else {
4787 dev_err(hba->dev,
4788 "Controller enable failed\n");
4789 if (retry_outer) {
4790 retry_outer--;
4791 goto start;
4792 }
4793 return -EIO;
4794 }
4795 usleep_range(1000, 1100);
4796 }
4797
4798 /* enable UIC related interrupts */
4799 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4800
4801 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4802
4803 return 0;
4804 }
4805
ufshcd_hba_enable(struct ufs_hba * hba)4806 int ufshcd_hba_enable(struct ufs_hba *hba)
4807 {
4808 int ret;
4809
4810 if (hba->quirks & UFSHCI_QUIRK_BROKEN_HCE) {
4811 ufshcd_set_link_off(hba);
4812 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
4813
4814 /* enable UIC related interrupts */
4815 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
4816 ret = ufshcd_dme_reset(hba);
4817 if (ret) {
4818 dev_err(hba->dev, "DME_RESET failed\n");
4819 return ret;
4820 }
4821
4822 ret = ufshcd_dme_enable(hba);
4823 if (ret) {
4824 dev_err(hba->dev, "Enabling DME failed\n");
4825 return ret;
4826 }
4827
4828 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
4829 } else {
4830 ret = ufshcd_hba_execute_hce(hba);
4831 }
4832
4833 return ret;
4834 }
4835 EXPORT_SYMBOL_GPL(ufshcd_hba_enable);
4836
ufshcd_disable_tx_lcc(struct ufs_hba * hba,bool peer)4837 static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
4838 {
4839 int tx_lanes = 0, i, err = 0;
4840
4841 if (!peer)
4842 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4843 &tx_lanes);
4844 else
4845 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
4846 &tx_lanes);
4847 for (i = 0; i < tx_lanes; i++) {
4848 if (!peer)
4849 err = ufshcd_dme_set(hba,
4850 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4851 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4852 0);
4853 else
4854 err = ufshcd_dme_peer_set(hba,
4855 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
4856 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
4857 0);
4858 if (err) {
4859 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
4860 __func__, peer, i, err);
4861 break;
4862 }
4863 }
4864
4865 return err;
4866 }
4867
ufshcd_disable_device_tx_lcc(struct ufs_hba * hba)4868 static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
4869 {
4870 return ufshcd_disable_tx_lcc(hba, true);
4871 }
4872
ufshcd_update_evt_hist(struct ufs_hba * hba,u32 id,u32 val)4873 void ufshcd_update_evt_hist(struct ufs_hba *hba, u32 id, u32 val)
4874 {
4875 struct ufs_event_hist *e;
4876
4877 if (id >= UFS_EVT_CNT)
4878 return;
4879
4880 e = &hba->ufs_stats.event[id];
4881 e->val[e->pos] = val;
4882 e->tstamp[e->pos] = local_clock();
4883 e->cnt += 1;
4884 e->pos = (e->pos + 1) % UFS_EVENT_HIST_LENGTH;
4885
4886 ufshcd_vops_event_notify(hba, id, &val);
4887 }
4888 EXPORT_SYMBOL_GPL(ufshcd_update_evt_hist);
4889
4890 /**
4891 * ufshcd_link_startup - Initialize unipro link startup
4892 * @hba: per adapter instance
4893 *
4894 * Return: 0 for success, non-zero in case of failure.
4895 */
ufshcd_link_startup(struct ufs_hba * hba)4896 static int ufshcd_link_startup(struct ufs_hba *hba)
4897 {
4898 int ret;
4899 int retries = DME_LINKSTARTUP_RETRIES;
4900 bool link_startup_again = false;
4901
4902 /*
4903 * If UFS device isn't active then we will have to issue link startup
4904 * 2 times to make sure the device state move to active.
4905 */
4906 if (!ufshcd_is_ufs_dev_active(hba))
4907 link_startup_again = true;
4908
4909 link_startup:
4910 do {
4911 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
4912
4913 ret = ufshcd_dme_link_startup(hba);
4914
4915 /* check if device is detected by inter-connect layer */
4916 if (!ret && !ufshcd_is_device_present(hba)) {
4917 ufshcd_update_evt_hist(hba,
4918 UFS_EVT_LINK_STARTUP_FAIL,
4919 0);
4920 dev_err(hba->dev, "%s: Device not present\n", __func__);
4921 ret = -ENXIO;
4922 goto out;
4923 }
4924
4925 /*
4926 * DME link lost indication is only received when link is up,
4927 * but we can't be sure if the link is up until link startup
4928 * succeeds. So reset the local Uni-Pro and try again.
4929 */
4930 if (ret && retries && ufshcd_hba_enable(hba)) {
4931 ufshcd_update_evt_hist(hba,
4932 UFS_EVT_LINK_STARTUP_FAIL,
4933 (u32)ret);
4934 goto out;
4935 }
4936 } while (ret && retries--);
4937
4938 if (ret) {
4939 /* failed to get the link up... retire */
4940 ufshcd_update_evt_hist(hba,
4941 UFS_EVT_LINK_STARTUP_FAIL,
4942 (u32)ret);
4943 goto out;
4944 }
4945
4946 if (link_startup_again) {
4947 link_startup_again = false;
4948 retries = DME_LINKSTARTUP_RETRIES;
4949 goto link_startup;
4950 }
4951
4952 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
4953 ufshcd_init_pwr_info(hba);
4954 ufshcd_print_pwr_info(hba);
4955
4956 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
4957 ret = ufshcd_disable_device_tx_lcc(hba);
4958 if (ret)
4959 goto out;
4960 }
4961
4962 /* Include any host controller configuration via UIC commands */
4963 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
4964 if (ret)
4965 goto out;
4966
4967 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
4968 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
4969 ret = ufshcd_make_hba_operational(hba);
4970 out:
4971 if (ret) {
4972 dev_err(hba->dev, "link startup failed %d\n", ret);
4973 ufshcd_print_host_state(hba);
4974 ufshcd_print_pwr_info(hba);
4975 ufshcd_print_evt_hist(hba);
4976 }
4977 return ret;
4978 }
4979
4980 /**
4981 * ufshcd_verify_dev_init() - Verify device initialization
4982 * @hba: per-adapter instance
4983 *
4984 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
4985 * device Transport Protocol (UTP) layer is ready after a reset.
4986 * If the UTP layer at the device side is not initialized, it may
4987 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
4988 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
4989 *
4990 * Return: 0 upon success; < 0 upon failure.
4991 */
ufshcd_verify_dev_init(struct ufs_hba * hba)4992 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
4993 {
4994 int err = 0;
4995 int retries;
4996
4997 ufshcd_hold(hba);
4998 mutex_lock(&hba->dev_cmd.lock);
4999 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
5000 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
5001 hba->nop_out_timeout);
5002
5003 if (!err || err == -ETIMEDOUT)
5004 break;
5005
5006 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5007 }
5008 mutex_unlock(&hba->dev_cmd.lock);
5009 ufshcd_release(hba);
5010
5011 if (err)
5012 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5013 return err;
5014 }
5015
5016 /**
5017 * ufshcd_setup_links - associate link b/w device wlun and other luns
5018 * @sdev: pointer to SCSI device
5019 * @hba: pointer to ufs hba
5020 */
ufshcd_setup_links(struct ufs_hba * hba,struct scsi_device * sdev)5021 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
5022 {
5023 struct device_link *link;
5024
5025 /*
5026 * Device wlun is the supplier & rest of the luns are consumers.
5027 * This ensures that device wlun suspends after all other luns.
5028 */
5029 if (hba->ufs_device_wlun) {
5030 link = device_link_add(&sdev->sdev_gendev,
5031 &hba->ufs_device_wlun->sdev_gendev,
5032 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
5033 if (!link) {
5034 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
5035 dev_name(&hba->ufs_device_wlun->sdev_gendev));
5036 return;
5037 }
5038 hba->luns_avail--;
5039 /* Ignore REPORT_LUN wlun probing */
5040 if (hba->luns_avail == 1) {
5041 ufshcd_rpm_put(hba);
5042 return;
5043 }
5044 } else {
5045 /*
5046 * Device wlun is probed. The assumption is that WLUNs are
5047 * scanned before other LUNs.
5048 */
5049 hba->luns_avail--;
5050 }
5051 }
5052
5053 /**
5054 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5055 * @hba: per-adapter instance
5056 * @sdev: pointer to SCSI device
5057 */
ufshcd_lu_init(struct ufs_hba * hba,struct scsi_device * sdev)5058 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5059 {
5060 int len = QUERY_DESC_MAX_SIZE;
5061 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5062 u8 lun_qdepth = hba->nutrs;
5063 u8 *desc_buf;
5064 int ret;
5065
5066 desc_buf = kzalloc(len, GFP_KERNEL);
5067 if (!desc_buf)
5068 goto set_qdepth;
5069
5070 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5071 if (ret < 0) {
5072 if (ret == -EOPNOTSUPP)
5073 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5074 lun_qdepth = 1;
5075 kfree(desc_buf);
5076 goto set_qdepth;
5077 }
5078
5079 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5080 /*
5081 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5082 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5083 */
5084 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5085 }
5086 /*
5087 * According to UFS device specification, the write protection mode is only supported by
5088 * normal LU, not supported by WLUN.
5089 */
5090 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5091 !hba->dev_info.is_lu_power_on_wp &&
5092 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5093 hba->dev_info.is_lu_power_on_wp = true;
5094
5095 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5096 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5097 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5098 hba->dev_info.b_advanced_rpmb_en = true;
5099
5100
5101 kfree(desc_buf);
5102 set_qdepth:
5103 /*
5104 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5105 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5106 */
5107 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5108 scsi_change_queue_depth(sdev, lun_qdepth);
5109 }
5110
5111 /**
5112 * ufshcd_slave_alloc - handle initial SCSI device configurations
5113 * @sdev: pointer to SCSI device
5114 *
5115 * Return: success.
5116 */
ufshcd_slave_alloc(struct scsi_device * sdev)5117 static int ufshcd_slave_alloc(struct scsi_device *sdev)
5118 {
5119 struct ufs_hba *hba;
5120
5121 hba = shost_priv(sdev->host);
5122
5123 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5124 sdev->use_10_for_ms = 1;
5125
5126 /* DBD field should be set to 1 in mode sense(10) */
5127 sdev->set_dbd_for_ms = 1;
5128
5129 /* allow SCSI layer to restart the device in case of errors */
5130 sdev->allow_restart = 1;
5131
5132 /* REPORT SUPPORTED OPERATION CODES is not supported */
5133 sdev->no_report_opcodes = 1;
5134
5135 /* WRITE_SAME command is not supported */
5136 sdev->no_write_same = 1;
5137
5138 ufshcd_lu_init(hba, sdev);
5139
5140 ufshcd_setup_links(hba, sdev);
5141
5142 return 0;
5143 }
5144
5145 /**
5146 * ufshcd_change_queue_depth - change queue depth
5147 * @sdev: pointer to SCSI device
5148 * @depth: required depth to set
5149 *
5150 * Change queue depth and make sure the max. limits are not crossed.
5151 *
5152 * Return: new queue depth.
5153 */
ufshcd_change_queue_depth(struct scsi_device * sdev,int depth)5154 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5155 {
5156 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5157 }
5158
5159 /**
5160 * ufshcd_slave_configure - adjust SCSI device configurations
5161 * @sdev: pointer to SCSI device
5162 *
5163 * Return: 0 (success).
5164 */
ufshcd_slave_configure(struct scsi_device * sdev)5165 static int ufshcd_slave_configure(struct scsi_device *sdev)
5166 {
5167 struct ufs_hba *hba = shost_priv(sdev->host);
5168 struct request_queue *q = sdev->request_queue;
5169
5170 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
5171 if (hba->quirks & UFSHCD_QUIRK_4KB_DMA_ALIGNMENT)
5172 blk_queue_update_dma_alignment(q, SZ_4K - 1);
5173 /*
5174 * Block runtime-pm until all consumers are added.
5175 * Refer ufshcd_setup_links().
5176 */
5177 if (is_device_wlun(sdev))
5178 pm_runtime_get_noresume(&sdev->sdev_gendev);
5179 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5180 sdev->rpm_autosuspend = 1;
5181 /*
5182 * Do not print messages during runtime PM to avoid never-ending cycles
5183 * of messages written back to storage by user space causing runtime
5184 * resume, causing more messages and so on.
5185 */
5186 sdev->silence_suspend = 1;
5187
5188 ufshcd_crypto_register(hba, q);
5189
5190 return 0;
5191 }
5192
5193 /**
5194 * ufshcd_slave_destroy - remove SCSI device configurations
5195 * @sdev: pointer to SCSI device
5196 */
ufshcd_slave_destroy(struct scsi_device * sdev)5197 static void ufshcd_slave_destroy(struct scsi_device *sdev)
5198 {
5199 struct ufs_hba *hba;
5200 unsigned long flags;
5201
5202 hba = shost_priv(sdev->host);
5203
5204 /* Drop the reference as it won't be needed anymore */
5205 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5206 spin_lock_irqsave(hba->host->host_lock, flags);
5207 hba->ufs_device_wlun = NULL;
5208 spin_unlock_irqrestore(hba->host->host_lock, flags);
5209 } else if (hba->ufs_device_wlun) {
5210 struct device *supplier = NULL;
5211
5212 /* Ensure UFS Device WLUN exists and does not disappear */
5213 spin_lock_irqsave(hba->host->host_lock, flags);
5214 if (hba->ufs_device_wlun) {
5215 supplier = &hba->ufs_device_wlun->sdev_gendev;
5216 get_device(supplier);
5217 }
5218 spin_unlock_irqrestore(hba->host->host_lock, flags);
5219
5220 if (supplier) {
5221 /*
5222 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5223 * device will not have been registered but can still
5224 * have a device link holding a reference to the device.
5225 */
5226 device_link_remove(&sdev->sdev_gendev, supplier);
5227 put_device(supplier);
5228 }
5229 }
5230 }
5231
5232 /**
5233 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5234 * @lrbp: pointer to local reference block of completed command
5235 * @scsi_status: SCSI command status
5236 *
5237 * Return: value base on SCSI command status.
5238 */
5239 static inline int
ufshcd_scsi_cmd_status(struct ufshcd_lrb * lrbp,int scsi_status)5240 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5241 {
5242 int result = 0;
5243
5244 switch (scsi_status) {
5245 case SAM_STAT_CHECK_CONDITION:
5246 ufshcd_copy_sense_data(lrbp);
5247 fallthrough;
5248 case SAM_STAT_GOOD:
5249 result |= DID_OK << 16 | scsi_status;
5250 break;
5251 case SAM_STAT_TASK_SET_FULL:
5252 case SAM_STAT_BUSY:
5253 case SAM_STAT_TASK_ABORTED:
5254 ufshcd_copy_sense_data(lrbp);
5255 result |= scsi_status;
5256 break;
5257 default:
5258 result |= DID_ERROR << 16;
5259 break;
5260 } /* end of switch */
5261
5262 return result;
5263 }
5264
5265 /**
5266 * ufshcd_transfer_rsp_status - Get overall status of the response
5267 * @hba: per adapter instance
5268 * @lrbp: pointer to local reference block of completed command
5269 * @cqe: pointer to the completion queue entry
5270 *
5271 * Return: result of the command to notify SCSI midlayer.
5272 */
5273 static inline int
ufshcd_transfer_rsp_status(struct ufs_hba * hba,struct ufshcd_lrb * lrbp,struct cq_entry * cqe)5274 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5275 struct cq_entry *cqe)
5276 {
5277 int result = 0;
5278 int scsi_status;
5279 enum utp_ocs ocs;
5280 u8 upiu_flags;
5281 u32 resid;
5282
5283 upiu_flags = lrbp->ucd_rsp_ptr->header.flags;
5284 resid = be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count);
5285 /*
5286 * Test !overflow instead of underflow to support UFS devices that do
5287 * not set either flag.
5288 */
5289 if (resid && !(upiu_flags & UPIU_RSP_FLAG_OVERFLOW))
5290 scsi_set_resid(lrbp->cmd, resid);
5291
5292 /* overall command status of utrd */
5293 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5294
5295 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5296 if (lrbp->ucd_rsp_ptr->header.response ||
5297 lrbp->ucd_rsp_ptr->header.status)
5298 ocs = OCS_SUCCESS;
5299 }
5300
5301 switch (ocs) {
5302 case OCS_SUCCESS:
5303 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5304 switch (ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr)) {
5305 case UPIU_TRANSACTION_RESPONSE:
5306 /*
5307 * get the result based on SCSI status response
5308 * to notify the SCSI midlayer of the command status
5309 */
5310 scsi_status = lrbp->ucd_rsp_ptr->header.status;
5311 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5312
5313 /*
5314 * Currently we are only supporting BKOPs exception
5315 * events hence we can ignore BKOPs exception event
5316 * during power management callbacks. BKOPs exception
5317 * event is not expected to be raised in runtime suspend
5318 * callback as it allows the urgent bkops.
5319 * During system suspend, we are anyway forcefully
5320 * disabling the bkops and if urgent bkops is needed
5321 * it will be enabled on system resume. Long term
5322 * solution could be to abort the system suspend if
5323 * UFS device needs urgent BKOPs.
5324 */
5325 if (!hba->pm_op_in_progress &&
5326 !ufshcd_eh_in_progress(hba) &&
5327 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5328 /* Flushed in suspend */
5329 schedule_work(&hba->eeh_work);
5330 break;
5331 case UPIU_TRANSACTION_REJECT_UPIU:
5332 /* TODO: handle Reject UPIU Response */
5333 result = DID_ERROR << 16;
5334 dev_err(hba->dev,
5335 "Reject UPIU not fully implemented\n");
5336 break;
5337 default:
5338 dev_err(hba->dev,
5339 "Unexpected request response code = %x\n",
5340 result);
5341 result = DID_ERROR << 16;
5342 break;
5343 }
5344 break;
5345 case OCS_ABORTED:
5346 result |= DID_ABORT << 16;
5347 break;
5348 case OCS_INVALID_COMMAND_STATUS:
5349 result |= DID_REQUEUE << 16;
5350 break;
5351 case OCS_INVALID_CMD_TABLE_ATTR:
5352 case OCS_INVALID_PRDT_ATTR:
5353 case OCS_MISMATCH_DATA_BUF_SIZE:
5354 case OCS_MISMATCH_RESP_UPIU_SIZE:
5355 case OCS_PEER_COMM_FAILURE:
5356 case OCS_FATAL_ERROR:
5357 case OCS_DEVICE_FATAL_ERROR:
5358 case OCS_INVALID_CRYPTO_CONFIG:
5359 case OCS_GENERAL_CRYPTO_ERROR:
5360 default:
5361 result |= DID_ERROR << 16;
5362 dev_err(hba->dev,
5363 "OCS error from controller = %x for tag %d\n",
5364 ocs, lrbp->task_tag);
5365 ufshcd_print_evt_hist(hba);
5366 ufshcd_print_host_state(hba);
5367 break;
5368 } /* end of switch */
5369
5370 if ((host_byte(result) != DID_OK) &&
5371 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5372 ufshcd_print_tr(hba, lrbp->task_tag, true);
5373 return result;
5374 }
5375
ufshcd_is_auto_hibern8_error(struct ufs_hba * hba,u32 intr_mask)5376 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5377 u32 intr_mask)
5378 {
5379 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5380 !ufshcd_is_auto_hibern8_enabled(hba))
5381 return false;
5382
5383 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5384 return false;
5385
5386 if (hba->active_uic_cmd &&
5387 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5388 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5389 return false;
5390
5391 return true;
5392 }
5393
5394 /**
5395 * ufshcd_uic_cmd_compl - handle completion of uic command
5396 * @hba: per adapter instance
5397 * @intr_status: interrupt status generated by the controller
5398 *
5399 * Return:
5400 * IRQ_HANDLED - If interrupt is valid
5401 * IRQ_NONE - If invalid interrupt
5402 */
ufshcd_uic_cmd_compl(struct ufs_hba * hba,u32 intr_status)5403 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5404 {
5405 irqreturn_t retval = IRQ_NONE;
5406
5407 spin_lock(hba->host->host_lock);
5408 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5409 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5410
5411 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
5412 hba->active_uic_cmd->argument2 |=
5413 ufshcd_get_uic_cmd_result(hba);
5414 hba->active_uic_cmd->argument3 =
5415 ufshcd_get_dme_attr_val(hba);
5416 if (!hba->uic_async_done)
5417 hba->active_uic_cmd->cmd_active = 0;
5418 complete(&hba->active_uic_cmd->done);
5419 retval = IRQ_HANDLED;
5420 }
5421
5422 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done) {
5423 hba->active_uic_cmd->cmd_active = 0;
5424 complete(hba->uic_async_done);
5425 retval = IRQ_HANDLED;
5426 }
5427
5428 if (retval == IRQ_HANDLED)
5429 ufshcd_add_uic_command_trace(hba, hba->active_uic_cmd,
5430 UFS_CMD_COMP);
5431 spin_unlock(hba->host->host_lock);
5432 return retval;
5433 }
5434
5435 /* Release the resources allocated for processing a SCSI command. */
ufshcd_release_scsi_cmd(struct ufs_hba * hba,struct ufshcd_lrb * lrbp)5436 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5437 struct ufshcd_lrb *lrbp)
5438 {
5439 struct scsi_cmnd *cmd = lrbp->cmd;
5440
5441 scsi_dma_unmap(cmd);
5442 ufshcd_release(hba);
5443 ufshcd_clk_scaling_update_busy(hba);
5444 }
5445
5446 /**
5447 * ufshcd_compl_one_cqe - handle a completion queue entry
5448 * @hba: per adapter instance
5449 * @task_tag: the task tag of the request to be completed
5450 * @cqe: pointer to the completion queue entry
5451 */
ufshcd_compl_one_cqe(struct ufs_hba * hba,int task_tag,struct cq_entry * cqe)5452 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5453 struct cq_entry *cqe)
5454 {
5455 struct ufshcd_lrb *lrbp;
5456 struct scsi_cmnd *cmd;
5457 enum utp_ocs ocs;
5458
5459 lrbp = &hba->lrb[task_tag];
5460 lrbp->compl_time_stamp = ktime_get();
5461 lrbp->compl_time_stamp_local_clock = local_clock();
5462 cmd = lrbp->cmd;
5463 if (cmd) {
5464 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5465 ufshcd_update_monitor(hba, lrbp);
5466 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5467 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5468 ufshcd_release_scsi_cmd(hba, lrbp);
5469 /* Do not touch lrbp after scsi done */
5470 scsi_done(cmd);
5471 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE ||
5472 lrbp->command_type == UTP_CMD_TYPE_UFS_STORAGE) {
5473 if (hba->dev_cmd.complete) {
5474 if (cqe) {
5475 ocs = le32_to_cpu(cqe->status) & MASK_OCS;
5476 lrbp->utr_descriptor_ptr->header.ocs = ocs;
5477 }
5478 complete(hba->dev_cmd.complete);
5479 ufshcd_clk_scaling_update_busy(hba);
5480 }
5481 }
5482 }
5483
5484 /**
5485 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5486 * @hba: per adapter instance
5487 * @completed_reqs: bitmask that indicates which requests to complete
5488 */
__ufshcd_transfer_req_compl(struct ufs_hba * hba,unsigned long completed_reqs)5489 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5490 unsigned long completed_reqs)
5491 {
5492 int tag;
5493
5494 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5495 ufshcd_compl_one_cqe(hba, tag, NULL);
5496 }
5497
5498 /* Any value that is not an existing queue number is fine for this constant. */
5499 enum {
5500 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5501 };
5502
ufshcd_clear_polled(struct ufs_hba * hba,unsigned long * completed_reqs)5503 static void ufshcd_clear_polled(struct ufs_hba *hba,
5504 unsigned long *completed_reqs)
5505 {
5506 int tag;
5507
5508 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5509 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5510
5511 if (!cmd)
5512 continue;
5513 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5514 __clear_bit(tag, completed_reqs);
5515 }
5516 }
5517
5518 /*
5519 * Return: > 0 if one or more commands have been completed or 0 if no
5520 * requests have been completed.
5521 */
ufshcd_poll(struct Scsi_Host * shost,unsigned int queue_num)5522 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5523 {
5524 struct ufs_hba *hba = shost_priv(shost);
5525 unsigned long completed_reqs, flags;
5526 u32 tr_doorbell;
5527 struct ufs_hw_queue *hwq;
5528
5529 if (is_mcq_enabled(hba)) {
5530 hwq = &hba->uhq[queue_num];
5531
5532 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5533 }
5534
5535 spin_lock_irqsave(&hba->outstanding_lock, flags);
5536 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5537 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5538 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5539 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5540 hba->outstanding_reqs);
5541 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5542 /* Do not complete polled requests from interrupt context. */
5543 ufshcd_clear_polled(hba, &completed_reqs);
5544 }
5545 hba->outstanding_reqs &= ~completed_reqs;
5546 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5547
5548 if (completed_reqs)
5549 __ufshcd_transfer_req_compl(hba, completed_reqs);
5550
5551 return completed_reqs != 0;
5552 }
5553
5554 /**
5555 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
5556 * invoked from the error handler context or ufshcd_host_reset_and_restore()
5557 * to complete the pending transfers and free the resources associated with
5558 * the scsi command.
5559 *
5560 * @hba: per adapter instance
5561 * @force_compl: This flag is set to true when invoked
5562 * from ufshcd_host_reset_and_restore() in which case it requires special
5563 * handling because the host controller has been reset by ufshcd_hba_stop().
5564 */
ufshcd_mcq_compl_pending_transfer(struct ufs_hba * hba,bool force_compl)5565 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
5566 bool force_compl)
5567 {
5568 struct ufs_hw_queue *hwq;
5569 struct ufshcd_lrb *lrbp;
5570 struct scsi_cmnd *cmd;
5571 unsigned long flags;
5572 u32 hwq_num, utag;
5573 int tag;
5574
5575 for (tag = 0; tag < hba->nutrs; tag++) {
5576 lrbp = &hba->lrb[tag];
5577 cmd = lrbp->cmd;
5578 if (!ufshcd_cmd_inflight(cmd) ||
5579 test_bit(SCMD_STATE_COMPLETE, &cmd->state))
5580 continue;
5581
5582 utag = blk_mq_unique_tag(scsi_cmd_to_rq(cmd));
5583 hwq_num = blk_mq_unique_tag_to_hwq(utag);
5584 hwq = &hba->uhq[hwq_num];
5585
5586 if (force_compl) {
5587 ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
5588 /*
5589 * For those cmds of which the cqes are not present
5590 * in the cq, complete them explicitly.
5591 */
5592 if (cmd && !test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
5593 spin_lock_irqsave(&hwq->cq_lock, flags);
5594 set_host_byte(cmd, DID_REQUEUE);
5595 ufshcd_release_scsi_cmd(hba, lrbp);
5596 scsi_done(cmd);
5597 spin_unlock_irqrestore(&hwq->cq_lock, flags);
5598 }
5599 } else {
5600 ufshcd_mcq_poll_cqe_lock(hba, hwq);
5601 }
5602 }
5603 }
5604
5605 /**
5606 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5607 * @hba: per adapter instance
5608 *
5609 * Return:
5610 * IRQ_HANDLED - If interrupt is valid
5611 * IRQ_NONE - If invalid interrupt
5612 */
ufshcd_transfer_req_compl(struct ufs_hba * hba)5613 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5614 {
5615 /* Resetting interrupt aggregation counters first and reading the
5616 * DOOR_BELL afterward allows us to handle all the completed requests.
5617 * In order to prevent other interrupts starvation the DB is read once
5618 * after reset. The down side of this solution is the possibility of
5619 * false interrupt if device completes another request after resetting
5620 * aggregation and before reading the DB.
5621 */
5622 if (ufshcd_is_intr_aggr_allowed(hba) &&
5623 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5624 ufshcd_reset_intr_aggr(hba);
5625
5626 if (ufs_fail_completion())
5627 return IRQ_HANDLED;
5628
5629 /*
5630 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5631 * do not want polling to trigger spurious interrupt complaints.
5632 */
5633 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5634
5635 return IRQ_HANDLED;
5636 }
5637
__ufshcd_write_ee_control(struct ufs_hba * hba,u32 ee_ctrl_mask)5638 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5639 {
5640 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5641 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5642 &ee_ctrl_mask);
5643 }
5644
ufshcd_write_ee_control(struct ufs_hba * hba)5645 int ufshcd_write_ee_control(struct ufs_hba *hba)
5646 {
5647 int err;
5648
5649 mutex_lock(&hba->ee_ctrl_mutex);
5650 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5651 mutex_unlock(&hba->ee_ctrl_mutex);
5652 if (err)
5653 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5654 __func__, err);
5655 return err;
5656 }
5657
ufshcd_update_ee_control(struct ufs_hba * hba,u16 * mask,const u16 * other_mask,u16 set,u16 clr)5658 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5659 const u16 *other_mask, u16 set, u16 clr)
5660 {
5661 u16 new_mask, ee_ctrl_mask;
5662 int err = 0;
5663
5664 mutex_lock(&hba->ee_ctrl_mutex);
5665 new_mask = (*mask & ~clr) | set;
5666 ee_ctrl_mask = new_mask | *other_mask;
5667 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5668 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5669 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5670 if (!err) {
5671 hba->ee_ctrl_mask = ee_ctrl_mask;
5672 *mask = new_mask;
5673 }
5674 mutex_unlock(&hba->ee_ctrl_mutex);
5675 return err;
5676 }
5677
5678 /**
5679 * ufshcd_disable_ee - disable exception event
5680 * @hba: per-adapter instance
5681 * @mask: exception event to disable
5682 *
5683 * Disables exception event in the device so that the EVENT_ALERT
5684 * bit is not set.
5685 *
5686 * Return: zero on success, non-zero error value on failure.
5687 */
ufshcd_disable_ee(struct ufs_hba * hba,u16 mask)5688 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5689 {
5690 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5691 }
5692
5693 /**
5694 * ufshcd_enable_ee - enable exception event
5695 * @hba: per-adapter instance
5696 * @mask: exception event to enable
5697 *
5698 * Enable corresponding exception event in the device to allow
5699 * device to alert host in critical scenarios.
5700 *
5701 * Return: zero on success, non-zero error value on failure.
5702 */
ufshcd_enable_ee(struct ufs_hba * hba,u16 mask)5703 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5704 {
5705 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5706 }
5707
5708 /**
5709 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5710 * @hba: per-adapter instance
5711 *
5712 * Allow device to manage background operations on its own. Enabling
5713 * this might lead to inconsistent latencies during normal data transfers
5714 * as the device is allowed to manage its own way of handling background
5715 * operations.
5716 *
5717 * Return: zero on success, non-zero on failure.
5718 */
ufshcd_enable_auto_bkops(struct ufs_hba * hba)5719 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5720 {
5721 int err = 0;
5722
5723 if (hba->auto_bkops_enabled)
5724 goto out;
5725
5726 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5727 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5728 if (err) {
5729 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5730 __func__, err);
5731 goto out;
5732 }
5733
5734 hba->auto_bkops_enabled = true;
5735 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Enabled");
5736
5737 /* No need of URGENT_BKOPS exception from the device */
5738 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5739 if (err)
5740 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5741 __func__, err);
5742 out:
5743 return err;
5744 }
5745
5746 /**
5747 * ufshcd_disable_auto_bkops - block device in doing background operations
5748 * @hba: per-adapter instance
5749 *
5750 * Disabling background operations improves command response latency but
5751 * has drawback of device moving into critical state where the device is
5752 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5753 * host is idle so that BKOPS are managed effectively without any negative
5754 * impacts.
5755 *
5756 * Return: zero on success, non-zero on failure.
5757 */
ufshcd_disable_auto_bkops(struct ufs_hba * hba)5758 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5759 {
5760 int err = 0;
5761
5762 if (!hba->auto_bkops_enabled)
5763 goto out;
5764
5765 /*
5766 * If host assisted BKOPs is to be enabled, make sure
5767 * urgent bkops exception is allowed.
5768 */
5769 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5770 if (err) {
5771 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5772 __func__, err);
5773 goto out;
5774 }
5775
5776 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5777 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5778 if (err) {
5779 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5780 __func__, err);
5781 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5782 goto out;
5783 }
5784
5785 hba->auto_bkops_enabled = false;
5786 trace_ufshcd_auto_bkops_state(dev_name(hba->dev), "Disabled");
5787 hba->is_urgent_bkops_lvl_checked = false;
5788 out:
5789 return err;
5790 }
5791
5792 /**
5793 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5794 * @hba: per adapter instance
5795 *
5796 * After a device reset the device may toggle the BKOPS_EN flag
5797 * to default value. The s/w tracking variables should be updated
5798 * as well. This function would change the auto-bkops state based on
5799 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5800 */
ufshcd_force_reset_auto_bkops(struct ufs_hba * hba)5801 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5802 {
5803 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5804 hba->auto_bkops_enabled = false;
5805 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5806 ufshcd_enable_auto_bkops(hba);
5807 } else {
5808 hba->auto_bkops_enabled = true;
5809 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5810 ufshcd_disable_auto_bkops(hba);
5811 }
5812 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5813 hba->is_urgent_bkops_lvl_checked = false;
5814 }
5815
ufshcd_get_bkops_status(struct ufs_hba * hba,u32 * status)5816 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5817 {
5818 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5819 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5820 }
5821
5822 /**
5823 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5824 * @hba: per-adapter instance
5825 * @status: bkops_status value
5826 *
5827 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
5828 * flag in the device to permit background operations if the device
5829 * bkops_status is greater than or equal to "status" argument passed to
5830 * this function, disable otherwise.
5831 *
5832 * Return: 0 for success, non-zero in case of failure.
5833 *
5834 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
5835 * to know whether auto bkops is enabled or disabled after this function
5836 * returns control to it.
5837 */
ufshcd_bkops_ctrl(struct ufs_hba * hba,enum bkops_status status)5838 static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
5839 enum bkops_status status)
5840 {
5841 int err;
5842 u32 curr_status = 0;
5843
5844 err = ufshcd_get_bkops_status(hba, &curr_status);
5845 if (err) {
5846 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5847 __func__, err);
5848 goto out;
5849 } else if (curr_status > BKOPS_STATUS_MAX) {
5850 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
5851 __func__, curr_status);
5852 err = -EINVAL;
5853 goto out;
5854 }
5855
5856 if (curr_status >= status)
5857 err = ufshcd_enable_auto_bkops(hba);
5858 else
5859 err = ufshcd_disable_auto_bkops(hba);
5860 out:
5861 return err;
5862 }
5863
5864 /**
5865 * ufshcd_urgent_bkops - handle urgent bkops exception event
5866 * @hba: per-adapter instance
5867 *
5868 * Enable fBackgroundOpsEn flag in the device to permit background
5869 * operations.
5870 *
5871 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
5872 * and negative error value for any other failure.
5873 *
5874 * Return: 0 upon success; < 0 upon failure.
5875 */
ufshcd_urgent_bkops(struct ufs_hba * hba)5876 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
5877 {
5878 return ufshcd_bkops_ctrl(hba, hba->urgent_bkops_lvl);
5879 }
5880
ufshcd_get_ee_status(struct ufs_hba * hba,u32 * status)5881 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
5882 {
5883 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5884 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
5885 }
5886
ufshcd_bkops_exception_event_handler(struct ufs_hba * hba)5887 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
5888 {
5889 int err;
5890 u32 curr_status = 0;
5891
5892 if (hba->is_urgent_bkops_lvl_checked)
5893 goto enable_auto_bkops;
5894
5895 err = ufshcd_get_bkops_status(hba, &curr_status);
5896 if (err) {
5897 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
5898 __func__, err);
5899 goto out;
5900 }
5901
5902 /*
5903 * We are seeing that some devices are raising the urgent bkops
5904 * exception events even when BKOPS status doesn't indicate performace
5905 * impacted or critical. Handle these device by determining their urgent
5906 * bkops status at runtime.
5907 */
5908 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
5909 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
5910 __func__, curr_status);
5911 /* update the current status as the urgent bkops level */
5912 hba->urgent_bkops_lvl = curr_status;
5913 hba->is_urgent_bkops_lvl_checked = true;
5914 }
5915
5916 enable_auto_bkops:
5917 err = ufshcd_enable_auto_bkops(hba);
5918 out:
5919 if (err < 0)
5920 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
5921 __func__, err);
5922 }
5923
ufshcd_temp_exception_event_handler(struct ufs_hba * hba,u16 status)5924 static void ufshcd_temp_exception_event_handler(struct ufs_hba *hba, u16 status)
5925 {
5926 u32 value;
5927
5928 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5929 QUERY_ATTR_IDN_CASE_ROUGH_TEMP, 0, 0, &value))
5930 return;
5931
5932 dev_info(hba->dev, "exception Tcase %d\n", value - 80);
5933
5934 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
5935
5936 /*
5937 * A placeholder for the platform vendors to add whatever additional
5938 * steps required
5939 */
5940 }
5941
__ufshcd_wb_toggle(struct ufs_hba * hba,bool set,enum flag_idn idn)5942 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
5943 {
5944 u8 index;
5945 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
5946 UPIU_QUERY_OPCODE_CLEAR_FLAG;
5947
5948 index = ufshcd_wb_get_query_index(hba);
5949 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
5950 }
5951
ufshcd_wb_toggle(struct ufs_hba * hba,bool enable)5952 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
5953 {
5954 int ret;
5955
5956 if (!ufshcd_is_wb_allowed(hba) ||
5957 hba->dev_info.wb_enabled == enable)
5958 return 0;
5959
5960 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
5961 if (ret) {
5962 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
5963 __func__, enable ? "enabling" : "disabling", ret);
5964 return ret;
5965 }
5966
5967 hba->dev_info.wb_enabled = enable;
5968 dev_dbg(hba->dev, "%s: Write Booster %s\n",
5969 __func__, enable ? "enabled" : "disabled");
5970
5971 return ret;
5972 }
5973
ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba * hba,bool enable)5974 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
5975 bool enable)
5976 {
5977 int ret;
5978
5979 ret = __ufshcd_wb_toggle(hba, enable,
5980 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
5981 if (ret) {
5982 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
5983 __func__, enable ? "enabling" : "disabling", ret);
5984 return;
5985 }
5986 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
5987 __func__, enable ? "enabled" : "disabled");
5988 }
5989
ufshcd_wb_toggle_buf_flush(struct ufs_hba * hba,bool enable)5990 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
5991 {
5992 int ret;
5993
5994 if (!ufshcd_is_wb_allowed(hba) ||
5995 hba->dev_info.wb_buf_flush_enabled == enable)
5996 return 0;
5997
5998 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
5999 if (ret) {
6000 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
6001 __func__, enable ? "enabling" : "disabling", ret);
6002 return ret;
6003 }
6004
6005 hba->dev_info.wb_buf_flush_enabled = enable;
6006 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
6007 __func__, enable ? "enabled" : "disabled");
6008
6009 return ret;
6010 }
6011
ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba * hba,u32 avail_buf)6012 static bool ufshcd_wb_presrv_usrspc_keep_vcc_on(struct ufs_hba *hba,
6013 u32 avail_buf)
6014 {
6015 u32 cur_buf;
6016 int ret;
6017 u8 index;
6018
6019 index = ufshcd_wb_get_query_index(hba);
6020 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6021 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
6022 index, 0, &cur_buf);
6023 if (ret) {
6024 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
6025 __func__, ret);
6026 return false;
6027 }
6028
6029 if (!cur_buf) {
6030 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
6031 cur_buf);
6032 return false;
6033 }
6034 /* Let it continue to flush when available buffer exceeds threshold */
6035 return avail_buf < hba->vps->wb_flush_threshold;
6036 }
6037
ufshcd_wb_force_disable(struct ufs_hba * hba)6038 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6039 {
6040 if (ufshcd_is_wb_buf_flush_allowed(hba))
6041 ufshcd_wb_toggle_buf_flush(hba, false);
6042
6043 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6044 ufshcd_wb_toggle(hba, false);
6045 hba->caps &= ~UFSHCD_CAP_WB_EN;
6046
6047 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6048 }
6049
ufshcd_is_wb_buf_lifetime_available(struct ufs_hba * hba)6050 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6051 {
6052 u32 lifetime;
6053 int ret;
6054 u8 index;
6055
6056 index = ufshcd_wb_get_query_index(hba);
6057 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6058 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6059 index, 0, &lifetime);
6060 if (ret) {
6061 dev_err(hba->dev,
6062 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6063 __func__, ret);
6064 return false;
6065 }
6066
6067 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6068 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6069 __func__, lifetime);
6070 return false;
6071 }
6072
6073 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6074 __func__, lifetime);
6075
6076 return true;
6077 }
6078
ufshcd_wb_need_flush(struct ufs_hba * hba)6079 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6080 {
6081 int ret;
6082 u32 avail_buf;
6083 u8 index;
6084
6085 if (!ufshcd_is_wb_allowed(hba))
6086 return false;
6087
6088 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6089 ufshcd_wb_force_disable(hba);
6090 return false;
6091 }
6092
6093 /*
6094 * The ufs device needs the vcc to be ON to flush.
6095 * With user-space reduction enabled, it's enough to enable flush
6096 * by checking only the available buffer. The threshold
6097 * defined here is > 90% full.
6098 * With user-space preserved enabled, the current-buffer
6099 * should be checked too because the wb buffer size can reduce
6100 * when disk tends to be full. This info is provided by current
6101 * buffer (dCurrentWriteBoosterBufferSize). There's no point in
6102 * keeping vcc on when current buffer is empty.
6103 */
6104 index = ufshcd_wb_get_query_index(hba);
6105 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6106 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6107 index, 0, &avail_buf);
6108 if (ret) {
6109 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6110 __func__, ret);
6111 return false;
6112 }
6113
6114 if (!hba->dev_info.b_presrv_uspc_en)
6115 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6116
6117 return ufshcd_wb_presrv_usrspc_keep_vcc_on(hba, avail_buf);
6118 }
6119
ufshcd_rpm_dev_flush_recheck_work(struct work_struct * work)6120 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6121 {
6122 struct ufs_hba *hba = container_of(to_delayed_work(work),
6123 struct ufs_hba,
6124 rpm_dev_flush_recheck_work);
6125 /*
6126 * To prevent unnecessary VCC power drain after device finishes
6127 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6128 * after a certain delay to recheck the threshold by next runtime
6129 * suspend.
6130 */
6131 ufshcd_rpm_get_sync(hba);
6132 ufshcd_rpm_put_sync(hba);
6133 }
6134
6135 /**
6136 * ufshcd_exception_event_handler - handle exceptions raised by device
6137 * @work: pointer to work data
6138 *
6139 * Read bExceptionEventStatus attribute from the device and handle the
6140 * exception event accordingly.
6141 */
ufshcd_exception_event_handler(struct work_struct * work)6142 static void ufshcd_exception_event_handler(struct work_struct *work)
6143 {
6144 struct ufs_hba *hba;
6145 int err;
6146 u32 status = 0;
6147 hba = container_of(work, struct ufs_hba, eeh_work);
6148
6149 ufshcd_scsi_block_requests(hba);
6150 err = ufshcd_get_ee_status(hba, &status);
6151 if (err) {
6152 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6153 __func__, err);
6154 goto out;
6155 }
6156
6157 trace_ufshcd_exception_event(dev_name(hba->dev), status);
6158
6159 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6160 ufshcd_bkops_exception_event_handler(hba);
6161
6162 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6163 ufshcd_temp_exception_event_handler(hba, status);
6164
6165 ufs_debugfs_exception_event(hba, status);
6166 out:
6167 ufshcd_scsi_unblock_requests(hba);
6168 }
6169
6170 /* Complete requests that have door-bell cleared */
ufshcd_complete_requests(struct ufs_hba * hba,bool force_compl)6171 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6172 {
6173 if (is_mcq_enabled(hba))
6174 ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6175 else
6176 ufshcd_transfer_req_compl(hba);
6177
6178 ufshcd_tmc_handler(hba);
6179 }
6180
6181 /**
6182 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6183 * to recover from the DL NAC errors or not.
6184 * @hba: per-adapter instance
6185 *
6186 * Return: true if error handling is required, false otherwise.
6187 */
ufshcd_quirk_dl_nac_errors(struct ufs_hba * hba)6188 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6189 {
6190 unsigned long flags;
6191 bool err_handling = true;
6192
6193 spin_lock_irqsave(hba->host->host_lock, flags);
6194 /*
6195 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6196 * device fatal error and/or DL NAC & REPLAY timeout errors.
6197 */
6198 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6199 goto out;
6200
6201 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6202 ((hba->saved_err & UIC_ERROR) &&
6203 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6204 goto out;
6205
6206 if ((hba->saved_err & UIC_ERROR) &&
6207 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6208 int err;
6209 /*
6210 * wait for 50ms to see if we can get any other errors or not.
6211 */
6212 spin_unlock_irqrestore(hba->host->host_lock, flags);
6213 msleep(50);
6214 spin_lock_irqsave(hba->host->host_lock, flags);
6215
6216 /*
6217 * now check if we have got any other severe errors other than
6218 * DL NAC error?
6219 */
6220 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6221 ((hba->saved_err & UIC_ERROR) &&
6222 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6223 goto out;
6224
6225 /*
6226 * As DL NAC is the only error received so far, send out NOP
6227 * command to confirm if link is still active or not.
6228 * - If we don't get any response then do error recovery.
6229 * - If we get response then clear the DL NAC error bit.
6230 */
6231
6232 spin_unlock_irqrestore(hba->host->host_lock, flags);
6233 err = ufshcd_verify_dev_init(hba);
6234 spin_lock_irqsave(hba->host->host_lock, flags);
6235
6236 if (err)
6237 goto out;
6238
6239 /* Link seems to be alive hence ignore the DL NAC errors */
6240 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6241 hba->saved_err &= ~UIC_ERROR;
6242 /* clear NAC error */
6243 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6244 if (!hba->saved_uic_err)
6245 err_handling = false;
6246 }
6247 out:
6248 spin_unlock_irqrestore(hba->host->host_lock, flags);
6249 return err_handling;
6250 }
6251
6252 /* host lock must be held before calling this func */
ufshcd_is_saved_err_fatal(struct ufs_hba * hba)6253 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6254 {
6255 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6256 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6257 }
6258
ufshcd_schedule_eh_work(struct ufs_hba * hba)6259 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6260 {
6261 lockdep_assert_held(hba->host->host_lock);
6262
6263 /* handle fatal errors only when link is not in error state */
6264 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6265 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6266 ufshcd_is_saved_err_fatal(hba))
6267 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6268 else
6269 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6270 queue_work(hba->eh_wq, &hba->eh_work);
6271 }
6272 }
6273
ufshcd_force_error_recovery(struct ufs_hba * hba)6274 static void ufshcd_force_error_recovery(struct ufs_hba *hba)
6275 {
6276 spin_lock_irq(hba->host->host_lock);
6277 hba->force_reset = true;
6278 ufshcd_schedule_eh_work(hba);
6279 spin_unlock_irq(hba->host->host_lock);
6280 }
6281
ufshcd_clk_scaling_allow(struct ufs_hba * hba,bool allow)6282 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6283 {
6284 mutex_lock(&hba->wb_mutex);
6285 down_write(&hba->clk_scaling_lock);
6286 hba->clk_scaling.is_allowed = allow;
6287 up_write(&hba->clk_scaling_lock);
6288 mutex_unlock(&hba->wb_mutex);
6289 }
6290
ufshcd_clk_scaling_suspend(struct ufs_hba * hba,bool suspend)6291 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6292 {
6293 if (suspend) {
6294 if (hba->clk_scaling.is_enabled)
6295 ufshcd_suspend_clkscaling(hba);
6296 ufshcd_clk_scaling_allow(hba, false);
6297 } else {
6298 ufshcd_clk_scaling_allow(hba, true);
6299 if (hba->clk_scaling.is_enabled)
6300 ufshcd_resume_clkscaling(hba);
6301 }
6302 }
6303
ufshcd_err_handling_prepare(struct ufs_hba * hba)6304 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6305 {
6306 ufshcd_rpm_get_sync(hba);
6307 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6308 hba->is_sys_suspended) {
6309 enum ufs_pm_op pm_op;
6310
6311 /*
6312 * Don't assume anything of resume, if
6313 * resume fails, irq and clocks can be OFF, and powers
6314 * can be OFF or in LPM.
6315 */
6316 ufshcd_setup_hba_vreg(hba, true);
6317 ufshcd_enable_irq(hba);
6318 ufshcd_setup_vreg(hba, true);
6319 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6320 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6321 ufshcd_hold(hba);
6322 if (!ufshcd_is_clkgating_allowed(hba))
6323 ufshcd_setup_clocks(hba, true);
6324 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6325 ufshcd_vops_resume(hba, pm_op);
6326 } else {
6327 ufshcd_hold(hba);
6328 if (ufshcd_is_clkscaling_supported(hba) &&
6329 hba->clk_scaling.is_enabled)
6330 ufshcd_suspend_clkscaling(hba);
6331 ufshcd_clk_scaling_allow(hba, false);
6332 }
6333 ufshcd_scsi_block_requests(hba);
6334 /* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6335 blk_mq_wait_quiesce_done(&hba->host->tag_set);
6336 cancel_work_sync(&hba->eeh_work);
6337 }
6338
ufshcd_err_handling_unprepare(struct ufs_hba * hba)6339 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6340 {
6341 ufshcd_scsi_unblock_requests(hba);
6342 ufshcd_release(hba);
6343 if (ufshcd_is_clkscaling_supported(hba))
6344 ufshcd_clk_scaling_suspend(hba, false);
6345 ufshcd_rpm_put(hba);
6346 }
6347
ufshcd_err_handling_should_stop(struct ufs_hba * hba)6348 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6349 {
6350 return (!hba->is_powered || hba->shutting_down ||
6351 !hba->ufs_device_wlun ||
6352 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6353 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6354 ufshcd_is_link_broken(hba))));
6355 }
6356
6357 #ifdef CONFIG_PM
ufshcd_recover_pm_error(struct ufs_hba * hba)6358 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6359 {
6360 struct Scsi_Host *shost = hba->host;
6361 struct scsi_device *sdev;
6362 struct request_queue *q;
6363 int ret;
6364
6365 hba->is_sys_suspended = false;
6366 /*
6367 * Set RPM status of wlun device to RPM_ACTIVE,
6368 * this also clears its runtime error.
6369 */
6370 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6371
6372 /* hba device might have a runtime error otherwise */
6373 if (ret)
6374 ret = pm_runtime_set_active(hba->dev);
6375 /*
6376 * If wlun device had runtime error, we also need to resume those
6377 * consumer scsi devices in case any of them has failed to be
6378 * resumed due to supplier runtime resume failure. This is to unblock
6379 * blk_queue_enter in case there are bios waiting inside it.
6380 */
6381 if (!ret) {
6382 shost_for_each_device(sdev, shost) {
6383 q = sdev->request_queue;
6384 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6385 q->rpm_status == RPM_SUSPENDING))
6386 pm_request_resume(q->dev);
6387 }
6388 }
6389 }
6390 #else
ufshcd_recover_pm_error(struct ufs_hba * hba)6391 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6392 {
6393 }
6394 #endif
6395
ufshcd_is_pwr_mode_restore_needed(struct ufs_hba * hba)6396 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6397 {
6398 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6399 u32 mode;
6400
6401 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6402
6403 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6404 return true;
6405
6406 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6407 return true;
6408
6409 return false;
6410 }
6411
ufshcd_abort_one(struct request * rq,void * priv)6412 static bool ufshcd_abort_one(struct request *rq, void *priv)
6413 {
6414 int *ret = priv;
6415 u32 tag = rq->tag;
6416 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6417 struct scsi_device *sdev = cmd->device;
6418 struct Scsi_Host *shost = sdev->host;
6419 struct ufs_hba *hba = shost_priv(shost);
6420 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
6421 struct ufs_hw_queue *hwq;
6422 unsigned long flags;
6423
6424 *ret = ufshcd_try_to_abort_task(hba, tag);
6425 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6426 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6427 *ret ? "failed" : "succeeded");
6428
6429 /* Release cmd in MCQ mode if abort succeeds */
6430 if (is_mcq_enabled(hba) && (*ret == 0)) {
6431 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
6432 if (!hwq)
6433 return 0;
6434 spin_lock_irqsave(&hwq->cq_lock, flags);
6435 if (ufshcd_cmd_inflight(lrbp->cmd))
6436 ufshcd_release_scsi_cmd(hba, lrbp);
6437 spin_unlock_irqrestore(&hwq->cq_lock, flags);
6438 }
6439
6440 return *ret == 0;
6441 }
6442
6443 /**
6444 * ufshcd_abort_all - Abort all pending commands.
6445 * @hba: Host bus adapter pointer.
6446 *
6447 * Return: true if and only if the host controller needs to be reset.
6448 */
ufshcd_abort_all(struct ufs_hba * hba)6449 static bool ufshcd_abort_all(struct ufs_hba *hba)
6450 {
6451 int tag, ret = 0;
6452
6453 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_abort_one, &ret);
6454 if (ret)
6455 goto out;
6456
6457 /* Clear pending task management requests */
6458 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6459 ret = ufshcd_clear_tm_cmd(hba, tag);
6460 if (ret)
6461 goto out;
6462 }
6463
6464 out:
6465 /* Complete the requests that are cleared by s/w */
6466 ufshcd_complete_requests(hba, false);
6467
6468 return ret != 0;
6469 }
6470
6471 /**
6472 * ufshcd_err_handler - handle UFS errors that require s/w attention
6473 * @work: pointer to work structure
6474 */
ufshcd_err_handler(struct work_struct * work)6475 static void ufshcd_err_handler(struct work_struct *work)
6476 {
6477 int retries = MAX_ERR_HANDLER_RETRIES;
6478 struct ufs_hba *hba;
6479 unsigned long flags;
6480 bool needs_restore;
6481 bool needs_reset;
6482 int pmc_err;
6483
6484 hba = container_of(work, struct ufs_hba, eh_work);
6485
6486 dev_info(hba->dev,
6487 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = %d; saved_uic_err = %d; force_reset = %d%s\n",
6488 __func__, ufshcd_state_name[hba->ufshcd_state],
6489 hba->is_powered, hba->shutting_down, hba->saved_err,
6490 hba->saved_uic_err, hba->force_reset,
6491 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6492
6493 down(&hba->host_sem);
6494 spin_lock_irqsave(hba->host->host_lock, flags);
6495 if (ufshcd_err_handling_should_stop(hba)) {
6496 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6497 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6498 spin_unlock_irqrestore(hba->host->host_lock, flags);
6499 up(&hba->host_sem);
6500 return;
6501 }
6502 ufshcd_set_eh_in_progress(hba);
6503 spin_unlock_irqrestore(hba->host->host_lock, flags);
6504 ufshcd_err_handling_prepare(hba);
6505 /* Complete requests that have door-bell cleared by h/w */
6506 ufshcd_complete_requests(hba, false);
6507 spin_lock_irqsave(hba->host->host_lock, flags);
6508 again:
6509 needs_restore = false;
6510 needs_reset = false;
6511
6512 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6513 hba->ufshcd_state = UFSHCD_STATE_RESET;
6514 /*
6515 * A full reset and restore might have happened after preparation
6516 * is finished, double check whether we should stop.
6517 */
6518 if (ufshcd_err_handling_should_stop(hba))
6519 goto skip_err_handling;
6520
6521 if ((hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) &&
6522 !hba->force_reset) {
6523 bool ret;
6524
6525 spin_unlock_irqrestore(hba->host->host_lock, flags);
6526 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6527 ret = ufshcd_quirk_dl_nac_errors(hba);
6528 spin_lock_irqsave(hba->host->host_lock, flags);
6529 if (!ret && ufshcd_err_handling_should_stop(hba))
6530 goto skip_err_handling;
6531 }
6532
6533 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6534 (hba->saved_uic_err &&
6535 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6536 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6537
6538 spin_unlock_irqrestore(hba->host->host_lock, flags);
6539 ufshcd_print_host_state(hba);
6540 ufshcd_print_pwr_info(hba);
6541 ufshcd_print_evt_hist(hba);
6542 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6543 ufshcd_print_trs_all(hba, pr_prdt);
6544 spin_lock_irqsave(hba->host->host_lock, flags);
6545 }
6546
6547 /*
6548 * if host reset is required then skip clearing the pending
6549 * transfers forcefully because they will get cleared during
6550 * host reset and restore
6551 */
6552 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6553 ufshcd_is_saved_err_fatal(hba) ||
6554 ((hba->saved_err & UIC_ERROR) &&
6555 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6556 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6557 needs_reset = true;
6558 goto do_reset;
6559 }
6560
6561 /*
6562 * If LINERESET was caught, UFS might have been put to PWM mode,
6563 * check if power mode restore is needed.
6564 */
6565 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6566 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6567 if (!hba->saved_uic_err)
6568 hba->saved_err &= ~UIC_ERROR;
6569 spin_unlock_irqrestore(hba->host->host_lock, flags);
6570 if (ufshcd_is_pwr_mode_restore_needed(hba))
6571 needs_restore = true;
6572 spin_lock_irqsave(hba->host->host_lock, flags);
6573 if (!hba->saved_err && !needs_restore)
6574 goto skip_err_handling;
6575 }
6576
6577 hba->silence_err_logs = true;
6578 /* release lock as clear command might sleep */
6579 spin_unlock_irqrestore(hba->host->host_lock, flags);
6580
6581 needs_reset = ufshcd_abort_all(hba);
6582
6583 spin_lock_irqsave(hba->host->host_lock, flags);
6584 hba->silence_err_logs = false;
6585 if (needs_reset)
6586 goto do_reset;
6587
6588 /*
6589 * After all reqs and tasks are cleared from doorbell,
6590 * now it is safe to retore power mode.
6591 */
6592 if (needs_restore) {
6593 spin_unlock_irqrestore(hba->host->host_lock, flags);
6594 /*
6595 * Hold the scaling lock just in case dev cmds
6596 * are sent via bsg and/or sysfs.
6597 */
6598 down_write(&hba->clk_scaling_lock);
6599 hba->force_pmc = true;
6600 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6601 if (pmc_err) {
6602 needs_reset = true;
6603 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6604 __func__, pmc_err);
6605 }
6606 hba->force_pmc = false;
6607 ufshcd_print_pwr_info(hba);
6608 up_write(&hba->clk_scaling_lock);
6609 spin_lock_irqsave(hba->host->host_lock, flags);
6610 }
6611
6612 do_reset:
6613 /* Fatal errors need reset */
6614 if (needs_reset) {
6615 int err;
6616
6617 hba->force_reset = false;
6618 spin_unlock_irqrestore(hba->host->host_lock, flags);
6619 err = ufshcd_reset_and_restore(hba);
6620 if (err)
6621 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6622 __func__, err);
6623 else
6624 ufshcd_recover_pm_error(hba);
6625 spin_lock_irqsave(hba->host->host_lock, flags);
6626 }
6627
6628 skip_err_handling:
6629 if (!needs_reset) {
6630 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6631 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6632 if (hba->saved_err || hba->saved_uic_err)
6633 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6634 __func__, hba->saved_err, hba->saved_uic_err);
6635 }
6636 /* Exit in an operational state or dead */
6637 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6638 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6639 if (--retries)
6640 goto again;
6641 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6642 }
6643 ufshcd_clear_eh_in_progress(hba);
6644 spin_unlock_irqrestore(hba->host->host_lock, flags);
6645 ufshcd_err_handling_unprepare(hba);
6646 up(&hba->host_sem);
6647
6648 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6649 ufshcd_state_name[hba->ufshcd_state]);
6650 }
6651
6652 /**
6653 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6654 * @hba: per-adapter instance
6655 *
6656 * Return:
6657 * IRQ_HANDLED - If interrupt is valid
6658 * IRQ_NONE - If invalid interrupt
6659 */
ufshcd_update_uic_error(struct ufs_hba * hba)6660 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6661 {
6662 u32 reg;
6663 irqreturn_t retval = IRQ_NONE;
6664
6665 /* PHY layer error */
6666 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6667 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6668 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6669 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6670 /*
6671 * To know whether this error is fatal or not, DB timeout
6672 * must be checked but this error is handled separately.
6673 */
6674 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6675 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6676 __func__);
6677
6678 /* Got a LINERESET indication. */
6679 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6680 struct uic_command *cmd = NULL;
6681
6682 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6683 if (hba->uic_async_done && hba->active_uic_cmd)
6684 cmd = hba->active_uic_cmd;
6685 /*
6686 * Ignore the LINERESET during power mode change
6687 * operation via DME_SET command.
6688 */
6689 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6690 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6691 }
6692 retval |= IRQ_HANDLED;
6693 }
6694
6695 /* PA_INIT_ERROR is fatal and needs UIC reset */
6696 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6697 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6698 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6699 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6700
6701 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6702 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6703 else if (hba->dev_quirks &
6704 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6705 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6706 hba->uic_error |=
6707 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6708 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6709 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6710 }
6711 retval |= IRQ_HANDLED;
6712 }
6713
6714 /* UIC NL/TL/DME errors needs software retry */
6715 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6716 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6717 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6718 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6719 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6720 retval |= IRQ_HANDLED;
6721 }
6722
6723 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6724 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6725 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6726 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6727 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6728 retval |= IRQ_HANDLED;
6729 }
6730
6731 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6732 if ((reg & UIC_DME_ERROR) &&
6733 (reg & UIC_DME_ERROR_CODE_MASK)) {
6734 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6735 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6736 retval |= IRQ_HANDLED;
6737 }
6738
6739 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6740 __func__, hba->uic_error);
6741 return retval;
6742 }
6743
6744 /**
6745 * ufshcd_check_errors - Check for errors that need s/w attention
6746 * @hba: per-adapter instance
6747 * @intr_status: interrupt status generated by the controller
6748 *
6749 * Return:
6750 * IRQ_HANDLED - If interrupt is valid
6751 * IRQ_NONE - If invalid interrupt
6752 */
ufshcd_check_errors(struct ufs_hba * hba,u32 intr_status)6753 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6754 {
6755 bool queue_eh_work = false;
6756 irqreturn_t retval = IRQ_NONE;
6757
6758 spin_lock(hba->host->host_lock);
6759 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6760
6761 if (hba->errors & INT_FATAL_ERRORS) {
6762 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6763 hba->errors);
6764 queue_eh_work = true;
6765 }
6766
6767 if (hba->errors & UIC_ERROR) {
6768 hba->uic_error = 0;
6769 retval = ufshcd_update_uic_error(hba);
6770 if (hba->uic_error)
6771 queue_eh_work = true;
6772 }
6773
6774 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6775 dev_err(hba->dev,
6776 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6777 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6778 "Enter" : "Exit",
6779 hba->errors, ufshcd_get_upmcrs(hba));
6780 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6781 hba->errors);
6782 ufshcd_set_link_broken(hba);
6783 queue_eh_work = true;
6784 }
6785
6786 if (queue_eh_work) {
6787 /*
6788 * update the transfer error masks to sticky bits, let's do this
6789 * irrespective of current ufshcd_state.
6790 */
6791 hba->saved_err |= hba->errors;
6792 hba->saved_uic_err |= hba->uic_error;
6793
6794 /* dump controller state before resetting */
6795 if ((hba->saved_err &
6796 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6797 (hba->saved_uic_err &&
6798 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6799 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6800 __func__, hba->saved_err,
6801 hba->saved_uic_err);
6802 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6803 "host_regs: ");
6804 ufshcd_print_pwr_info(hba);
6805 }
6806 ufshcd_schedule_eh_work(hba);
6807 retval |= IRQ_HANDLED;
6808 }
6809 /*
6810 * if (!queue_eh_work) -
6811 * Other errors are either non-fatal where host recovers
6812 * itself without s/w intervention or errors that will be
6813 * handled by the SCSI core layer.
6814 */
6815 hba->errors = 0;
6816 hba->uic_error = 0;
6817 spin_unlock(hba->host->host_lock);
6818 return retval;
6819 }
6820
6821 /**
6822 * ufshcd_tmc_handler - handle task management function completion
6823 * @hba: per adapter instance
6824 *
6825 * Return:
6826 * IRQ_HANDLED - If interrupt is valid
6827 * IRQ_NONE - If invalid interrupt
6828 */
ufshcd_tmc_handler(struct ufs_hba * hba)6829 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
6830 {
6831 unsigned long flags, pending, issued;
6832 irqreturn_t ret = IRQ_NONE;
6833 int tag;
6834
6835 spin_lock_irqsave(hba->host->host_lock, flags);
6836 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
6837 issued = hba->outstanding_tasks & ~pending;
6838 for_each_set_bit(tag, &issued, hba->nutmrs) {
6839 struct request *req = hba->tmf_rqs[tag];
6840 struct completion *c = req->end_io_data;
6841
6842 complete(c);
6843 ret = IRQ_HANDLED;
6844 }
6845 spin_unlock_irqrestore(hba->host->host_lock, flags);
6846
6847 return ret;
6848 }
6849
6850 /**
6851 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
6852 * @hba: per adapter instance
6853 *
6854 * Return: IRQ_HANDLED if interrupt is handled.
6855 */
ufshcd_handle_mcq_cq_events(struct ufs_hba * hba)6856 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
6857 {
6858 struct ufs_hw_queue *hwq;
6859 unsigned long outstanding_cqs;
6860 unsigned int nr_queues;
6861 int i, ret;
6862 u32 events;
6863
6864 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
6865 if (ret)
6866 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
6867
6868 /* Exclude the poll queues */
6869 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
6870 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
6871 hwq = &hba->uhq[i];
6872
6873 events = ufshcd_mcq_read_cqis(hba, i);
6874 if (events)
6875 ufshcd_mcq_write_cqis(hba, events, i);
6876
6877 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
6878 ufshcd_mcq_poll_cqe_lock(hba, hwq);
6879 }
6880
6881 return IRQ_HANDLED;
6882 }
6883
6884 /**
6885 * ufshcd_sl_intr - Interrupt service routine
6886 * @hba: per adapter instance
6887 * @intr_status: contains interrupts generated by the controller
6888 *
6889 * Return:
6890 * IRQ_HANDLED - If interrupt is valid
6891 * IRQ_NONE - If invalid interrupt
6892 */
ufshcd_sl_intr(struct ufs_hba * hba,u32 intr_status)6893 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
6894 {
6895 irqreturn_t retval = IRQ_NONE;
6896
6897 if (intr_status & UFSHCD_UIC_MASK)
6898 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
6899
6900 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
6901 retval |= ufshcd_check_errors(hba, intr_status);
6902
6903 if (intr_status & UTP_TASK_REQ_COMPL)
6904 retval |= ufshcd_tmc_handler(hba);
6905
6906 if (intr_status & UTP_TRANSFER_REQ_COMPL)
6907 retval |= ufshcd_transfer_req_compl(hba);
6908
6909 if (intr_status & MCQ_CQ_EVENT_STATUS)
6910 retval |= ufshcd_handle_mcq_cq_events(hba);
6911
6912 return retval;
6913 }
6914
6915 /**
6916 * ufshcd_intr - Main interrupt service routine
6917 * @irq: irq number
6918 * @__hba: pointer to adapter instance
6919 *
6920 * Return:
6921 * IRQ_HANDLED - If interrupt is valid
6922 * IRQ_NONE - If invalid interrupt
6923 */
ufshcd_intr(int irq,void * __hba)6924 static irqreturn_t ufshcd_intr(int irq, void *__hba)
6925 {
6926 u32 intr_status, enabled_intr_status = 0;
6927 irqreturn_t retval = IRQ_NONE;
6928 struct ufs_hba *hba = __hba;
6929 int retries = hba->nutrs;
6930
6931 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6932 hba->ufs_stats.last_intr_status = intr_status;
6933 hba->ufs_stats.last_intr_ts = local_clock();
6934
6935 /*
6936 * There could be max of hba->nutrs reqs in flight and in worst case
6937 * if the reqs get finished 1 by 1 after the interrupt status is
6938 * read, make sure we handle them by checking the interrupt status
6939 * again in a loop until we process all of the reqs before returning.
6940 */
6941 while (intr_status && retries--) {
6942 enabled_intr_status =
6943 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
6944 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
6945 if (enabled_intr_status)
6946 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
6947
6948 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
6949 }
6950
6951 if (enabled_intr_status && retval == IRQ_NONE &&
6952 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
6953 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
6954 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
6955 __func__,
6956 intr_status,
6957 hba->ufs_stats.last_intr_status,
6958 enabled_intr_status);
6959 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
6960 }
6961
6962 return retval;
6963 }
6964
ufshcd_clear_tm_cmd(struct ufs_hba * hba,int tag)6965 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
6966 {
6967 int err = 0;
6968 u32 mask = 1 << tag;
6969 unsigned long flags;
6970
6971 if (!test_bit(tag, &hba->outstanding_tasks))
6972 goto out;
6973
6974 spin_lock_irqsave(hba->host->host_lock, flags);
6975 ufshcd_utmrl_clear(hba, tag);
6976 spin_unlock_irqrestore(hba->host->host_lock, flags);
6977
6978 /* poll for max. 1 sec to clear door bell register by h/w */
6979 err = ufshcd_wait_for_register(hba,
6980 REG_UTP_TASK_REQ_DOOR_BELL,
6981 mask, 0, 1000, 1000);
6982
6983 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
6984 tag, err < 0 ? "failed" : "succeeded");
6985
6986 out:
6987 return err;
6988 }
6989
__ufshcd_issue_tm_cmd(struct ufs_hba * hba,struct utp_task_req_desc * treq,u8 tm_function)6990 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
6991 struct utp_task_req_desc *treq, u8 tm_function)
6992 {
6993 struct request_queue *q = hba->tmf_queue;
6994 struct Scsi_Host *host = hba->host;
6995 DECLARE_COMPLETION_ONSTACK(wait);
6996 struct request *req;
6997 unsigned long flags;
6998 int task_tag, err;
6999
7000 /*
7001 * blk_mq_alloc_request() is used here only to get a free tag.
7002 */
7003 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
7004 if (IS_ERR(req))
7005 return PTR_ERR(req);
7006
7007 req->end_io_data = &wait;
7008 ufshcd_hold(hba);
7009
7010 spin_lock_irqsave(host->host_lock, flags);
7011
7012 task_tag = req->tag;
7013 WARN_ONCE(task_tag < 0 || task_tag >= hba->nutmrs, "Invalid tag %d\n",
7014 task_tag);
7015 hba->tmf_rqs[req->tag] = req;
7016 treq->upiu_req.req_header.task_tag = task_tag;
7017
7018 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
7019 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
7020
7021 /* send command to the controller */
7022 __set_bit(task_tag, &hba->outstanding_tasks);
7023
7024 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
7025 /* Make sure that doorbell is committed immediately */
7026 wmb();
7027
7028 spin_unlock_irqrestore(host->host_lock, flags);
7029
7030 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
7031
7032 /* wait until the task management command is completed */
7033 err = wait_for_completion_io_timeout(&wait,
7034 msecs_to_jiffies(TM_CMD_TIMEOUT));
7035 if (!err) {
7036 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
7037 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
7038 __func__, tm_function);
7039 if (ufshcd_clear_tm_cmd(hba, task_tag))
7040 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
7041 __func__, task_tag);
7042 err = -ETIMEDOUT;
7043 } else {
7044 err = 0;
7045 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
7046
7047 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
7048 }
7049
7050 spin_lock_irqsave(hba->host->host_lock, flags);
7051 hba->tmf_rqs[req->tag] = NULL;
7052 __clear_bit(task_tag, &hba->outstanding_tasks);
7053 spin_unlock_irqrestore(hba->host->host_lock, flags);
7054
7055 ufshcd_release(hba);
7056 blk_mq_free_request(req);
7057
7058 return err;
7059 }
7060
7061 /**
7062 * ufshcd_issue_tm_cmd - issues task management commands to controller
7063 * @hba: per adapter instance
7064 * @lun_id: LUN ID to which TM command is sent
7065 * @task_id: task ID to which the TM command is applicable
7066 * @tm_function: task management function opcode
7067 * @tm_response: task management service response return value
7068 *
7069 * Return: non-zero value on error, zero on success.
7070 */
ufshcd_issue_tm_cmd(struct ufs_hba * hba,int lun_id,int task_id,u8 tm_function,u8 * tm_response)7071 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7072 u8 tm_function, u8 *tm_response)
7073 {
7074 struct utp_task_req_desc treq = { };
7075 enum utp_ocs ocs_value;
7076 int err;
7077
7078 /* Configure task request descriptor */
7079 treq.header.interrupt = 1;
7080 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7081
7082 /* Configure task request UPIU */
7083 treq.upiu_req.req_header.transaction_code = UPIU_TRANSACTION_TASK_REQ;
7084 treq.upiu_req.req_header.lun = lun_id;
7085 treq.upiu_req.req_header.tm_function = tm_function;
7086
7087 /*
7088 * The host shall provide the same value for LUN field in the basic
7089 * header and for Input Parameter.
7090 */
7091 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7092 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7093
7094 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7095 if (err == -ETIMEDOUT)
7096 return err;
7097
7098 ocs_value = treq.header.ocs & MASK_OCS;
7099 if (ocs_value != OCS_SUCCESS)
7100 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7101 __func__, ocs_value);
7102 else if (tm_response)
7103 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7104 MASK_TM_SERVICE_RESP;
7105 return err;
7106 }
7107
7108 /**
7109 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7110 * @hba: per-adapter instance
7111 * @req_upiu: upiu request
7112 * @rsp_upiu: upiu reply
7113 * @desc_buff: pointer to descriptor buffer, NULL if NA
7114 * @buff_len: descriptor size, 0 if NA
7115 * @cmd_type: specifies the type (NOP, Query...)
7116 * @desc_op: descriptor operation
7117 *
7118 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7119 * Therefore, it "rides" the device management infrastructure: uses its tag and
7120 * tasks work queues.
7121 *
7122 * Since there is only one available tag for device management commands,
7123 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7124 *
7125 * Return: 0 upon success; < 0 upon failure.
7126 */
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)7127 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7128 struct utp_upiu_req *req_upiu,
7129 struct utp_upiu_req *rsp_upiu,
7130 u8 *desc_buff, int *buff_len,
7131 enum dev_cmd_type cmd_type,
7132 enum query_opcode desc_op)
7133 {
7134 DECLARE_COMPLETION_ONSTACK(wait);
7135 const u32 tag = hba->reserved_slot;
7136 struct ufshcd_lrb *lrbp;
7137 int err = 0;
7138 u8 upiu_flags;
7139
7140 /* Protects use of hba->reserved_slot. */
7141 lockdep_assert_held(&hba->dev_cmd.lock);
7142
7143 down_read(&hba->clk_scaling_lock);
7144
7145 lrbp = &hba->lrb[tag];
7146 lrbp->cmd = NULL;
7147 lrbp->task_tag = tag;
7148 lrbp->lun = 0;
7149 lrbp->intr_cmd = true;
7150 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7151 hba->dev_cmd.type = cmd_type;
7152
7153 if (hba->ufs_version <= ufshci_version(1, 1))
7154 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
7155 else
7156 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7157
7158 /* update the task tag in the request upiu */
7159 req_upiu->header.task_tag = tag;
7160
7161 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE, 0);
7162
7163 /* just copy the upiu request as it is */
7164 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7165 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7166 /* The Data Segment Area is optional depending upon the query
7167 * function value. for WRITE DESCRIPTOR, the data segment
7168 * follows right after the tsf.
7169 */
7170 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7171 *buff_len = 0;
7172 }
7173
7174 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7175
7176 hba->dev_cmd.complete = &wait;
7177
7178 ufshcd_add_query_upiu_trace(hba, UFS_QUERY_SEND, lrbp->ucd_req_ptr);
7179
7180 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7181 /*
7182 * ignore the returning value here - ufshcd_check_query_response is
7183 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7184 * read the response directly ignoring all errors.
7185 */
7186 ufshcd_wait_for_dev_cmd(hba, lrbp, QUERY_REQ_TIMEOUT);
7187
7188 /* just copy the upiu response as it is */
7189 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7190 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7191 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7192 u16 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
7193 .data_segment_length);
7194
7195 if (*buff_len >= resp_len) {
7196 memcpy(desc_buff, descp, resp_len);
7197 *buff_len = resp_len;
7198 } else {
7199 dev_warn(hba->dev,
7200 "%s: rsp size %d is bigger than buffer size %d",
7201 __func__, resp_len, *buff_len);
7202 *buff_len = 0;
7203 err = -EINVAL;
7204 }
7205 }
7206 ufshcd_add_query_upiu_trace(hba, err ? UFS_QUERY_ERR : UFS_QUERY_COMP,
7207 (struct utp_upiu_req *)lrbp->ucd_rsp_ptr);
7208
7209 up_read(&hba->clk_scaling_lock);
7210 return err;
7211 }
7212
7213 /**
7214 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7215 * @hba: per-adapter instance
7216 * @req_upiu: upiu request
7217 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7218 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7219 * @desc_buff: pointer to descriptor buffer, NULL if NA
7220 * @buff_len: descriptor size, 0 if NA
7221 * @desc_op: descriptor operation
7222 *
7223 * Supports UTP Transfer requests (nop and query), and UTP Task
7224 * Management requests.
7225 * It is up to the caller to fill the upiu conent properly, as it will
7226 * be copied without any further input validations.
7227 *
7228 * Return: 0 upon success; < 0 upon failure.
7229 */
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)7230 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7231 struct utp_upiu_req *req_upiu,
7232 struct utp_upiu_req *rsp_upiu,
7233 enum upiu_request_transaction msgcode,
7234 u8 *desc_buff, int *buff_len,
7235 enum query_opcode desc_op)
7236 {
7237 int err;
7238 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7239 struct utp_task_req_desc treq = { };
7240 enum utp_ocs ocs_value;
7241 u8 tm_f = req_upiu->header.tm_function;
7242
7243 switch (msgcode) {
7244 case UPIU_TRANSACTION_NOP_OUT:
7245 cmd_type = DEV_CMD_TYPE_NOP;
7246 fallthrough;
7247 case UPIU_TRANSACTION_QUERY_REQ:
7248 ufshcd_hold(hba);
7249 mutex_lock(&hba->dev_cmd.lock);
7250 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7251 desc_buff, buff_len,
7252 cmd_type, desc_op);
7253 mutex_unlock(&hba->dev_cmd.lock);
7254 ufshcd_release(hba);
7255
7256 break;
7257 case UPIU_TRANSACTION_TASK_REQ:
7258 treq.header.interrupt = 1;
7259 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7260
7261 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7262
7263 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7264 if (err == -ETIMEDOUT)
7265 break;
7266
7267 ocs_value = treq.header.ocs & MASK_OCS;
7268 if (ocs_value != OCS_SUCCESS) {
7269 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7270 ocs_value);
7271 break;
7272 }
7273
7274 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7275
7276 break;
7277 default:
7278 err = -EINVAL;
7279
7280 break;
7281 }
7282
7283 return err;
7284 }
7285
7286 /**
7287 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7288 * @hba: per adapter instance
7289 * @req_upiu: upiu request
7290 * @rsp_upiu: upiu reply
7291 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7292 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7293 * @sg_cnt: The number of sg lists actually used
7294 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7295 * @dir: DMA direction
7296 *
7297 * Return: zero on success, non-zero on failure.
7298 */
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)7299 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7300 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7301 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7302 enum dma_data_direction dir)
7303 {
7304 DECLARE_COMPLETION_ONSTACK(wait);
7305 const u32 tag = hba->reserved_slot;
7306 struct ufshcd_lrb *lrbp;
7307 int err = 0;
7308 int result;
7309 u8 upiu_flags;
7310 u8 *ehs_data;
7311 u16 ehs_len;
7312
7313 /* Protects use of hba->reserved_slot. */
7314 ufshcd_hold(hba);
7315 mutex_lock(&hba->dev_cmd.lock);
7316 down_read(&hba->clk_scaling_lock);
7317
7318 lrbp = &hba->lrb[tag];
7319 lrbp->cmd = NULL;
7320 lrbp->task_tag = tag;
7321 lrbp->lun = UFS_UPIU_RPMB_WLUN;
7322
7323 lrbp->intr_cmd = true;
7324 ufshcd_prepare_lrbp_crypto(NULL, lrbp);
7325 hba->dev_cmd.type = DEV_CMD_TYPE_RPMB;
7326
7327 /* Advanced RPMB starts from UFS 4.0, so its command type is UTP_CMD_TYPE_UFS_STORAGE */
7328 lrbp->command_type = UTP_CMD_TYPE_UFS_STORAGE;
7329
7330 /*
7331 * According to UFSHCI 4.0 specification page 24, if EHSLUTRDS is 0, host controller takes
7332 * EHS length from CMD UPIU, and SW driver use EHS Length field in CMD UPIU. if it is 1,
7333 * HW controller takes EHS length from UTRD.
7334 */
7335 if (hba->capabilities & MASK_EHSLUTRD_SUPPORTED)
7336 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 2);
7337 else
7338 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, dir, 0);
7339
7340 /* update the task tag */
7341 req_upiu->header.task_tag = tag;
7342
7343 /* copy the UPIU(contains CDB) request as it is */
7344 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7345 /* Copy EHS, starting with byte32, immediately after the CDB package */
7346 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7347
7348 if (dir != DMA_NONE && sg_list)
7349 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7350
7351 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7352
7353 hba->dev_cmd.complete = &wait;
7354
7355 ufshcd_send_command(hba, tag, hba->dev_cmd_queue);
7356
7357 err = ufshcd_wait_for_dev_cmd(hba, lrbp, ADVANCED_RPMB_REQ_TIMEOUT);
7358
7359 if (!err) {
7360 /* Just copy the upiu response as it is */
7361 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7362 /* Get the response UPIU result */
7363 result = (lrbp->ucd_rsp_ptr->header.response << 8) |
7364 lrbp->ucd_rsp_ptr->header.status;
7365
7366 ehs_len = lrbp->ucd_rsp_ptr->header.ehs_length;
7367 /*
7368 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7369 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7370 * Message is 02h
7371 */
7372 if (ehs_len == 2 && rsp_ehs) {
7373 /*
7374 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7375 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7376 */
7377 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7378 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7379 }
7380 }
7381
7382 up_read(&hba->clk_scaling_lock);
7383 mutex_unlock(&hba->dev_cmd.lock);
7384 ufshcd_release(hba);
7385 return err ? : result;
7386 }
7387
7388 /**
7389 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7390 * @cmd: SCSI command pointer
7391 *
7392 * Return: SUCCESS or FAILED.
7393 */
ufshcd_eh_device_reset_handler(struct scsi_cmnd * cmd)7394 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7395 {
7396 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7397 struct Scsi_Host *host;
7398 struct ufs_hba *hba;
7399 struct ufs_hw_queue *hwq;
7400 struct ufshcd_lrb *lrbp;
7401 u32 pos, not_cleared_mask = 0;
7402 int err;
7403 u8 resp = 0xF, lun;
7404
7405 host = cmd->device->host;
7406 hba = shost_priv(host);
7407
7408 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7409 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7410 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7411 if (!err)
7412 err = resp;
7413 goto out;
7414 }
7415
7416 if (is_mcq_enabled(hba)) {
7417 for (pos = 0; pos < hba->nutrs; pos++) {
7418 lrbp = &hba->lrb[pos];
7419 if (ufshcd_cmd_inflight(lrbp->cmd) &&
7420 lrbp->lun == lun) {
7421 ufshcd_clear_cmd(hba, pos);
7422 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
7423 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7424 }
7425 }
7426 err = 0;
7427 goto out;
7428 }
7429
7430 /* clear the commands that were pending for corresponding LUN */
7431 spin_lock_irqsave(&hba->outstanding_lock, flags);
7432 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7433 if (hba->lrb[pos].lun == lun)
7434 __set_bit(pos, &pending_reqs);
7435 hba->outstanding_reqs &= ~pending_reqs;
7436 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7437
7438 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7439 if (ufshcd_clear_cmd(hba, pos) < 0) {
7440 spin_lock_irqsave(&hba->outstanding_lock, flags);
7441 not_cleared = 1U << pos &
7442 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7443 hba->outstanding_reqs |= not_cleared;
7444 not_cleared_mask |= not_cleared;
7445 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7446
7447 dev_err(hba->dev, "%s: failed to clear request %d\n",
7448 __func__, pos);
7449 }
7450 }
7451 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7452
7453 out:
7454 hba->req_abort_count = 0;
7455 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7456 if (!err) {
7457 err = SUCCESS;
7458 } else {
7459 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7460 err = FAILED;
7461 }
7462 return err;
7463 }
7464
ufshcd_set_req_abort_skip(struct ufs_hba * hba,unsigned long bitmap)7465 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7466 {
7467 struct ufshcd_lrb *lrbp;
7468 int tag;
7469
7470 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7471 lrbp = &hba->lrb[tag];
7472 lrbp->req_abort_skip = true;
7473 }
7474 }
7475
7476 /**
7477 * ufshcd_try_to_abort_task - abort a specific task
7478 * @hba: Pointer to adapter instance
7479 * @tag: Task tag/index to be aborted
7480 *
7481 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7482 * command, and in host controller by clearing the door-bell register. There can
7483 * be race between controller sending the command to the device while abort is
7484 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7485 * really issued and then try to abort it.
7486 *
7487 * Return: zero on success, non-zero on failure.
7488 */
ufshcd_try_to_abort_task(struct ufs_hba * hba,int tag)7489 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7490 {
7491 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7492 int err = 0;
7493 int poll_cnt;
7494 u8 resp = 0xF;
7495 u32 reg;
7496
7497 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7498 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7499 UFS_QUERY_TASK, &resp);
7500 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7501 /* cmd pending in the device */
7502 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7503 __func__, tag);
7504 break;
7505 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7506 /*
7507 * cmd not pending in the device, check if it is
7508 * in transition.
7509 */
7510 dev_err(hba->dev, "%s: cmd at tag %d not pending in the device.\n",
7511 __func__, tag);
7512 if (is_mcq_enabled(hba)) {
7513 /* MCQ mode */
7514 if (ufshcd_cmd_inflight(lrbp->cmd)) {
7515 /* sleep for max. 200us same delay as in SDB mode */
7516 usleep_range(100, 200);
7517 continue;
7518 }
7519 /* command completed already */
7520 dev_err(hba->dev, "%s: cmd at tag=%d is cleared.\n",
7521 __func__, tag);
7522 goto out;
7523 }
7524
7525 /* Single Doorbell Mode */
7526 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7527 if (reg & (1 << tag)) {
7528 /* sleep for max. 200us to stabilize */
7529 usleep_range(100, 200);
7530 continue;
7531 }
7532 /* command completed already */
7533 dev_err(hba->dev, "%s: cmd at tag %d successfully cleared from DB.\n",
7534 __func__, tag);
7535 goto out;
7536 } else {
7537 dev_err(hba->dev,
7538 "%s: no response from device. tag = %d, err %d\n",
7539 __func__, tag, err);
7540 if (!err)
7541 err = resp; /* service response error */
7542 goto out;
7543 }
7544 }
7545
7546 if (!poll_cnt) {
7547 err = -EBUSY;
7548 goto out;
7549 }
7550
7551 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7552 UFS_ABORT_TASK, &resp);
7553 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7554 if (!err) {
7555 err = resp; /* service response error */
7556 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7557 __func__, tag, err);
7558 }
7559 goto out;
7560 }
7561
7562 err = ufshcd_clear_cmd(hba, tag);
7563 if (err)
7564 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7565 __func__, tag, err);
7566
7567 out:
7568 return err;
7569 }
7570
7571 /**
7572 * ufshcd_abort - scsi host template eh_abort_handler callback
7573 * @cmd: SCSI command pointer
7574 *
7575 * Return: SUCCESS or FAILED.
7576 */
ufshcd_abort(struct scsi_cmnd * cmd)7577 static int ufshcd_abort(struct scsi_cmnd *cmd)
7578 {
7579 struct Scsi_Host *host = cmd->device->host;
7580 struct ufs_hba *hba = shost_priv(host);
7581 int tag = scsi_cmd_to_rq(cmd)->tag;
7582 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7583 unsigned long flags;
7584 int err = FAILED;
7585 bool outstanding;
7586 u32 reg;
7587
7588 WARN_ONCE(tag < 0, "Invalid tag %d\n", tag);
7589
7590 ufshcd_hold(hba);
7591
7592 if (!is_mcq_enabled(hba)) {
7593 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7594 if (!test_bit(tag, &hba->outstanding_reqs)) {
7595 /* If command is already aborted/completed, return FAILED. */
7596 dev_err(hba->dev,
7597 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7598 __func__, tag, hba->outstanding_reqs, reg);
7599 goto release;
7600 }
7601 }
7602
7603 /* Print Transfer Request of aborted task */
7604 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7605
7606 /*
7607 * Print detailed info about aborted request.
7608 * As more than one request might get aborted at the same time,
7609 * print full information only for the first aborted request in order
7610 * to reduce repeated printouts. For other aborted requests only print
7611 * basic details.
7612 */
7613 scsi_print_command(cmd);
7614 if (!hba->req_abort_count) {
7615 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7616 ufshcd_print_evt_hist(hba);
7617 ufshcd_print_host_state(hba);
7618 ufshcd_print_pwr_info(hba);
7619 ufshcd_print_tr(hba, tag, true);
7620 } else {
7621 ufshcd_print_tr(hba, tag, false);
7622 }
7623 hba->req_abort_count++;
7624
7625 if (!is_mcq_enabled(hba) && !(reg & (1 << tag))) {
7626 /* only execute this code in single doorbell mode */
7627 dev_err(hba->dev,
7628 "%s: cmd was completed, but without a notifying intr, tag = %d",
7629 __func__, tag);
7630 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7631 goto release;
7632 }
7633
7634 /*
7635 * Task abort to the device W-LUN is illegal. When this command
7636 * will fail, due to spec violation, scsi err handling next step
7637 * will be to send LU reset which, again, is a spec violation.
7638 * To avoid these unnecessary/illegal steps, first we clean up
7639 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7640 * then queue the eh_work and bail.
7641 */
7642 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7643 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7644
7645 spin_lock_irqsave(host->host_lock, flags);
7646 hba->force_reset = true;
7647 ufshcd_schedule_eh_work(hba);
7648 spin_unlock_irqrestore(host->host_lock, flags);
7649 goto release;
7650 }
7651
7652 if (is_mcq_enabled(hba)) {
7653 /* MCQ mode. Branch off to handle abort for mcq mode */
7654 err = ufshcd_mcq_abort(cmd);
7655 goto release;
7656 }
7657
7658 /* Skip task abort in case previous aborts failed and report failure */
7659 if (lrbp->req_abort_skip) {
7660 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7661 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7662 goto release;
7663 }
7664
7665 err = ufshcd_try_to_abort_task(hba, tag);
7666 if (err) {
7667 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7668 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7669 err = FAILED;
7670 goto release;
7671 }
7672
7673 /*
7674 * Clear the corresponding bit from outstanding_reqs since the command
7675 * has been aborted successfully.
7676 */
7677 spin_lock_irqsave(&hba->outstanding_lock, flags);
7678 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7679 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7680
7681 if (outstanding)
7682 ufshcd_release_scsi_cmd(hba, lrbp);
7683
7684 err = SUCCESS;
7685
7686 release:
7687 /* Matches the ufshcd_hold() call at the start of this function. */
7688 ufshcd_release(hba);
7689 return err;
7690 }
7691
7692 /**
7693 * ufshcd_host_reset_and_restore - reset and restore host controller
7694 * @hba: per-adapter instance
7695 *
7696 * Note that host controller reset may issue DME_RESET to
7697 * local and remote (device) Uni-Pro stack and the attributes
7698 * are reset to default state.
7699 *
7700 * Return: zero on success, non-zero on failure.
7701 */
ufshcd_host_reset_and_restore(struct ufs_hba * hba)7702 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7703 {
7704 int err;
7705
7706 /*
7707 * Stop the host controller and complete the requests
7708 * cleared by h/w
7709 */
7710 ufshcd_hba_stop(hba);
7711 hba->silence_err_logs = true;
7712 ufshcd_complete_requests(hba, true);
7713 hba->silence_err_logs = false;
7714
7715 /* scale up clocks to max frequency before full reinitialization */
7716 ufshcd_scale_clks(hba, true);
7717
7718 err = ufshcd_hba_enable(hba);
7719
7720 /* Establish the link again and restore the device */
7721 if (!err)
7722 err = ufshcd_probe_hba(hba, false);
7723
7724 if (err)
7725 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7726 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7727 return err;
7728 }
7729
7730 /**
7731 * ufshcd_reset_and_restore - reset and re-initialize host/device
7732 * @hba: per-adapter instance
7733 *
7734 * Reset and recover device, host and re-establish link. This
7735 * is helpful to recover the communication in fatal error conditions.
7736 *
7737 * Return: zero on success, non-zero on failure.
7738 */
ufshcd_reset_and_restore(struct ufs_hba * hba)7739 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7740 {
7741 u32 saved_err = 0;
7742 u32 saved_uic_err = 0;
7743 int err = 0;
7744 unsigned long flags;
7745 int retries = MAX_HOST_RESET_RETRIES;
7746
7747 spin_lock_irqsave(hba->host->host_lock, flags);
7748 do {
7749 /*
7750 * This is a fresh start, cache and clear saved error first,
7751 * in case new error generated during reset and restore.
7752 */
7753 saved_err |= hba->saved_err;
7754 saved_uic_err |= hba->saved_uic_err;
7755 hba->saved_err = 0;
7756 hba->saved_uic_err = 0;
7757 hba->force_reset = false;
7758 hba->ufshcd_state = UFSHCD_STATE_RESET;
7759 spin_unlock_irqrestore(hba->host->host_lock, flags);
7760
7761 /* Reset the attached device */
7762 ufshcd_device_reset(hba);
7763
7764 err = ufshcd_host_reset_and_restore(hba);
7765
7766 spin_lock_irqsave(hba->host->host_lock, flags);
7767 if (err)
7768 continue;
7769 /* Do not exit unless operational or dead */
7770 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7771 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7772 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7773 err = -EAGAIN;
7774 } while (err && --retries);
7775
7776 /*
7777 * Inform scsi mid-layer that we did reset and allow to handle
7778 * Unit Attention properly.
7779 */
7780 scsi_report_bus_reset(hba->host, 0);
7781 if (err) {
7782 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7783 hba->saved_err |= saved_err;
7784 hba->saved_uic_err |= saved_uic_err;
7785 }
7786 spin_unlock_irqrestore(hba->host->host_lock, flags);
7787
7788 return err;
7789 }
7790
7791 /**
7792 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7793 * @cmd: SCSI command pointer
7794 *
7795 * Return: SUCCESS or FAILED.
7796 */
ufshcd_eh_host_reset_handler(struct scsi_cmnd * cmd)7797 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7798 {
7799 int err = SUCCESS;
7800 unsigned long flags;
7801 struct ufs_hba *hba;
7802
7803 hba = shost_priv(cmd->device->host);
7804
7805 spin_lock_irqsave(hba->host->host_lock, flags);
7806 hba->force_reset = true;
7807 ufshcd_schedule_eh_work(hba);
7808 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7809 spin_unlock_irqrestore(hba->host->host_lock, flags);
7810
7811 flush_work(&hba->eh_work);
7812
7813 spin_lock_irqsave(hba->host->host_lock, flags);
7814 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
7815 err = FAILED;
7816 spin_unlock_irqrestore(hba->host->host_lock, flags);
7817
7818 return err;
7819 }
7820
7821 /**
7822 * ufshcd_get_max_icc_level - calculate the ICC level
7823 * @sup_curr_uA: max. current supported by the regulator
7824 * @start_scan: row at the desc table to start scan from
7825 * @buff: power descriptor buffer
7826 *
7827 * Return: calculated max ICC level for specific regulator.
7828 */
ufshcd_get_max_icc_level(int sup_curr_uA,u32 start_scan,const char * buff)7829 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
7830 const char *buff)
7831 {
7832 int i;
7833 int curr_uA;
7834 u16 data;
7835 u16 unit;
7836
7837 for (i = start_scan; i >= 0; i--) {
7838 data = get_unaligned_be16(&buff[2 * i]);
7839 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
7840 ATTR_ICC_LVL_UNIT_OFFSET;
7841 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
7842 switch (unit) {
7843 case UFSHCD_NANO_AMP:
7844 curr_uA = curr_uA / 1000;
7845 break;
7846 case UFSHCD_MILI_AMP:
7847 curr_uA = curr_uA * 1000;
7848 break;
7849 case UFSHCD_AMP:
7850 curr_uA = curr_uA * 1000 * 1000;
7851 break;
7852 case UFSHCD_MICRO_AMP:
7853 default:
7854 break;
7855 }
7856 if (sup_curr_uA >= curr_uA)
7857 break;
7858 }
7859 if (i < 0) {
7860 i = 0;
7861 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
7862 }
7863
7864 return (u32)i;
7865 }
7866
7867 /**
7868 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
7869 * In case regulators are not initialized we'll return 0
7870 * @hba: per-adapter instance
7871 * @desc_buf: power descriptor buffer to extract ICC levels from.
7872 *
7873 * Return: calculated ICC level.
7874 */
ufshcd_find_max_sup_active_icc_level(struct ufs_hba * hba,const u8 * desc_buf)7875 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
7876 const u8 *desc_buf)
7877 {
7878 u32 icc_level = 0;
7879
7880 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
7881 !hba->vreg_info.vccq2) {
7882 /*
7883 * Using dev_dbg to avoid messages during runtime PM to avoid
7884 * never-ending cycles of messages written back to storage by
7885 * user space causing runtime resume, causing more messages and
7886 * so on.
7887 */
7888 dev_dbg(hba->dev,
7889 "%s: Regulator capability was not set, actvIccLevel=%d",
7890 __func__, icc_level);
7891 goto out;
7892 }
7893
7894 if (hba->vreg_info.vcc->max_uA)
7895 icc_level = ufshcd_get_max_icc_level(
7896 hba->vreg_info.vcc->max_uA,
7897 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
7898 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
7899
7900 if (hba->vreg_info.vccq->max_uA)
7901 icc_level = ufshcd_get_max_icc_level(
7902 hba->vreg_info.vccq->max_uA,
7903 icc_level,
7904 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
7905
7906 if (hba->vreg_info.vccq2->max_uA)
7907 icc_level = ufshcd_get_max_icc_level(
7908 hba->vreg_info.vccq2->max_uA,
7909 icc_level,
7910 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
7911 out:
7912 return icc_level;
7913 }
7914
ufshcd_set_active_icc_lvl(struct ufs_hba * hba)7915 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
7916 {
7917 int ret;
7918 u8 *desc_buf;
7919 u32 icc_level;
7920
7921 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
7922 if (!desc_buf)
7923 return;
7924
7925 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
7926 desc_buf, QUERY_DESC_MAX_SIZE);
7927 if (ret) {
7928 dev_err(hba->dev,
7929 "%s: Failed reading power descriptor ret = %d",
7930 __func__, ret);
7931 goto out;
7932 }
7933
7934 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
7935 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
7936
7937 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
7938 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
7939
7940 if (ret)
7941 dev_err(hba->dev,
7942 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
7943 __func__, icc_level, ret);
7944
7945 out:
7946 kfree(desc_buf);
7947 }
7948
ufshcd_blk_pm_runtime_init(struct scsi_device * sdev)7949 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
7950 {
7951 scsi_autopm_get_device(sdev);
7952 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
7953 if (sdev->rpm_autosuspend)
7954 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
7955 RPM_AUTOSUSPEND_DELAY_MS);
7956 scsi_autopm_put_device(sdev);
7957 }
7958
7959 /**
7960 * ufshcd_scsi_add_wlus - Adds required W-LUs
7961 * @hba: per-adapter instance
7962 *
7963 * UFS device specification requires the UFS devices to support 4 well known
7964 * logical units:
7965 * "REPORT_LUNS" (address: 01h)
7966 * "UFS Device" (address: 50h)
7967 * "RPMB" (address: 44h)
7968 * "BOOT" (address: 30h)
7969 * UFS device's power management needs to be controlled by "POWER CONDITION"
7970 * field of SSU (START STOP UNIT) command. But this "power condition" field
7971 * will take effect only when its sent to "UFS device" well known logical unit
7972 * hence we require the scsi_device instance to represent this logical unit in
7973 * order for the UFS host driver to send the SSU command for power management.
7974 *
7975 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
7976 * Block) LU so user space process can control this LU. User space may also
7977 * want to have access to BOOT LU.
7978 *
7979 * This function adds scsi device instances for each of all well known LUs
7980 * (except "REPORT LUNS" LU).
7981 *
7982 * Return: zero on success (all required W-LUs are added successfully),
7983 * non-zero error value on failure (if failed to add any of the required W-LU).
7984 */
ufshcd_scsi_add_wlus(struct ufs_hba * hba)7985 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
7986 {
7987 int ret = 0;
7988 struct scsi_device *sdev_boot, *sdev_rpmb;
7989
7990 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
7991 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
7992 if (IS_ERR(hba->ufs_device_wlun)) {
7993 ret = PTR_ERR(hba->ufs_device_wlun);
7994 hba->ufs_device_wlun = NULL;
7995 goto out;
7996 }
7997 scsi_device_put(hba->ufs_device_wlun);
7998
7999 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
8000 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
8001 if (IS_ERR(sdev_rpmb)) {
8002 ret = PTR_ERR(sdev_rpmb);
8003 goto remove_ufs_device_wlun;
8004 }
8005 ufshcd_blk_pm_runtime_init(sdev_rpmb);
8006 scsi_device_put(sdev_rpmb);
8007
8008 sdev_boot = __scsi_add_device(hba->host, 0, 0,
8009 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
8010 if (IS_ERR(sdev_boot)) {
8011 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
8012 } else {
8013 ufshcd_blk_pm_runtime_init(sdev_boot);
8014 scsi_device_put(sdev_boot);
8015 }
8016 goto out;
8017
8018 remove_ufs_device_wlun:
8019 scsi_remove_device(hba->ufs_device_wlun);
8020 out:
8021 return ret;
8022 }
8023
ufshcd_wb_probe(struct ufs_hba * hba,const u8 * desc_buf)8024 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
8025 {
8026 struct ufs_dev_info *dev_info = &hba->dev_info;
8027 u8 lun;
8028 u32 d_lu_wb_buf_alloc;
8029 u32 ext_ufs_feature;
8030
8031 if (!ufshcd_is_wb_allowed(hba))
8032 return;
8033
8034 /*
8035 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
8036 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
8037 * enabled
8038 */
8039 if (!(dev_info->wspecversion >= 0x310 ||
8040 dev_info->wspecversion == 0x220 ||
8041 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
8042 goto wb_disabled;
8043
8044 ext_ufs_feature = get_unaligned_be32(desc_buf +
8045 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8046
8047 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
8048 goto wb_disabled;
8049
8050 /*
8051 * WB may be supported but not configured while provisioning. The spec
8052 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
8053 * buffer configured.
8054 */
8055 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
8056
8057 dev_info->b_presrv_uspc_en =
8058 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
8059
8060 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
8061 if (!get_unaligned_be32(desc_buf +
8062 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
8063 goto wb_disabled;
8064 } else {
8065 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
8066 d_lu_wb_buf_alloc = 0;
8067 ufshcd_read_unit_desc_param(hba,
8068 lun,
8069 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
8070 (u8 *)&d_lu_wb_buf_alloc,
8071 sizeof(d_lu_wb_buf_alloc));
8072 if (d_lu_wb_buf_alloc) {
8073 dev_info->wb_dedicated_lu = lun;
8074 break;
8075 }
8076 }
8077
8078 if (!d_lu_wb_buf_alloc)
8079 goto wb_disabled;
8080 }
8081
8082 if (!ufshcd_is_wb_buf_lifetime_available(hba))
8083 goto wb_disabled;
8084
8085 return;
8086
8087 wb_disabled:
8088 hba->caps &= ~UFSHCD_CAP_WB_EN;
8089 }
8090
ufshcd_temp_notif_probe(struct ufs_hba * hba,const u8 * desc_buf)8091 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8092 {
8093 struct ufs_dev_info *dev_info = &hba->dev_info;
8094 u32 ext_ufs_feature;
8095 u8 mask = 0;
8096
8097 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8098 return;
8099
8100 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8101
8102 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8103 mask |= MASK_EE_TOO_LOW_TEMP;
8104
8105 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8106 mask |= MASK_EE_TOO_HIGH_TEMP;
8107
8108 if (mask) {
8109 ufshcd_enable_ee(hba, mask);
8110 ufs_hwmon_probe(hba, mask);
8111 }
8112 }
8113
ufshcd_ext_iid_probe(struct ufs_hba * hba,u8 * desc_buf)8114 static void ufshcd_ext_iid_probe(struct ufs_hba *hba, u8 *desc_buf)
8115 {
8116 struct ufs_dev_info *dev_info = &hba->dev_info;
8117 u32 ext_ufs_feature;
8118 u32 ext_iid_en = 0;
8119 int err;
8120
8121 /* Only UFS-4.0 and above may support EXT_IID */
8122 if (dev_info->wspecversion < 0x400)
8123 goto out;
8124
8125 ext_ufs_feature = get_unaligned_be32(desc_buf +
8126 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8127 if (!(ext_ufs_feature & UFS_DEV_EXT_IID_SUP))
8128 goto out;
8129
8130 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8131 QUERY_ATTR_IDN_EXT_IID_EN, 0, 0, &ext_iid_en);
8132 if (err)
8133 dev_err(hba->dev, "failed reading bEXTIIDEn. err = %d\n", err);
8134
8135 out:
8136 dev_info->b_ext_iid_en = ext_iid_en;
8137 }
8138
ufshcd_fixup_dev_quirks(struct ufs_hba * hba,const struct ufs_dev_quirk * fixups)8139 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8140 const struct ufs_dev_quirk *fixups)
8141 {
8142 const struct ufs_dev_quirk *f;
8143 struct ufs_dev_info *dev_info = &hba->dev_info;
8144
8145 if (!fixups)
8146 return;
8147
8148 for (f = fixups; f->quirk; f++) {
8149 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8150 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8151 ((dev_info->model &&
8152 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8153 !strcmp(f->model, UFS_ANY_MODEL)))
8154 hba->dev_quirks |= f->quirk;
8155 }
8156 }
8157 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8158
ufs_fixup_device_setup(struct ufs_hba * hba)8159 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8160 {
8161 /* fix by general quirk table */
8162 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8163
8164 /* allow vendors to fix quirks */
8165 ufshcd_vops_fixup_dev_quirks(hba);
8166 }
8167
ufshcd_update_rtc(struct ufs_hba * hba)8168 static void ufshcd_update_rtc(struct ufs_hba *hba)
8169 {
8170 struct timespec64 ts64;
8171 int err;
8172 u32 val;
8173
8174 ktime_get_real_ts64(&ts64);
8175
8176 if (ts64.tv_sec < hba->dev_info.rtc_time_baseline) {
8177 dev_warn_once(hba->dev, "%s: Current time precedes previous setting!\n", __func__);
8178 return;
8179 }
8180
8181 /*
8182 * The Absolute RTC mode has a 136-year limit, spanning from 2010 to 2146. If a time beyond
8183 * 2146 is required, it is recommended to choose the relative RTC mode.
8184 */
8185 val = ts64.tv_sec - hba->dev_info.rtc_time_baseline;
8186
8187 /* Skip update RTC if RPM state is not RPM_ACTIVE */
8188 if (ufshcd_rpm_get_if_active(hba) <= 0)
8189 return;
8190
8191 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, QUERY_ATTR_IDN_SECONDS_PASSED,
8192 0, 0, &val);
8193 ufshcd_rpm_put(hba);
8194
8195 if (err)
8196 dev_err(hba->dev, "%s: Failed to update rtc %d\n", __func__, err);
8197 else if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
8198 hba->dev_info.rtc_time_baseline = ts64.tv_sec;
8199 }
8200
ufshcd_rtc_work(struct work_struct * work)8201 static void ufshcd_rtc_work(struct work_struct *work)
8202 {
8203 struct ufs_hba *hba;
8204
8205 hba = container_of(to_delayed_work(work), struct ufs_hba, ufs_rtc_update_work);
8206
8207 /* Update RTC only when there are no requests in progress and UFSHCI is operational */
8208 if (!ufshcd_is_ufs_dev_busy(hba) &&
8209 hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL &&
8210 !hba->clk_gating.active_reqs)
8211 ufshcd_update_rtc(hba);
8212
8213 if (ufshcd_is_ufs_dev_active(hba))
8214 schedule_delayed_work(&hba->ufs_rtc_update_work,
8215 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
8216 }
8217
ufs_init_rtc(struct ufs_hba * hba,u8 * desc_buf)8218 static void ufs_init_rtc(struct ufs_hba *hba, u8 *desc_buf)
8219 {
8220 u16 periodic_rtc_update = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_FRQ_RTC]);
8221 struct ufs_dev_info *dev_info = &hba->dev_info;
8222
8223 if (periodic_rtc_update & UFS_RTC_TIME_BASELINE) {
8224 dev_info->rtc_type = UFS_RTC_ABSOLUTE;
8225
8226 /*
8227 * The concept of measuring time in Linux as the number of seconds elapsed since
8228 * 00:00:00 UTC on January 1, 1970, and UFS ABS RTC is elapsed from January 1st
8229 * 2010 00:00, here we need to adjust ABS baseline.
8230 */
8231 dev_info->rtc_time_baseline = mktime64(2010, 1, 1, 0, 0, 0) -
8232 mktime64(1970, 1, 1, 0, 0, 0);
8233 } else {
8234 dev_info->rtc_type = UFS_RTC_RELATIVE;
8235 dev_info->rtc_time_baseline = 0;
8236 }
8237 }
8238
ufs_get_device_desc(struct ufs_hba * hba)8239 static int ufs_get_device_desc(struct ufs_hba *hba)
8240 {
8241 int err;
8242 u8 model_index;
8243 u8 *desc_buf;
8244 struct ufs_dev_info *dev_info = &hba->dev_info;
8245
8246 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8247 if (!desc_buf) {
8248 err = -ENOMEM;
8249 goto out;
8250 }
8251
8252 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8253 QUERY_DESC_MAX_SIZE);
8254 if (err) {
8255 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8256 __func__, err);
8257 goto out;
8258 }
8259
8260 /*
8261 * getting vendor (manufacturerID) and Bank Index in big endian
8262 * format
8263 */
8264 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8265 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8266
8267 /* getting Specification Version in big endian format */
8268 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8269 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8270 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8271
8272 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8273
8274 err = ufshcd_read_string_desc(hba, model_index,
8275 &dev_info->model, SD_ASCII_STD);
8276 if (err < 0) {
8277 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8278 __func__, err);
8279 goto out;
8280 }
8281
8282 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8283 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8284
8285 ufs_fixup_device_setup(hba);
8286
8287 ufshcd_wb_probe(hba, desc_buf);
8288
8289 ufshcd_temp_notif_probe(hba, desc_buf);
8290
8291 ufs_init_rtc(hba, desc_buf);
8292
8293 if (hba->ext_iid_sup)
8294 ufshcd_ext_iid_probe(hba, desc_buf);
8295
8296 /*
8297 * ufshcd_read_string_desc returns size of the string
8298 * reset the error value
8299 */
8300 err = 0;
8301
8302 out:
8303 kfree(desc_buf);
8304 return err;
8305 }
8306
ufs_put_device_desc(struct ufs_hba * hba)8307 static void ufs_put_device_desc(struct ufs_hba *hba)
8308 {
8309 struct ufs_dev_info *dev_info = &hba->dev_info;
8310
8311 kfree(dev_info->model);
8312 dev_info->model = NULL;
8313 }
8314
8315 /**
8316 * ufshcd_tune_pa_tactivate - Tunes PA_TActivate of local UniPro
8317 * @hba: per-adapter instance
8318 *
8319 * PA_TActivate parameter can be tuned manually if UniPro version is less than
8320 * 1.61. PA_TActivate needs to be greater than or equal to peerM-PHY's
8321 * RX_MIN_ACTIVATETIME_CAPABILITY attribute. This optimal value can help reduce
8322 * the hibern8 exit latency.
8323 *
8324 * Return: zero on success, non-zero error value on failure.
8325 */
ufshcd_tune_pa_tactivate(struct ufs_hba * hba)8326 static int ufshcd_tune_pa_tactivate(struct ufs_hba *hba)
8327 {
8328 int ret = 0;
8329 u32 peer_rx_min_activatetime = 0, tuned_pa_tactivate;
8330
8331 ret = ufshcd_dme_peer_get(hba,
8332 UIC_ARG_MIB_SEL(
8333 RX_MIN_ACTIVATETIME_CAPABILITY,
8334 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8335 &peer_rx_min_activatetime);
8336 if (ret)
8337 goto out;
8338
8339 /* make sure proper unit conversion is applied */
8340 tuned_pa_tactivate =
8341 ((peer_rx_min_activatetime * RX_MIN_ACTIVATETIME_UNIT_US)
8342 / PA_TACTIVATE_TIME_UNIT_US);
8343 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8344 tuned_pa_tactivate);
8345
8346 out:
8347 return ret;
8348 }
8349
8350 /**
8351 * ufshcd_tune_pa_hibern8time - Tunes PA_Hibern8Time of local UniPro
8352 * @hba: per-adapter instance
8353 *
8354 * PA_Hibern8Time parameter can be tuned manually if UniPro version is less than
8355 * 1.61. PA_Hibern8Time needs to be maximum of local M-PHY's
8356 * TX_HIBERN8TIME_CAPABILITY & peer M-PHY's RX_HIBERN8TIME_CAPABILITY.
8357 * This optimal value can help reduce the hibern8 exit latency.
8358 *
8359 * Return: zero on success, non-zero error value on failure.
8360 */
ufshcd_tune_pa_hibern8time(struct ufs_hba * hba)8361 static int ufshcd_tune_pa_hibern8time(struct ufs_hba *hba)
8362 {
8363 int ret = 0;
8364 u32 local_tx_hibern8_time_cap = 0, peer_rx_hibern8_time_cap = 0;
8365 u32 max_hibern8_time, tuned_pa_hibern8time;
8366
8367 ret = ufshcd_dme_get(hba,
8368 UIC_ARG_MIB_SEL(TX_HIBERN8TIME_CAPABILITY,
8369 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(0)),
8370 &local_tx_hibern8_time_cap);
8371 if (ret)
8372 goto out;
8373
8374 ret = ufshcd_dme_peer_get(hba,
8375 UIC_ARG_MIB_SEL(RX_HIBERN8TIME_CAPABILITY,
8376 UIC_ARG_MPHY_RX_GEN_SEL_INDEX(0)),
8377 &peer_rx_hibern8_time_cap);
8378 if (ret)
8379 goto out;
8380
8381 max_hibern8_time = max(local_tx_hibern8_time_cap,
8382 peer_rx_hibern8_time_cap);
8383 /* make sure proper unit conversion is applied */
8384 tuned_pa_hibern8time = ((max_hibern8_time * HIBERN8TIME_UNIT_US)
8385 / PA_HIBERN8_TIME_UNIT_US);
8386 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME),
8387 tuned_pa_hibern8time);
8388 out:
8389 return ret;
8390 }
8391
8392 /**
8393 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8394 * less than device PA_TACTIVATE time.
8395 * @hba: per-adapter instance
8396 *
8397 * Some UFS devices require host PA_TACTIVATE to be lower than device
8398 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8399 * for such devices.
8400 *
8401 * Return: zero on success, non-zero error value on failure.
8402 */
ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba * hba)8403 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8404 {
8405 int ret = 0;
8406 u32 granularity, peer_granularity;
8407 u32 pa_tactivate, peer_pa_tactivate;
8408 u32 pa_tactivate_us, peer_pa_tactivate_us;
8409 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8410
8411 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8412 &granularity);
8413 if (ret)
8414 goto out;
8415
8416 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8417 &peer_granularity);
8418 if (ret)
8419 goto out;
8420
8421 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8422 (granularity > PA_GRANULARITY_MAX_VAL)) {
8423 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8424 __func__, granularity);
8425 return -EINVAL;
8426 }
8427
8428 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8429 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8430 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8431 __func__, peer_granularity);
8432 return -EINVAL;
8433 }
8434
8435 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8436 if (ret)
8437 goto out;
8438
8439 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8440 &peer_pa_tactivate);
8441 if (ret)
8442 goto out;
8443
8444 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8445 peer_pa_tactivate_us = peer_pa_tactivate *
8446 gran_to_us_table[peer_granularity - 1];
8447
8448 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8449 u32 new_peer_pa_tactivate;
8450
8451 new_peer_pa_tactivate = pa_tactivate_us /
8452 gran_to_us_table[peer_granularity - 1];
8453 new_peer_pa_tactivate++;
8454 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8455 new_peer_pa_tactivate);
8456 }
8457
8458 out:
8459 return ret;
8460 }
8461
ufshcd_tune_unipro_params(struct ufs_hba * hba)8462 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8463 {
8464 if (ufshcd_is_unipro_pa_params_tuning_req(hba)) {
8465 ufshcd_tune_pa_tactivate(hba);
8466 ufshcd_tune_pa_hibern8time(hba);
8467 }
8468
8469 ufshcd_vops_apply_dev_quirks(hba);
8470
8471 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8472 /* set 1ms timeout for PA_TACTIVATE */
8473 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8474
8475 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8476 ufshcd_quirk_tune_host_pa_tactivate(hba);
8477 }
8478
ufshcd_clear_dbg_ufs_stats(struct ufs_hba * hba)8479 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8480 {
8481 hba->ufs_stats.hibern8_exit_cnt = 0;
8482 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8483 hba->req_abort_count = 0;
8484 }
8485
ufshcd_device_geo_params_init(struct ufs_hba * hba)8486 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8487 {
8488 int err;
8489 u8 *desc_buf;
8490
8491 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8492 if (!desc_buf) {
8493 err = -ENOMEM;
8494 goto out;
8495 }
8496
8497 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8498 desc_buf, QUERY_DESC_MAX_SIZE);
8499 if (err) {
8500 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8501 __func__, err);
8502 goto out;
8503 }
8504
8505 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8506 hba->dev_info.max_lu_supported = 32;
8507 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8508 hba->dev_info.max_lu_supported = 8;
8509
8510 out:
8511 kfree(desc_buf);
8512 return err;
8513 }
8514
8515 struct ufs_ref_clk {
8516 unsigned long freq_hz;
8517 enum ufs_ref_clk_freq val;
8518 };
8519
8520 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8521 {19200000, REF_CLK_FREQ_19_2_MHZ},
8522 {26000000, REF_CLK_FREQ_26_MHZ},
8523 {38400000, REF_CLK_FREQ_38_4_MHZ},
8524 {52000000, REF_CLK_FREQ_52_MHZ},
8525 {0, REF_CLK_FREQ_INVAL},
8526 };
8527
8528 static enum ufs_ref_clk_freq
ufs_get_bref_clk_from_hz(unsigned long freq)8529 ufs_get_bref_clk_from_hz(unsigned long freq)
8530 {
8531 int i;
8532
8533 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8534 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8535 return ufs_ref_clk_freqs[i].val;
8536
8537 return REF_CLK_FREQ_INVAL;
8538 }
8539
ufshcd_parse_dev_ref_clk_freq(struct ufs_hba * hba,struct clk * refclk)8540 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8541 {
8542 unsigned long freq;
8543
8544 freq = clk_get_rate(refclk);
8545
8546 hba->dev_ref_clk_freq =
8547 ufs_get_bref_clk_from_hz(freq);
8548
8549 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8550 dev_err(hba->dev,
8551 "invalid ref_clk setting = %ld\n", freq);
8552 }
8553
ufshcd_set_dev_ref_clk(struct ufs_hba * hba)8554 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8555 {
8556 int err;
8557 u32 ref_clk;
8558 u32 freq = hba->dev_ref_clk_freq;
8559
8560 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8561 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8562
8563 if (err) {
8564 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8565 err);
8566 goto out;
8567 }
8568
8569 if (ref_clk == freq)
8570 goto out; /* nothing to update */
8571
8572 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8573 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8574
8575 if (err) {
8576 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8577 ufs_ref_clk_freqs[freq].freq_hz);
8578 goto out;
8579 }
8580
8581 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8582 ufs_ref_clk_freqs[freq].freq_hz);
8583
8584 out:
8585 return err;
8586 }
8587
ufshcd_device_params_init(struct ufs_hba * hba)8588 static int ufshcd_device_params_init(struct ufs_hba *hba)
8589 {
8590 bool flag;
8591 int ret;
8592
8593 /* Init UFS geometry descriptor related parameters */
8594 ret = ufshcd_device_geo_params_init(hba);
8595 if (ret)
8596 goto out;
8597
8598 /* Check and apply UFS device quirks */
8599 ret = ufs_get_device_desc(hba);
8600 if (ret) {
8601 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8602 __func__, ret);
8603 goto out;
8604 }
8605
8606 ufshcd_get_ref_clk_gating_wait(hba);
8607
8608 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8609 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8610 hba->dev_info.f_power_on_wp_en = flag;
8611
8612 /* Probe maximum power mode co-supported by both UFS host and device */
8613 if (ufshcd_get_max_pwr_mode(hba))
8614 dev_err(hba->dev,
8615 "%s: Failed getting max supported power mode\n",
8616 __func__);
8617 out:
8618 return ret;
8619 }
8620
ufshcd_set_timestamp_attr(struct ufs_hba * hba)8621 static void ufshcd_set_timestamp_attr(struct ufs_hba *hba)
8622 {
8623 int err;
8624 struct ufs_query_req *request = NULL;
8625 struct ufs_query_res *response = NULL;
8626 struct ufs_dev_info *dev_info = &hba->dev_info;
8627 struct utp_upiu_query_v4_0 *upiu_data;
8628
8629 if (dev_info->wspecversion < 0x400)
8630 return;
8631
8632 ufshcd_hold(hba);
8633
8634 mutex_lock(&hba->dev_cmd.lock);
8635
8636 ufshcd_init_query(hba, &request, &response,
8637 UPIU_QUERY_OPCODE_WRITE_ATTR,
8638 QUERY_ATTR_IDN_TIMESTAMP, 0, 0);
8639
8640 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
8641
8642 upiu_data = (struct utp_upiu_query_v4_0 *)&request->upiu_req;
8643
8644 put_unaligned_be64(ktime_get_real_ns(), &upiu_data->osf3);
8645
8646 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
8647
8648 if (err)
8649 dev_err(hba->dev, "%s: failed to set timestamp %d\n",
8650 __func__, err);
8651
8652 mutex_unlock(&hba->dev_cmd.lock);
8653 ufshcd_release(hba);
8654 }
8655
8656 /**
8657 * ufshcd_add_lus - probe and add UFS logical units
8658 * @hba: per-adapter instance
8659 *
8660 * Return: 0 upon success; < 0 upon failure.
8661 */
ufshcd_add_lus(struct ufs_hba * hba)8662 static int ufshcd_add_lus(struct ufs_hba *hba)
8663 {
8664 int ret;
8665
8666 /* Add required well known logical units to scsi mid layer */
8667 ret = ufshcd_scsi_add_wlus(hba);
8668 if (ret)
8669 goto out;
8670
8671 /* Initialize devfreq after UFS device is detected */
8672 if (ufshcd_is_clkscaling_supported(hba)) {
8673 memcpy(&hba->clk_scaling.saved_pwr_info,
8674 &hba->pwr_info,
8675 sizeof(struct ufs_pa_layer_attr));
8676 hba->clk_scaling.is_allowed = true;
8677
8678 ret = ufshcd_devfreq_init(hba);
8679 if (ret)
8680 goto out;
8681
8682 hba->clk_scaling.is_enabled = true;
8683 ufshcd_init_clk_scaling_sysfs(hba);
8684 }
8685
8686 /*
8687 * The RTC update code accesses the hba->ufs_device_wlun->sdev_gendev
8688 * pointer and hence must only be started after the WLUN pointer has
8689 * been initialized by ufshcd_scsi_add_wlus().
8690 */
8691 schedule_delayed_work(&hba->ufs_rtc_update_work,
8692 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
8693
8694 ufs_bsg_probe(hba);
8695 scsi_scan_host(hba->host);
8696
8697 out:
8698 return ret;
8699 }
8700
8701 /* SDB - Single Doorbell */
ufshcd_release_sdb_queue(struct ufs_hba * hba,int nutrs)8702 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8703 {
8704 size_t ucdl_size, utrdl_size;
8705
8706 ucdl_size = ufshcd_get_ucd_size(hba) * nutrs;
8707 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8708 hba->ucdl_dma_addr);
8709
8710 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8711 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8712 hba->utrdl_dma_addr);
8713
8714 devm_kfree(hba->dev, hba->lrb);
8715 }
8716
ufshcd_alloc_mcq(struct ufs_hba * hba)8717 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8718 {
8719 int ret;
8720 int old_nutrs = hba->nutrs;
8721
8722 ret = ufshcd_mcq_decide_queue_depth(hba);
8723 if (ret < 0)
8724 return ret;
8725
8726 hba->nutrs = ret;
8727 ret = ufshcd_mcq_init(hba);
8728 if (ret)
8729 goto err;
8730
8731 /*
8732 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8733 * Number of supported tags in MCQ mode may be larger than SDB mode.
8734 */
8735 if (hba->nutrs != old_nutrs) {
8736 ufshcd_release_sdb_queue(hba, old_nutrs);
8737 ret = ufshcd_memory_alloc(hba);
8738 if (ret)
8739 goto err;
8740 ufshcd_host_memory_configure(hba);
8741 }
8742
8743 ret = ufshcd_mcq_memory_alloc(hba);
8744 if (ret)
8745 goto err;
8746
8747 return 0;
8748 err:
8749 hba->nutrs = old_nutrs;
8750 return ret;
8751 }
8752
ufshcd_config_mcq(struct ufs_hba * hba)8753 static void ufshcd_config_mcq(struct ufs_hba *hba)
8754 {
8755 int ret;
8756 u32 intrs;
8757
8758 ret = ufshcd_mcq_vops_config_esi(hba);
8759 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8760
8761 intrs = UFSHCD_ENABLE_MCQ_INTRS;
8762 if (hba->quirks & UFSHCD_QUIRK_MCQ_BROKEN_INTR)
8763 intrs &= ~MCQ_CQ_EVENT_STATUS;
8764 ufshcd_enable_intr(hba, intrs);
8765 ufshcd_mcq_make_queues_operational(hba);
8766 ufshcd_mcq_config_mac(hba, hba->nutrs);
8767
8768 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8769 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8770
8771 /* Select MCQ mode */
8772 ufshcd_writel(hba, ufshcd_readl(hba, REG_UFS_MEM_CFG) | 0x1,
8773 REG_UFS_MEM_CFG);
8774 hba->mcq_enabled = true;
8775
8776 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8777 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8778 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8779 hba->nutrs);
8780 }
8781
ufshcd_device_init(struct ufs_hba * hba,bool init_dev_params)8782 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8783 {
8784 int ret;
8785 struct Scsi_Host *host = hba->host;
8786
8787 hba->ufshcd_state = UFSHCD_STATE_RESET;
8788
8789 ret = ufshcd_link_startup(hba);
8790 if (ret)
8791 return ret;
8792
8793 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8794 return ret;
8795
8796 /* Debug counters initialization */
8797 ufshcd_clear_dbg_ufs_stats(hba);
8798
8799 /* UniPro link is active now */
8800 ufshcd_set_link_active(hba);
8801
8802 /* Reconfigure MCQ upon reset */
8803 if (is_mcq_enabled(hba) && !init_dev_params)
8804 ufshcd_config_mcq(hba);
8805
8806 /* Verify device initialization by sending NOP OUT UPIU */
8807 ret = ufshcd_verify_dev_init(hba);
8808 if (ret)
8809 return ret;
8810
8811 /* Initiate UFS initialization, and waiting until completion */
8812 ret = ufshcd_complete_dev_init(hba);
8813 if (ret)
8814 return ret;
8815
8816 /*
8817 * Initialize UFS device parameters used by driver, these
8818 * parameters are associated with UFS descriptors.
8819 */
8820 if (init_dev_params) {
8821 ret = ufshcd_device_params_init(hba);
8822 if (ret)
8823 return ret;
8824 if (is_mcq_supported(hba) && !hba->scsi_host_added) {
8825 ret = ufshcd_alloc_mcq(hba);
8826 if (!ret) {
8827 ufshcd_config_mcq(hba);
8828 } else {
8829 /* Continue with SDB mode */
8830 use_mcq_mode = false;
8831 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
8832 ret);
8833 }
8834 ret = scsi_add_host(host, hba->dev);
8835 if (ret) {
8836 dev_err(hba->dev, "scsi_add_host failed\n");
8837 return ret;
8838 }
8839 hba->scsi_host_added = true;
8840 } else if (is_mcq_supported(hba)) {
8841 /* UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH is set */
8842 ufshcd_config_mcq(hba);
8843 }
8844 }
8845
8846 ufshcd_tune_unipro_params(hba);
8847
8848 /* UFS device is also active now */
8849 ufshcd_set_ufs_dev_active(hba);
8850 ufshcd_force_reset_auto_bkops(hba);
8851
8852 ufshcd_set_timestamp_attr(hba);
8853
8854 /* Gear up to HS gear if supported */
8855 if (hba->max_pwr_info.is_valid) {
8856 /*
8857 * Set the right value to bRefClkFreq before attempting to
8858 * switch to HS gears.
8859 */
8860 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8861 ufshcd_set_dev_ref_clk(hba);
8862 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8863 if (ret) {
8864 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8865 __func__, ret);
8866 return ret;
8867 }
8868 }
8869
8870 return 0;
8871 }
8872
8873 /**
8874 * ufshcd_probe_hba - probe hba to detect device and initialize it
8875 * @hba: per-adapter instance
8876 * @init_dev_params: whether or not to call ufshcd_device_params_init().
8877 *
8878 * Execute link-startup and verify device initialization
8879 *
8880 * Return: 0 upon success; < 0 upon failure.
8881 */
ufshcd_probe_hba(struct ufs_hba * hba,bool init_dev_params)8882 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
8883 {
8884 ktime_t start = ktime_get();
8885 unsigned long flags;
8886 int ret;
8887
8888 ret = ufshcd_device_init(hba, init_dev_params);
8889 if (ret)
8890 goto out;
8891
8892 if (!hba->pm_op_in_progress &&
8893 (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH)) {
8894 /* Reset the device and controller before doing reinit */
8895 ufshcd_device_reset(hba);
8896 ufs_put_device_desc(hba);
8897 ufshcd_hba_stop(hba);
8898 ret = ufshcd_hba_enable(hba);
8899 if (ret) {
8900 dev_err(hba->dev, "Host controller enable failed\n");
8901 ufshcd_print_evt_hist(hba);
8902 ufshcd_print_host_state(hba);
8903 goto out;
8904 }
8905
8906 /* Reinit the device */
8907 ret = ufshcd_device_init(hba, init_dev_params);
8908 if (ret)
8909 goto out;
8910 }
8911
8912 ufshcd_print_pwr_info(hba);
8913
8914 /*
8915 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
8916 * and for removable UFS card as well, hence always set the parameter.
8917 * Note: Error handler may issue the device reset hence resetting
8918 * bActiveICCLevel as well so it is always safe to set this here.
8919 */
8920 ufshcd_set_active_icc_lvl(hba);
8921
8922 /* Enable UFS Write Booster if supported */
8923 ufshcd_configure_wb(hba);
8924
8925 if (hba->ee_usr_mask)
8926 ufshcd_write_ee_control(hba);
8927 /* Enable Auto-Hibernate if configured */
8928 ufshcd_auto_hibern8_enable(hba);
8929
8930 out:
8931 spin_lock_irqsave(hba->host->host_lock, flags);
8932 if (ret)
8933 hba->ufshcd_state = UFSHCD_STATE_ERROR;
8934 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
8935 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
8936 spin_unlock_irqrestore(hba->host->host_lock, flags);
8937
8938 trace_ufshcd_init(dev_name(hba->dev), ret,
8939 ktime_to_us(ktime_sub(ktime_get(), start)),
8940 hba->curr_dev_pwr_mode, hba->uic_link_state);
8941 return ret;
8942 }
8943
8944 /**
8945 * ufshcd_async_scan - asynchronous execution for probing hba
8946 * @data: data pointer to pass to this function
8947 * @cookie: cookie data
8948 */
ufshcd_async_scan(void * data,async_cookie_t cookie)8949 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
8950 {
8951 struct ufs_hba *hba = (struct ufs_hba *)data;
8952 int ret;
8953
8954 down(&hba->host_sem);
8955 /* Initialize hba, detect and initialize UFS device */
8956 ret = ufshcd_probe_hba(hba, true);
8957 up(&hba->host_sem);
8958 if (ret)
8959 goto out;
8960
8961 /* Probe and add UFS logical units */
8962 ret = ufshcd_add_lus(hba);
8963
8964 out:
8965 pm_runtime_put_sync(hba->dev);
8966
8967 if (ret)
8968 dev_err(hba->dev, "%s failed: %d\n", __func__, ret);
8969 }
8970
ufshcd_eh_timed_out(struct scsi_cmnd * scmd)8971 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
8972 {
8973 struct ufs_hba *hba = shost_priv(scmd->device->host);
8974
8975 if (!hba->system_suspending) {
8976 /* Activate the error handler in the SCSI core. */
8977 return SCSI_EH_NOT_HANDLED;
8978 }
8979
8980 /*
8981 * If we get here we know that no TMFs are outstanding and also that
8982 * the only pending command is a START STOP UNIT command. Handle the
8983 * timeout of that command directly to prevent a deadlock between
8984 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
8985 */
8986 ufshcd_link_recovery(hba);
8987 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
8988 __func__, hba->outstanding_tasks);
8989
8990 return scsi_host_busy(hba->host) ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
8991 }
8992
8993 static const struct attribute_group *ufshcd_driver_groups[] = {
8994 &ufs_sysfs_unit_descriptor_group,
8995 &ufs_sysfs_lun_attributes_group,
8996 NULL,
8997 };
8998
8999 static struct ufs_hba_variant_params ufs_hba_vps = {
9000 .hba_enable_delay_us = 1000,
9001 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
9002 .devfreq_profile.polling_ms = 100,
9003 .devfreq_profile.target = ufshcd_devfreq_target,
9004 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
9005 .ondemand_data.upthreshold = 70,
9006 .ondemand_data.downdifferential = 5,
9007 };
9008
9009 static const struct scsi_host_template ufshcd_driver_template = {
9010 .module = THIS_MODULE,
9011 .name = UFSHCD,
9012 .proc_name = UFSHCD,
9013 .map_queues = ufshcd_map_queues,
9014 .queuecommand = ufshcd_queuecommand,
9015 .mq_poll = ufshcd_poll,
9016 .slave_alloc = ufshcd_slave_alloc,
9017 .slave_configure = ufshcd_slave_configure,
9018 .slave_destroy = ufshcd_slave_destroy,
9019 .change_queue_depth = ufshcd_change_queue_depth,
9020 .eh_abort_handler = ufshcd_abort,
9021 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
9022 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
9023 .eh_timed_out = ufshcd_eh_timed_out,
9024 .this_id = -1,
9025 .sg_tablesize = SG_ALL,
9026 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
9027 .can_queue = UFSHCD_CAN_QUEUE,
9028 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
9029 .max_sectors = SZ_1M / SECTOR_SIZE,
9030 .max_host_blocked = 1,
9031 .track_queue_depth = 1,
9032 .skip_settle_delay = 1,
9033 .sdev_groups = ufshcd_driver_groups,
9034 .rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS,
9035 };
9036
ufshcd_config_vreg_load(struct device * dev,struct ufs_vreg * vreg,int ua)9037 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
9038 int ua)
9039 {
9040 int ret;
9041
9042 if (!vreg)
9043 return 0;
9044
9045 /*
9046 * "set_load" operation shall be required on those regulators
9047 * which specifically configured current limitation. Otherwise
9048 * zero max_uA may cause unexpected behavior when regulator is
9049 * enabled or set as high power mode.
9050 */
9051 if (!vreg->max_uA)
9052 return 0;
9053
9054 ret = regulator_set_load(vreg->reg, ua);
9055 if (ret < 0) {
9056 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
9057 __func__, vreg->name, ua, ret);
9058 }
9059
9060 return ret;
9061 }
9062
ufshcd_config_vreg_lpm(struct ufs_hba * hba,struct ufs_vreg * vreg)9063 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
9064 struct ufs_vreg *vreg)
9065 {
9066 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
9067 }
9068
ufshcd_config_vreg_hpm(struct ufs_hba * hba,struct ufs_vreg * vreg)9069 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
9070 struct ufs_vreg *vreg)
9071 {
9072 if (!vreg)
9073 return 0;
9074
9075 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
9076 }
9077
ufshcd_config_vreg(struct device * dev,struct ufs_vreg * vreg,bool on)9078 static int ufshcd_config_vreg(struct device *dev,
9079 struct ufs_vreg *vreg, bool on)
9080 {
9081 if (regulator_count_voltages(vreg->reg) <= 0)
9082 return 0;
9083
9084 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
9085 }
9086
ufshcd_enable_vreg(struct device * dev,struct ufs_vreg * vreg)9087 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
9088 {
9089 int ret = 0;
9090
9091 if (!vreg || vreg->enabled)
9092 goto out;
9093
9094 ret = ufshcd_config_vreg(dev, vreg, true);
9095 if (!ret)
9096 ret = regulator_enable(vreg->reg);
9097
9098 if (!ret)
9099 vreg->enabled = true;
9100 else
9101 dev_err(dev, "%s: %s enable failed, err=%d\n",
9102 __func__, vreg->name, ret);
9103 out:
9104 return ret;
9105 }
9106
ufshcd_disable_vreg(struct device * dev,struct ufs_vreg * vreg)9107 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
9108 {
9109 int ret = 0;
9110
9111 if (!vreg || !vreg->enabled || vreg->always_on)
9112 goto out;
9113
9114 ret = regulator_disable(vreg->reg);
9115
9116 if (!ret) {
9117 /* ignore errors on applying disable config */
9118 ufshcd_config_vreg(dev, vreg, false);
9119 vreg->enabled = false;
9120 } else {
9121 dev_err(dev, "%s: %s disable failed, err=%d\n",
9122 __func__, vreg->name, ret);
9123 }
9124 out:
9125 return ret;
9126 }
9127
ufshcd_setup_vreg(struct ufs_hba * hba,bool on)9128 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
9129 {
9130 int ret = 0;
9131 struct device *dev = hba->dev;
9132 struct ufs_vreg_info *info = &hba->vreg_info;
9133
9134 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
9135 if (ret)
9136 goto out;
9137
9138 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
9139 if (ret)
9140 goto out;
9141
9142 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
9143
9144 out:
9145 if (ret) {
9146 ufshcd_toggle_vreg(dev, info->vccq2, false);
9147 ufshcd_toggle_vreg(dev, info->vccq, false);
9148 ufshcd_toggle_vreg(dev, info->vcc, false);
9149 }
9150 return ret;
9151 }
9152
ufshcd_setup_hba_vreg(struct ufs_hba * hba,bool on)9153 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
9154 {
9155 struct ufs_vreg_info *info = &hba->vreg_info;
9156
9157 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9158 }
9159
ufshcd_get_vreg(struct device * dev,struct ufs_vreg * vreg)9160 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9161 {
9162 int ret = 0;
9163
9164 if (!vreg)
9165 goto out;
9166
9167 vreg->reg = devm_regulator_get(dev, vreg->name);
9168 if (IS_ERR(vreg->reg)) {
9169 ret = PTR_ERR(vreg->reg);
9170 dev_err(dev, "%s: %s get failed, err=%d\n",
9171 __func__, vreg->name, ret);
9172 }
9173 out:
9174 return ret;
9175 }
9176 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9177
ufshcd_init_vreg(struct ufs_hba * hba)9178 static int ufshcd_init_vreg(struct ufs_hba *hba)
9179 {
9180 int ret = 0;
9181 struct device *dev = hba->dev;
9182 struct ufs_vreg_info *info = &hba->vreg_info;
9183
9184 ret = ufshcd_get_vreg(dev, info->vcc);
9185 if (ret)
9186 goto out;
9187
9188 ret = ufshcd_get_vreg(dev, info->vccq);
9189 if (!ret)
9190 ret = ufshcd_get_vreg(dev, info->vccq2);
9191 out:
9192 return ret;
9193 }
9194
ufshcd_init_hba_vreg(struct ufs_hba * hba)9195 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9196 {
9197 struct ufs_vreg_info *info = &hba->vreg_info;
9198
9199 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9200 }
9201
ufshcd_setup_clocks(struct ufs_hba * hba,bool on)9202 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9203 {
9204 int ret = 0;
9205 struct ufs_clk_info *clki;
9206 struct list_head *head = &hba->clk_list_head;
9207 unsigned long flags;
9208 ktime_t start = ktime_get();
9209 bool clk_state_changed = false;
9210
9211 if (list_empty(head))
9212 goto out;
9213
9214 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9215 if (ret)
9216 return ret;
9217
9218 list_for_each_entry(clki, head, list) {
9219 if (!IS_ERR_OR_NULL(clki->clk)) {
9220 /*
9221 * Don't disable clocks which are needed
9222 * to keep the link active.
9223 */
9224 if (ufshcd_is_link_active(hba) &&
9225 clki->keep_link_active)
9226 continue;
9227
9228 clk_state_changed = on ^ clki->enabled;
9229 if (on && !clki->enabled) {
9230 ret = clk_prepare_enable(clki->clk);
9231 if (ret) {
9232 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9233 __func__, clki->name, ret);
9234 goto out;
9235 }
9236 } else if (!on && clki->enabled) {
9237 clk_disable_unprepare(clki->clk);
9238 }
9239 clki->enabled = on;
9240 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9241 clki->name, on ? "en" : "dis");
9242 }
9243 }
9244
9245 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9246 if (ret)
9247 return ret;
9248
9249 out:
9250 if (ret) {
9251 list_for_each_entry(clki, head, list) {
9252 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9253 clk_disable_unprepare(clki->clk);
9254 }
9255 } else if (!ret && on) {
9256 spin_lock_irqsave(hba->host->host_lock, flags);
9257 hba->clk_gating.state = CLKS_ON;
9258 trace_ufshcd_clk_gating(dev_name(hba->dev),
9259 hba->clk_gating.state);
9260 spin_unlock_irqrestore(hba->host->host_lock, flags);
9261 }
9262
9263 if (clk_state_changed)
9264 trace_ufshcd_profile_clk_gating(dev_name(hba->dev),
9265 (on ? "on" : "off"),
9266 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9267 return ret;
9268 }
9269
ufshcd_parse_ref_clk_property(struct ufs_hba * hba)9270 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9271 {
9272 u32 freq;
9273 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9274
9275 if (ret) {
9276 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9277 return REF_CLK_FREQ_INVAL;
9278 }
9279
9280 return ufs_get_bref_clk_from_hz(freq);
9281 }
9282
ufshcd_init_clocks(struct ufs_hba * hba)9283 static int ufshcd_init_clocks(struct ufs_hba *hba)
9284 {
9285 int ret = 0;
9286 struct ufs_clk_info *clki;
9287 struct device *dev = hba->dev;
9288 struct list_head *head = &hba->clk_list_head;
9289
9290 if (list_empty(head))
9291 goto out;
9292
9293 list_for_each_entry(clki, head, list) {
9294 if (!clki->name)
9295 continue;
9296
9297 clki->clk = devm_clk_get(dev, clki->name);
9298 if (IS_ERR(clki->clk)) {
9299 ret = PTR_ERR(clki->clk);
9300 dev_err(dev, "%s: %s clk get failed, %d\n",
9301 __func__, clki->name, ret);
9302 goto out;
9303 }
9304
9305 /*
9306 * Parse device ref clk freq as per device tree "ref_clk".
9307 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9308 * in ufshcd_alloc_host().
9309 */
9310 if (!strcmp(clki->name, "ref_clk"))
9311 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9312
9313 if (clki->max_freq) {
9314 ret = clk_set_rate(clki->clk, clki->max_freq);
9315 if (ret) {
9316 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9317 __func__, clki->name,
9318 clki->max_freq, ret);
9319 goto out;
9320 }
9321 clki->curr_freq = clki->max_freq;
9322 }
9323 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9324 clki->name, clk_get_rate(clki->clk));
9325 }
9326 out:
9327 return ret;
9328 }
9329
ufshcd_variant_hba_init(struct ufs_hba * hba)9330 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9331 {
9332 int err = 0;
9333
9334 if (!hba->vops)
9335 goto out;
9336
9337 err = ufshcd_vops_init(hba);
9338 if (err)
9339 dev_err_probe(hba->dev, err,
9340 "%s: variant %s init failed with err %d\n",
9341 __func__, ufshcd_get_var_name(hba), err);
9342 out:
9343 return err;
9344 }
9345
ufshcd_variant_hba_exit(struct ufs_hba * hba)9346 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9347 {
9348 if (!hba->vops)
9349 return;
9350
9351 ufshcd_vops_exit(hba);
9352 }
9353
ufshcd_hba_init(struct ufs_hba * hba)9354 static int ufshcd_hba_init(struct ufs_hba *hba)
9355 {
9356 int err;
9357
9358 /*
9359 * Handle host controller power separately from the UFS device power
9360 * rails as it will help controlling the UFS host controller power
9361 * collapse easily which is different than UFS device power collapse.
9362 * Also, enable the host controller power before we go ahead with rest
9363 * of the initialization here.
9364 */
9365 err = ufshcd_init_hba_vreg(hba);
9366 if (err)
9367 goto out;
9368
9369 err = ufshcd_setup_hba_vreg(hba, true);
9370 if (err)
9371 goto out;
9372
9373 err = ufshcd_init_clocks(hba);
9374 if (err)
9375 goto out_disable_hba_vreg;
9376
9377 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9378 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9379
9380 err = ufshcd_setup_clocks(hba, true);
9381 if (err)
9382 goto out_disable_hba_vreg;
9383
9384 err = ufshcd_init_vreg(hba);
9385 if (err)
9386 goto out_disable_clks;
9387
9388 err = ufshcd_setup_vreg(hba, true);
9389 if (err)
9390 goto out_disable_clks;
9391
9392 err = ufshcd_variant_hba_init(hba);
9393 if (err)
9394 goto out_disable_vreg;
9395
9396 ufs_debugfs_hba_init(hba);
9397
9398 hba->is_powered = true;
9399 goto out;
9400
9401 out_disable_vreg:
9402 ufshcd_setup_vreg(hba, false);
9403 out_disable_clks:
9404 ufshcd_setup_clocks(hba, false);
9405 out_disable_hba_vreg:
9406 ufshcd_setup_hba_vreg(hba, false);
9407 out:
9408 return err;
9409 }
9410
ufshcd_hba_exit(struct ufs_hba * hba)9411 static void ufshcd_hba_exit(struct ufs_hba *hba)
9412 {
9413 if (hba->is_powered) {
9414 ufshcd_exit_clk_scaling(hba);
9415 ufshcd_exit_clk_gating(hba);
9416 if (hba->eh_wq)
9417 destroy_workqueue(hba->eh_wq);
9418 ufs_debugfs_hba_exit(hba);
9419 ufshcd_variant_hba_exit(hba);
9420 ufshcd_setup_vreg(hba, false);
9421 ufshcd_setup_clocks(hba, false);
9422 ufshcd_setup_hba_vreg(hba, false);
9423 hba->is_powered = false;
9424 ufs_put_device_desc(hba);
9425 }
9426 }
9427
ufshcd_execute_start_stop(struct scsi_device * sdev,enum ufs_dev_pwr_mode pwr_mode,struct scsi_sense_hdr * sshdr)9428 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9429 enum ufs_dev_pwr_mode pwr_mode,
9430 struct scsi_sense_hdr *sshdr)
9431 {
9432 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9433 const struct scsi_exec_args args = {
9434 .sshdr = sshdr,
9435 .req_flags = BLK_MQ_REQ_PM,
9436 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9437 };
9438
9439 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9440 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9441 &args);
9442 }
9443
9444 /**
9445 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9446 * power mode
9447 * @hba: per adapter instance
9448 * @pwr_mode: device power mode to set
9449 *
9450 * Return: 0 if requested power mode is set successfully;
9451 * < 0 if failed to set the requested power mode.
9452 */
ufshcd_set_dev_pwr_mode(struct ufs_hba * hba,enum ufs_dev_pwr_mode pwr_mode)9453 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9454 enum ufs_dev_pwr_mode pwr_mode)
9455 {
9456 struct scsi_sense_hdr sshdr;
9457 struct scsi_device *sdp;
9458 unsigned long flags;
9459 int ret, retries;
9460
9461 spin_lock_irqsave(hba->host->host_lock, flags);
9462 sdp = hba->ufs_device_wlun;
9463 if (sdp && scsi_device_online(sdp))
9464 ret = scsi_device_get(sdp);
9465 else
9466 ret = -ENODEV;
9467 spin_unlock_irqrestore(hba->host->host_lock, flags);
9468
9469 if (ret)
9470 return ret;
9471
9472 /*
9473 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9474 * handling, which would wait for host to be resumed. Since we know
9475 * we are functional while we are here, skip host resume in error
9476 * handling context.
9477 */
9478 hba->host->eh_noresume = 1;
9479
9480 /*
9481 * Current function would be generally called from the power management
9482 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9483 * already suspended childs.
9484 */
9485 for (retries = 3; retries > 0; --retries) {
9486 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9487 /*
9488 * scsi_execute() only returns a negative value if the request
9489 * queue is dying.
9490 */
9491 if (ret <= 0)
9492 break;
9493 }
9494 if (ret) {
9495 sdev_printk(KERN_WARNING, sdp,
9496 "START_STOP failed for power mode: %d, result %x\n",
9497 pwr_mode, ret);
9498 if (ret > 0) {
9499 if (scsi_sense_valid(&sshdr))
9500 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9501 ret = -EIO;
9502 }
9503 } else {
9504 hba->curr_dev_pwr_mode = pwr_mode;
9505 }
9506
9507 scsi_device_put(sdp);
9508 hba->host->eh_noresume = 0;
9509 return ret;
9510 }
9511
ufshcd_link_state_transition(struct ufs_hba * hba,enum uic_link_state req_link_state,bool check_for_bkops)9512 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9513 enum uic_link_state req_link_state,
9514 bool check_for_bkops)
9515 {
9516 int ret = 0;
9517
9518 if (req_link_state == hba->uic_link_state)
9519 return 0;
9520
9521 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9522 ret = ufshcd_uic_hibern8_enter(hba);
9523 if (!ret) {
9524 ufshcd_set_link_hibern8(hba);
9525 } else {
9526 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9527 __func__, ret);
9528 goto out;
9529 }
9530 }
9531 /*
9532 * If autobkops is enabled, link can't be turned off because
9533 * turning off the link would also turn off the device, except in the
9534 * case of DeepSleep where the device is expected to remain powered.
9535 */
9536 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9537 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9538 /*
9539 * Let's make sure that link is in low power mode, we are doing
9540 * this currently by putting the link in Hibern8. Otherway to
9541 * put the link in low power mode is to send the DME end point
9542 * to device and then send the DME reset command to local
9543 * unipro. But putting the link in hibern8 is much faster.
9544 *
9545 * Note also that putting the link in Hibern8 is a requirement
9546 * for entering DeepSleep.
9547 */
9548 ret = ufshcd_uic_hibern8_enter(hba);
9549 if (ret) {
9550 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9551 __func__, ret);
9552 goto out;
9553 }
9554 /*
9555 * Change controller state to "reset state" which
9556 * should also put the link in off/reset state
9557 */
9558 ufshcd_hba_stop(hba);
9559 /*
9560 * TODO: Check if we need any delay to make sure that
9561 * controller is reset
9562 */
9563 ufshcd_set_link_off(hba);
9564 }
9565
9566 out:
9567 return ret;
9568 }
9569
ufshcd_vreg_set_lpm(struct ufs_hba * hba)9570 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9571 {
9572 bool vcc_off = false;
9573
9574 /*
9575 * It seems some UFS devices may keep drawing more than sleep current
9576 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9577 * To avoid this situation, add 2ms delay before putting these UFS
9578 * rails in LPM mode.
9579 */
9580 if (!ufshcd_is_link_active(hba) &&
9581 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9582 usleep_range(2000, 2100);
9583
9584 /*
9585 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9586 * power.
9587 *
9588 * If UFS device and link is in OFF state, all power supplies (VCC,
9589 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9590 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9591 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9592 *
9593 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9594 * in low power state which would save some power.
9595 *
9596 * If Write Booster is enabled and the device needs to flush the WB
9597 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9598 */
9599 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9600 !hba->dev_info.is_lu_power_on_wp) {
9601 ufshcd_setup_vreg(hba, false);
9602 vcc_off = true;
9603 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9604 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9605 vcc_off = true;
9606 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9607 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9608 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9609 }
9610 }
9611
9612 /*
9613 * Some UFS devices require delay after VCC power rail is turned-off.
9614 */
9615 if (vcc_off && hba->vreg_info.vcc &&
9616 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9617 usleep_range(5000, 5100);
9618 }
9619
9620 #ifdef CONFIG_PM
ufshcd_vreg_set_hpm(struct ufs_hba * hba)9621 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9622 {
9623 int ret = 0;
9624
9625 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9626 !hba->dev_info.is_lu_power_on_wp) {
9627 ret = ufshcd_setup_vreg(hba, true);
9628 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9629 if (!ufshcd_is_link_active(hba)) {
9630 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9631 if (ret)
9632 goto vcc_disable;
9633 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9634 if (ret)
9635 goto vccq_lpm;
9636 }
9637 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9638 }
9639 goto out;
9640
9641 vccq_lpm:
9642 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9643 vcc_disable:
9644 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9645 out:
9646 return ret;
9647 }
9648 #endif /* CONFIG_PM */
9649
ufshcd_hba_vreg_set_lpm(struct ufs_hba * hba)9650 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9651 {
9652 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9653 ufshcd_setup_hba_vreg(hba, false);
9654 }
9655
ufshcd_hba_vreg_set_hpm(struct ufs_hba * hba)9656 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9657 {
9658 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9659 ufshcd_setup_hba_vreg(hba, true);
9660 }
9661
__ufshcd_wl_suspend(struct ufs_hba * hba,enum ufs_pm_op pm_op)9662 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9663 {
9664 int ret = 0;
9665 bool check_for_bkops;
9666 enum ufs_pm_level pm_lvl;
9667 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9668 enum uic_link_state req_link_state;
9669
9670 hba->pm_op_in_progress = true;
9671 if (pm_op != UFS_SHUTDOWN_PM) {
9672 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9673 hba->rpm_lvl : hba->spm_lvl;
9674 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9675 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9676 } else {
9677 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9678 req_link_state = UIC_LINK_OFF_STATE;
9679 }
9680
9681 /*
9682 * If we can't transition into any of the low power modes
9683 * just gate the clocks.
9684 */
9685 ufshcd_hold(hba);
9686 hba->clk_gating.is_suspended = true;
9687
9688 if (ufshcd_is_clkscaling_supported(hba))
9689 ufshcd_clk_scaling_suspend(hba, true);
9690
9691 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9692 req_link_state == UIC_LINK_ACTIVE_STATE) {
9693 goto vops_suspend;
9694 }
9695
9696 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9697 (req_link_state == hba->uic_link_state))
9698 goto enable_scaling;
9699
9700 /* UFS device & link must be active before we enter in this function */
9701 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9702 /* Wait err handler finish or trigger err recovery */
9703 if (!ufshcd_eh_in_progress(hba))
9704 ufshcd_force_error_recovery(hba);
9705 ret = -EBUSY;
9706 goto enable_scaling;
9707 }
9708
9709 if (pm_op == UFS_RUNTIME_PM) {
9710 if (ufshcd_can_autobkops_during_suspend(hba)) {
9711 /*
9712 * The device is idle with no requests in the queue,
9713 * allow background operations if bkops status shows
9714 * that performance might be impacted.
9715 */
9716 ret = ufshcd_urgent_bkops(hba);
9717 if (ret) {
9718 /*
9719 * If return err in suspend flow, IO will hang.
9720 * Trigger error handler and break suspend for
9721 * error recovery.
9722 */
9723 ufshcd_force_error_recovery(hba);
9724 ret = -EBUSY;
9725 goto enable_scaling;
9726 }
9727 } else {
9728 /* make sure that auto bkops is disabled */
9729 ufshcd_disable_auto_bkops(hba);
9730 }
9731 /*
9732 * If device needs to do BKOP or WB buffer flush during
9733 * Hibern8, keep device power mode as "active power mode"
9734 * and VCC supply.
9735 */
9736 hba->dev_info.b_rpm_dev_flush_capable =
9737 hba->auto_bkops_enabled ||
9738 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9739 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9740 ufshcd_is_auto_hibern8_enabled(hba))) &&
9741 ufshcd_wb_need_flush(hba));
9742 }
9743
9744 flush_work(&hba->eeh_work);
9745
9746 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9747 if (ret)
9748 goto enable_scaling;
9749
9750 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9751 if (pm_op != UFS_RUNTIME_PM)
9752 /* ensure that bkops is disabled */
9753 ufshcd_disable_auto_bkops(hba);
9754
9755 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9756 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9757 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9758 /*
9759 * If return err in suspend flow, IO will hang.
9760 * Trigger error handler and break suspend for
9761 * error recovery.
9762 */
9763 ufshcd_force_error_recovery(hba);
9764 ret = -EBUSY;
9765 }
9766 if (ret)
9767 goto enable_scaling;
9768 }
9769 }
9770
9771 /*
9772 * In the case of DeepSleep, the device is expected to remain powered
9773 * with the link off, so do not check for bkops.
9774 */
9775 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9776 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9777 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9778 /*
9779 * If return err in suspend flow, IO will hang.
9780 * Trigger error handler and break suspend for
9781 * error recovery.
9782 */
9783 ufshcd_force_error_recovery(hba);
9784 ret = -EBUSY;
9785 }
9786 if (ret)
9787 goto set_dev_active;
9788
9789 vops_suspend:
9790 /*
9791 * Call vendor specific suspend callback. As these callbacks may access
9792 * vendor specific host controller register space call them before the
9793 * host clocks are ON.
9794 */
9795 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9796 if (ret)
9797 goto set_link_active;
9798
9799 cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
9800 goto out;
9801
9802 set_link_active:
9803 /*
9804 * Device hardware reset is required to exit DeepSleep. Also, for
9805 * DeepSleep, the link is off so host reset and restore will be done
9806 * further below.
9807 */
9808 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9809 ufshcd_device_reset(hba);
9810 WARN_ON(!ufshcd_is_link_off(hba));
9811 }
9812 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9813 ufshcd_set_link_active(hba);
9814 else if (ufshcd_is_link_off(hba))
9815 ufshcd_host_reset_and_restore(hba);
9816 set_dev_active:
9817 /* Can also get here needing to exit DeepSleep */
9818 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9819 ufshcd_device_reset(hba);
9820 ufshcd_host_reset_and_restore(hba);
9821 }
9822 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9823 ufshcd_disable_auto_bkops(hba);
9824 enable_scaling:
9825 if (ufshcd_is_clkscaling_supported(hba))
9826 ufshcd_clk_scaling_suspend(hba, false);
9827
9828 hba->dev_info.b_rpm_dev_flush_capable = false;
9829 out:
9830 if (hba->dev_info.b_rpm_dev_flush_capable) {
9831 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9832 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9833 }
9834
9835 if (ret) {
9836 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
9837 hba->clk_gating.is_suspended = false;
9838 ufshcd_release(hba);
9839 }
9840 hba->pm_op_in_progress = false;
9841 return ret;
9842 }
9843
9844 #ifdef CONFIG_PM
__ufshcd_wl_resume(struct ufs_hba * hba,enum ufs_pm_op pm_op)9845 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9846 {
9847 int ret;
9848 enum uic_link_state old_link_state = hba->uic_link_state;
9849
9850 hba->pm_op_in_progress = true;
9851
9852 /*
9853 * Call vendor specific resume callback. As these callbacks may access
9854 * vendor specific host controller register space call them when the
9855 * host clocks are ON.
9856 */
9857 ret = ufshcd_vops_resume(hba, pm_op);
9858 if (ret)
9859 goto out;
9860
9861 /* For DeepSleep, the only supported option is to have the link off */
9862 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
9863
9864 if (ufshcd_is_link_hibern8(hba)) {
9865 ret = ufshcd_uic_hibern8_exit(hba);
9866 if (!ret) {
9867 ufshcd_set_link_active(hba);
9868 } else {
9869 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
9870 __func__, ret);
9871 goto vendor_suspend;
9872 }
9873 } else if (ufshcd_is_link_off(hba)) {
9874 /*
9875 * A full initialization of the host and the device is
9876 * required since the link was put to off during suspend.
9877 * Note, in the case of DeepSleep, the device will exit
9878 * DeepSleep due to device reset.
9879 */
9880 ret = ufshcd_reset_and_restore(hba);
9881 /*
9882 * ufshcd_reset_and_restore() should have already
9883 * set the link state as active
9884 */
9885 if (ret || !ufshcd_is_link_active(hba))
9886 goto vendor_suspend;
9887 }
9888
9889 if (!ufshcd_is_ufs_dev_active(hba)) {
9890 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
9891 if (ret)
9892 goto set_old_link_state;
9893 ufshcd_set_timestamp_attr(hba);
9894 schedule_delayed_work(&hba->ufs_rtc_update_work,
9895 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
9896 }
9897
9898 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
9899 ufshcd_enable_auto_bkops(hba);
9900 else
9901 /*
9902 * If BKOPs operations are urgently needed at this moment then
9903 * keep auto-bkops enabled or else disable it.
9904 */
9905 ufshcd_urgent_bkops(hba);
9906
9907 if (hba->ee_usr_mask)
9908 ufshcd_write_ee_control(hba);
9909
9910 if (ufshcd_is_clkscaling_supported(hba))
9911 ufshcd_clk_scaling_suspend(hba, false);
9912
9913 if (hba->dev_info.b_rpm_dev_flush_capable) {
9914 hba->dev_info.b_rpm_dev_flush_capable = false;
9915 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
9916 }
9917
9918 /* Enable Auto-Hibernate if configured */
9919 ufshcd_auto_hibern8_enable(hba);
9920
9921 goto out;
9922
9923 set_old_link_state:
9924 ufshcd_link_state_transition(hba, old_link_state, 0);
9925 vendor_suspend:
9926 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9927 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9928 out:
9929 if (ret)
9930 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
9931 hba->clk_gating.is_suspended = false;
9932 ufshcd_release(hba);
9933 hba->pm_op_in_progress = false;
9934 return ret;
9935 }
9936
ufshcd_wl_runtime_suspend(struct device * dev)9937 static int ufshcd_wl_runtime_suspend(struct device *dev)
9938 {
9939 struct scsi_device *sdev = to_scsi_device(dev);
9940 struct ufs_hba *hba;
9941 int ret;
9942 ktime_t start = ktime_get();
9943
9944 hba = shost_priv(sdev->host);
9945
9946 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
9947 if (ret)
9948 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9949
9950 trace_ufshcd_wl_runtime_suspend(dev_name(dev), ret,
9951 ktime_to_us(ktime_sub(ktime_get(), start)),
9952 hba->curr_dev_pwr_mode, hba->uic_link_state);
9953
9954 return ret;
9955 }
9956
ufshcd_wl_runtime_resume(struct device * dev)9957 static int ufshcd_wl_runtime_resume(struct device *dev)
9958 {
9959 struct scsi_device *sdev = to_scsi_device(dev);
9960 struct ufs_hba *hba;
9961 int ret = 0;
9962 ktime_t start = ktime_get();
9963
9964 hba = shost_priv(sdev->host);
9965
9966 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
9967 if (ret)
9968 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9969
9970 trace_ufshcd_wl_runtime_resume(dev_name(dev), ret,
9971 ktime_to_us(ktime_sub(ktime_get(), start)),
9972 hba->curr_dev_pwr_mode, hba->uic_link_state);
9973
9974 return ret;
9975 }
9976 #endif
9977
9978 #ifdef CONFIG_PM_SLEEP
ufshcd_wl_suspend(struct device * dev)9979 static int ufshcd_wl_suspend(struct device *dev)
9980 {
9981 struct scsi_device *sdev = to_scsi_device(dev);
9982 struct ufs_hba *hba;
9983 int ret = 0;
9984 ktime_t start = ktime_get();
9985
9986 hba = shost_priv(sdev->host);
9987 down(&hba->host_sem);
9988 hba->system_suspending = true;
9989
9990 if (pm_runtime_suspended(dev))
9991 goto out;
9992
9993 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
9994 if (ret) {
9995 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
9996 up(&hba->host_sem);
9997 }
9998
9999 out:
10000 if (!ret)
10001 hba->is_sys_suspended = true;
10002 trace_ufshcd_wl_suspend(dev_name(dev), ret,
10003 ktime_to_us(ktime_sub(ktime_get(), start)),
10004 hba->curr_dev_pwr_mode, hba->uic_link_state);
10005
10006 return ret;
10007 }
10008
ufshcd_wl_resume(struct device * dev)10009 static int ufshcd_wl_resume(struct device *dev)
10010 {
10011 struct scsi_device *sdev = to_scsi_device(dev);
10012 struct ufs_hba *hba;
10013 int ret = 0;
10014 ktime_t start = ktime_get();
10015
10016 hba = shost_priv(sdev->host);
10017
10018 if (pm_runtime_suspended(dev))
10019 goto out;
10020
10021 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
10022 if (ret)
10023 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10024 out:
10025 trace_ufshcd_wl_resume(dev_name(dev), ret,
10026 ktime_to_us(ktime_sub(ktime_get(), start)),
10027 hba->curr_dev_pwr_mode, hba->uic_link_state);
10028 if (!ret)
10029 hba->is_sys_suspended = false;
10030 hba->system_suspending = false;
10031 up(&hba->host_sem);
10032 return ret;
10033 }
10034 #endif
10035
10036 /**
10037 * ufshcd_suspend - helper function for suspend operations
10038 * @hba: per adapter instance
10039 *
10040 * This function will put disable irqs, turn off clocks
10041 * and set vreg and hba-vreg in lpm mode.
10042 *
10043 * Return: 0 upon success; < 0 upon failure.
10044 */
ufshcd_suspend(struct ufs_hba * hba)10045 static int ufshcd_suspend(struct ufs_hba *hba)
10046 {
10047 int ret;
10048
10049 if (!hba->is_powered)
10050 return 0;
10051 /*
10052 * Disable the host irq as host controller as there won't be any
10053 * host controller transaction expected till resume.
10054 */
10055 ufshcd_disable_irq(hba);
10056 ret = ufshcd_setup_clocks(hba, false);
10057 if (ret) {
10058 ufshcd_enable_irq(hba);
10059 return ret;
10060 }
10061 if (ufshcd_is_clkgating_allowed(hba)) {
10062 hba->clk_gating.state = CLKS_OFF;
10063 trace_ufshcd_clk_gating(dev_name(hba->dev),
10064 hba->clk_gating.state);
10065 }
10066
10067 ufshcd_vreg_set_lpm(hba);
10068 /* Put the host controller in low power mode if possible */
10069 ufshcd_hba_vreg_set_lpm(hba);
10070 return ret;
10071 }
10072
10073 #ifdef CONFIG_PM
10074 /**
10075 * ufshcd_resume - helper function for resume operations
10076 * @hba: per adapter instance
10077 *
10078 * This function basically turns on the regulators, clocks and
10079 * irqs of the hba.
10080 *
10081 * Return: 0 for success and non-zero for failure.
10082 */
ufshcd_resume(struct ufs_hba * hba)10083 static int ufshcd_resume(struct ufs_hba *hba)
10084 {
10085 int ret;
10086
10087 if (!hba->is_powered)
10088 return 0;
10089
10090 ufshcd_hba_vreg_set_hpm(hba);
10091 ret = ufshcd_vreg_set_hpm(hba);
10092 if (ret)
10093 goto out;
10094
10095 /* Make sure clocks are enabled before accessing controller */
10096 ret = ufshcd_setup_clocks(hba, true);
10097 if (ret)
10098 goto disable_vreg;
10099
10100 /* enable the host irq as host controller would be active soon */
10101 ufshcd_enable_irq(hba);
10102
10103 goto out;
10104
10105 disable_vreg:
10106 ufshcd_vreg_set_lpm(hba);
10107 out:
10108 if (ret)
10109 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
10110 return ret;
10111 }
10112 #endif /* CONFIG_PM */
10113
10114 #ifdef CONFIG_PM_SLEEP
10115 /**
10116 * ufshcd_system_suspend - system suspend callback
10117 * @dev: Device associated with the UFS controller.
10118 *
10119 * Executed before putting the system into a sleep state in which the contents
10120 * of main memory are preserved.
10121 *
10122 * Return: 0 for success and non-zero for failure.
10123 */
ufshcd_system_suspend(struct device * dev)10124 int ufshcd_system_suspend(struct device *dev)
10125 {
10126 struct ufs_hba *hba = dev_get_drvdata(dev);
10127 int ret = 0;
10128 ktime_t start = ktime_get();
10129
10130 if (pm_runtime_suspended(hba->dev))
10131 goto out;
10132
10133 ret = ufshcd_suspend(hba);
10134 out:
10135 trace_ufshcd_system_suspend(dev_name(hba->dev), ret,
10136 ktime_to_us(ktime_sub(ktime_get(), start)),
10137 hba->curr_dev_pwr_mode, hba->uic_link_state);
10138 return ret;
10139 }
10140 EXPORT_SYMBOL(ufshcd_system_suspend);
10141
10142 /**
10143 * ufshcd_system_resume - system resume callback
10144 * @dev: Device associated with the UFS controller.
10145 *
10146 * Executed after waking the system up from a sleep state in which the contents
10147 * of main memory were preserved.
10148 *
10149 * Return: 0 for success and non-zero for failure.
10150 */
ufshcd_system_resume(struct device * dev)10151 int ufshcd_system_resume(struct device *dev)
10152 {
10153 struct ufs_hba *hba = dev_get_drvdata(dev);
10154 ktime_t start = ktime_get();
10155 int ret = 0;
10156
10157 if (pm_runtime_suspended(hba->dev))
10158 goto out;
10159
10160 ret = ufshcd_resume(hba);
10161
10162 out:
10163 trace_ufshcd_system_resume(dev_name(hba->dev), ret,
10164 ktime_to_us(ktime_sub(ktime_get(), start)),
10165 hba->curr_dev_pwr_mode, hba->uic_link_state);
10166
10167 return ret;
10168 }
10169 EXPORT_SYMBOL(ufshcd_system_resume);
10170 #endif /* CONFIG_PM_SLEEP */
10171
10172 #ifdef CONFIG_PM
10173 /**
10174 * ufshcd_runtime_suspend - runtime suspend callback
10175 * @dev: Device associated with the UFS controller.
10176 *
10177 * Check the description of ufshcd_suspend() function for more details.
10178 *
10179 * Return: 0 for success and non-zero for failure.
10180 */
ufshcd_runtime_suspend(struct device * dev)10181 int ufshcd_runtime_suspend(struct device *dev)
10182 {
10183 struct ufs_hba *hba = dev_get_drvdata(dev);
10184 int ret;
10185 ktime_t start = ktime_get();
10186
10187 ret = ufshcd_suspend(hba);
10188
10189 trace_ufshcd_runtime_suspend(dev_name(hba->dev), ret,
10190 ktime_to_us(ktime_sub(ktime_get(), start)),
10191 hba->curr_dev_pwr_mode, hba->uic_link_state);
10192 return ret;
10193 }
10194 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10195
10196 /**
10197 * ufshcd_runtime_resume - runtime resume routine
10198 * @dev: Device associated with the UFS controller.
10199 *
10200 * This function basically brings controller
10201 * to active state. Following operations are done in this function:
10202 *
10203 * 1. Turn on all the controller related clocks
10204 * 2. Turn ON VCC rail
10205 *
10206 * Return: 0 upon success; < 0 upon failure.
10207 */
ufshcd_runtime_resume(struct device * dev)10208 int ufshcd_runtime_resume(struct device *dev)
10209 {
10210 struct ufs_hba *hba = dev_get_drvdata(dev);
10211 int ret;
10212 ktime_t start = ktime_get();
10213
10214 ret = ufshcd_resume(hba);
10215
10216 trace_ufshcd_runtime_resume(dev_name(hba->dev), ret,
10217 ktime_to_us(ktime_sub(ktime_get(), start)),
10218 hba->curr_dev_pwr_mode, hba->uic_link_state);
10219 return ret;
10220 }
10221 EXPORT_SYMBOL(ufshcd_runtime_resume);
10222 #endif /* CONFIG_PM */
10223
ufshcd_wl_shutdown(struct device * dev)10224 static void ufshcd_wl_shutdown(struct device *dev)
10225 {
10226 struct scsi_device *sdev = to_scsi_device(dev);
10227 struct ufs_hba *hba = shost_priv(sdev->host);
10228
10229 down(&hba->host_sem);
10230 hba->shutting_down = true;
10231 up(&hba->host_sem);
10232
10233 /* Turn on everything while shutting down */
10234 ufshcd_rpm_get_sync(hba);
10235 scsi_device_quiesce(sdev);
10236 shost_for_each_device(sdev, hba->host) {
10237 if (sdev == hba->ufs_device_wlun)
10238 continue;
10239 mutex_lock(&sdev->state_mutex);
10240 scsi_device_set_state(sdev, SDEV_OFFLINE);
10241 mutex_unlock(&sdev->state_mutex);
10242 }
10243 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10244
10245 /*
10246 * Next, turn off the UFS controller and the UFS regulators. Disable
10247 * clocks.
10248 */
10249 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10250 ufshcd_suspend(hba);
10251
10252 hba->is_powered = false;
10253 }
10254
10255 /**
10256 * ufshcd_remove - de-allocate SCSI host and host memory space
10257 * data structure memory
10258 * @hba: per adapter instance
10259 */
ufshcd_remove(struct ufs_hba * hba)10260 void ufshcd_remove(struct ufs_hba *hba)
10261 {
10262 if (hba->ufs_device_wlun)
10263 ufshcd_rpm_get_sync(hba);
10264 ufs_hwmon_remove(hba);
10265 ufs_bsg_remove(hba);
10266 ufs_sysfs_remove_nodes(hba->dev);
10267 cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
10268 blk_mq_destroy_queue(hba->tmf_queue);
10269 blk_put_queue(hba->tmf_queue);
10270 blk_mq_free_tag_set(&hba->tmf_tag_set);
10271 if (hba->scsi_host_added)
10272 scsi_remove_host(hba->host);
10273 /* disable interrupts */
10274 ufshcd_disable_intr(hba, hba->intr_mask);
10275 ufshcd_hba_stop(hba);
10276 ufshcd_hba_exit(hba);
10277 }
10278 EXPORT_SYMBOL_GPL(ufshcd_remove);
10279
10280 #ifdef CONFIG_PM_SLEEP
ufshcd_system_freeze(struct device * dev)10281 int ufshcd_system_freeze(struct device *dev)
10282 {
10283
10284 return ufshcd_system_suspend(dev);
10285
10286 }
10287 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10288
ufshcd_system_restore(struct device * dev)10289 int ufshcd_system_restore(struct device *dev)
10290 {
10291
10292 struct ufs_hba *hba = dev_get_drvdata(dev);
10293 int ret;
10294
10295 ret = ufshcd_system_resume(dev);
10296 if (ret)
10297 return ret;
10298
10299 /* Configure UTRL and UTMRL base address registers */
10300 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10301 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10302 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10303 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10304 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10305 REG_UTP_TASK_REQ_LIST_BASE_L);
10306 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10307 REG_UTP_TASK_REQ_LIST_BASE_H);
10308 /*
10309 * Make sure that UTRL and UTMRL base address registers
10310 * are updated with the latest queue addresses. Only after
10311 * updating these addresses, we can queue the new commands.
10312 */
10313 ufshcd_readl(hba, REG_UTP_TASK_REQ_LIST_BASE_H);
10314
10315 return 0;
10316
10317 }
10318 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10319
ufshcd_system_thaw(struct device * dev)10320 int ufshcd_system_thaw(struct device *dev)
10321 {
10322 return ufshcd_system_resume(dev);
10323 }
10324 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10325 #endif /* CONFIG_PM_SLEEP */
10326
10327 /**
10328 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
10329 * @hba: pointer to Host Bus Adapter (HBA)
10330 */
ufshcd_dealloc_host(struct ufs_hba * hba)10331 void ufshcd_dealloc_host(struct ufs_hba *hba)
10332 {
10333 scsi_host_put(hba->host);
10334 }
10335 EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
10336
10337 /**
10338 * ufshcd_set_dma_mask - Set dma mask based on the controller
10339 * addressing capability
10340 * @hba: per adapter instance
10341 *
10342 * Return: 0 for success, non-zero for failure.
10343 */
ufshcd_set_dma_mask(struct ufs_hba * hba)10344 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10345 {
10346 if (hba->vops && hba->vops->set_dma_mask)
10347 return hba->vops->set_dma_mask(hba);
10348 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10349 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10350 return 0;
10351 }
10352 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10353 }
10354
10355 /**
10356 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10357 * @dev: pointer to device handle
10358 * @hba_handle: driver private handle
10359 *
10360 * Return: 0 on success, non-zero value on failure.
10361 */
ufshcd_alloc_host(struct device * dev,struct ufs_hba ** hba_handle)10362 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10363 {
10364 struct Scsi_Host *host;
10365 struct ufs_hba *hba;
10366 int err = 0;
10367
10368 if (!dev) {
10369 dev_err(dev,
10370 "Invalid memory reference for dev is NULL\n");
10371 err = -ENODEV;
10372 goto out_error;
10373 }
10374
10375 host = scsi_host_alloc(&ufshcd_driver_template,
10376 sizeof(struct ufs_hba));
10377 if (!host) {
10378 dev_err(dev, "scsi_host_alloc failed\n");
10379 err = -ENOMEM;
10380 goto out_error;
10381 }
10382 host->nr_maps = HCTX_TYPE_POLL + 1;
10383 hba = shost_priv(host);
10384 hba->host = host;
10385 hba->dev = dev;
10386 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10387 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10388 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10389 INIT_LIST_HEAD(&hba->clk_list_head);
10390 spin_lock_init(&hba->outstanding_lock);
10391
10392 *hba_handle = hba;
10393
10394 out_error:
10395 return err;
10396 }
10397 EXPORT_SYMBOL(ufshcd_alloc_host);
10398
10399 /* 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)10400 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10401 const struct blk_mq_queue_data *qd)
10402 {
10403 WARN_ON_ONCE(true);
10404 return BLK_STS_NOTSUPP;
10405 }
10406
10407 static const struct blk_mq_ops ufshcd_tmf_ops = {
10408 .queue_rq = ufshcd_queue_tmf,
10409 };
10410
10411 /**
10412 * ufshcd_init - Driver initialization routine
10413 * @hba: per-adapter instance
10414 * @mmio_base: base register address
10415 * @irq: Interrupt line of device
10416 *
10417 * Return: 0 on success, non-zero value on failure.
10418 */
ufshcd_init(struct ufs_hba * hba,void __iomem * mmio_base,unsigned int irq)10419 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10420 {
10421 int err;
10422 struct Scsi_Host *host = hba->host;
10423 struct device *dev = hba->dev;
10424 char eh_wq_name[sizeof("ufs_eh_wq_00")];
10425
10426 /*
10427 * dev_set_drvdata() must be called before any callbacks are registered
10428 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10429 * sysfs).
10430 */
10431 dev_set_drvdata(dev, hba);
10432
10433 if (!mmio_base) {
10434 dev_err(hba->dev,
10435 "Invalid memory reference for mmio_base is NULL\n");
10436 err = -ENODEV;
10437 goto out_error;
10438 }
10439
10440 hba->mmio_base = mmio_base;
10441 hba->irq = irq;
10442 hba->vps = &ufs_hba_vps;
10443
10444 err = ufshcd_hba_init(hba);
10445 if (err)
10446 goto out_error;
10447
10448 /* Read capabilities registers */
10449 err = ufshcd_hba_capabilities(hba);
10450 if (err)
10451 goto out_disable;
10452
10453 /* Get UFS version supported by the controller */
10454 hba->ufs_version = ufshcd_get_ufs_version(hba);
10455
10456 /* Get Interrupt bit mask per version */
10457 hba->intr_mask = ufshcd_get_intr_mask(hba);
10458
10459 err = ufshcd_set_dma_mask(hba);
10460 if (err) {
10461 dev_err(hba->dev, "set dma mask failed\n");
10462 goto out_disable;
10463 }
10464
10465 /* Allocate memory for host memory space */
10466 err = ufshcd_memory_alloc(hba);
10467 if (err) {
10468 dev_err(hba->dev, "Memory allocation failed\n");
10469 goto out_disable;
10470 }
10471
10472 /* Configure LRB */
10473 ufshcd_host_memory_configure(hba);
10474
10475 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10476 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10477 host->max_id = UFSHCD_MAX_ID;
10478 host->max_lun = UFS_MAX_LUNS;
10479 host->max_channel = UFSHCD_MAX_CHANNEL;
10480 host->unique_id = host->host_no;
10481 host->max_cmd_len = UFS_CDB_SIZE;
10482 host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
10483
10484 hba->max_pwr_info.is_valid = false;
10485
10486 /* Initialize work queues */
10487 snprintf(eh_wq_name, sizeof(eh_wq_name), "ufs_eh_wq_%d",
10488 hba->host->host_no);
10489 hba->eh_wq = create_singlethread_workqueue(eh_wq_name);
10490 if (!hba->eh_wq) {
10491 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10492 __func__);
10493 err = -ENOMEM;
10494 goto out_disable;
10495 }
10496 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10497 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10498
10499 sema_init(&hba->host_sem, 1);
10500
10501 /* Initialize UIC command mutex */
10502 mutex_init(&hba->uic_cmd_mutex);
10503
10504 /* Initialize mutex for device management commands */
10505 mutex_init(&hba->dev_cmd.lock);
10506
10507 /* Initialize mutex for exception event control */
10508 mutex_init(&hba->ee_ctrl_mutex);
10509
10510 mutex_init(&hba->wb_mutex);
10511 init_rwsem(&hba->clk_scaling_lock);
10512
10513 ufshcd_init_clk_gating(hba);
10514
10515 ufshcd_init_clk_scaling(hba);
10516
10517 /*
10518 * In order to avoid any spurious interrupt immediately after
10519 * registering UFS controller interrupt handler, clear any pending UFS
10520 * interrupt status and disable all the UFS interrupts.
10521 */
10522 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10523 REG_INTERRUPT_STATUS);
10524 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10525 /*
10526 * Make sure that UFS interrupts are disabled and any pending interrupt
10527 * status is cleared before registering UFS interrupt handler.
10528 */
10529 ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
10530
10531 /* IRQ registration */
10532 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
10533 if (err) {
10534 dev_err(hba->dev, "request irq failed\n");
10535 goto out_disable;
10536 } else {
10537 hba->is_irq_enabled = true;
10538 }
10539
10540 if (!is_mcq_supported(hba)) {
10541 if (!hba->lsdb_sup) {
10542 dev_err(hba->dev, "%s: failed to initialize (legacy doorbell mode not supported)\n",
10543 __func__);
10544 err = -EINVAL;
10545 goto out_disable;
10546 }
10547 err = scsi_add_host(host, hba->dev);
10548 if (err) {
10549 dev_err(hba->dev, "scsi_add_host failed\n");
10550 goto out_disable;
10551 }
10552 hba->scsi_host_added = true;
10553 }
10554
10555 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10556 .nr_hw_queues = 1,
10557 .queue_depth = hba->nutmrs,
10558 .ops = &ufshcd_tmf_ops,
10559 .flags = BLK_MQ_F_NO_SCHED,
10560 };
10561 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10562 if (err < 0)
10563 goto out_remove_scsi_host;
10564 hba->tmf_queue = blk_mq_init_queue(&hba->tmf_tag_set);
10565 if (IS_ERR(hba->tmf_queue)) {
10566 err = PTR_ERR(hba->tmf_queue);
10567 goto free_tmf_tag_set;
10568 }
10569 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10570 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10571 if (!hba->tmf_rqs) {
10572 err = -ENOMEM;
10573 goto free_tmf_queue;
10574 }
10575
10576 /* Reset the attached device */
10577 ufshcd_device_reset(hba);
10578
10579 ufshcd_init_crypto(hba);
10580
10581 /* Host controller enable */
10582 err = ufshcd_hba_enable(hba);
10583 if (err) {
10584 dev_err(hba->dev, "Host controller enable failed\n");
10585 ufshcd_print_evt_hist(hba);
10586 ufshcd_print_host_state(hba);
10587 goto free_tmf_queue;
10588 }
10589
10590 /*
10591 * Set the default power management level for runtime and system PM if
10592 * not set by the host controller drivers.
10593 * Default power saving mode is to keep UFS link in Hibern8 state
10594 * and UFS device in sleep state.
10595 */
10596 if (!hba->rpm_lvl)
10597 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10598 UFS_SLEEP_PWR_MODE,
10599 UIC_LINK_HIBERN8_STATE);
10600 if (!hba->spm_lvl)
10601 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10602 UFS_SLEEP_PWR_MODE,
10603 UIC_LINK_HIBERN8_STATE);
10604
10605 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work);
10606 INIT_DELAYED_WORK(&hba->ufs_rtc_update_work, ufshcd_rtc_work);
10607
10608 /* Set the default auto-hiberate idle timer value to 150 ms */
10609 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10610 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10611 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10612 }
10613
10614 /* Hold auto suspend until async scan completes */
10615 pm_runtime_get_sync(dev);
10616 atomic_set(&hba->scsi_block_reqs_cnt, 0);
10617 /*
10618 * We are assuming that device wasn't put in sleep/power-down
10619 * state exclusively during the boot stage before kernel.
10620 * This assumption helps avoid doing link startup twice during
10621 * ufshcd_probe_hba().
10622 */
10623 ufshcd_set_ufs_dev_active(hba);
10624
10625 async_schedule(ufshcd_async_scan, hba);
10626 ufs_sysfs_add_nodes(hba->dev);
10627
10628 device_enable_async_suspend(dev);
10629 return 0;
10630
10631 free_tmf_queue:
10632 blk_mq_destroy_queue(hba->tmf_queue);
10633 blk_put_queue(hba->tmf_queue);
10634 free_tmf_tag_set:
10635 blk_mq_free_tag_set(&hba->tmf_tag_set);
10636 out_remove_scsi_host:
10637 if (hba->scsi_host_added)
10638 scsi_remove_host(hba->host);
10639 out_disable:
10640 hba->is_irq_enabled = false;
10641 ufshcd_hba_exit(hba);
10642 out_error:
10643 return err;
10644 }
10645 EXPORT_SYMBOL_GPL(ufshcd_init);
10646
ufshcd_resume_complete(struct device * dev)10647 void ufshcd_resume_complete(struct device *dev)
10648 {
10649 struct ufs_hba *hba = dev_get_drvdata(dev);
10650
10651 if (hba->complete_put) {
10652 ufshcd_rpm_put(hba);
10653 hba->complete_put = false;
10654 }
10655 }
10656 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10657
ufshcd_rpm_ok_for_spm(struct ufs_hba * hba)10658 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10659 {
10660 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10661 enum ufs_dev_pwr_mode dev_pwr_mode;
10662 enum uic_link_state link_state;
10663 unsigned long flags;
10664 bool res;
10665
10666 spin_lock_irqsave(&dev->power.lock, flags);
10667 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10668 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10669 res = pm_runtime_suspended(dev) &&
10670 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10671 hba->uic_link_state == link_state &&
10672 !hba->dev_info.b_rpm_dev_flush_capable;
10673 spin_unlock_irqrestore(&dev->power.lock, flags);
10674
10675 return res;
10676 }
10677
__ufshcd_suspend_prepare(struct device * dev,bool rpm_ok_for_spm)10678 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10679 {
10680 struct ufs_hba *hba = dev_get_drvdata(dev);
10681 int ret;
10682
10683 /*
10684 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10685 * are same. And it doesn't wake up the device for system-suspend
10686 * if it's runtime suspended. But ufs doesn't follow that.
10687 * Refer ufshcd_resume_complete()
10688 */
10689 if (hba->ufs_device_wlun) {
10690 /* Prevent runtime suspend */
10691 ufshcd_rpm_get_noresume(hba);
10692 /*
10693 * Check if already runtime suspended in same state as system
10694 * suspend would be.
10695 */
10696 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10697 /* RPM state is not ok for SPM, so runtime resume */
10698 ret = ufshcd_rpm_resume(hba);
10699 if (ret < 0 && ret != -EACCES) {
10700 ufshcd_rpm_put(hba);
10701 return ret;
10702 }
10703 }
10704 hba->complete_put = true;
10705 }
10706 return 0;
10707 }
10708 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10709
ufshcd_suspend_prepare(struct device * dev)10710 int ufshcd_suspend_prepare(struct device *dev)
10711 {
10712 return __ufshcd_suspend_prepare(dev, true);
10713 }
10714 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10715
10716 #ifdef CONFIG_PM_SLEEP
ufshcd_wl_poweroff(struct device * dev)10717 static int ufshcd_wl_poweroff(struct device *dev)
10718 {
10719 struct scsi_device *sdev = to_scsi_device(dev);
10720 struct ufs_hba *hba = shost_priv(sdev->host);
10721
10722 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10723 return 0;
10724 }
10725 #endif
10726
ufshcd_wl_probe(struct device * dev)10727 static int ufshcd_wl_probe(struct device *dev)
10728 {
10729 struct scsi_device *sdev = to_scsi_device(dev);
10730
10731 if (!is_device_wlun(sdev))
10732 return -ENODEV;
10733
10734 blk_pm_runtime_init(sdev->request_queue, dev);
10735 pm_runtime_set_autosuspend_delay(dev, 0);
10736 pm_runtime_allow(dev);
10737
10738 return 0;
10739 }
10740
ufshcd_wl_remove(struct device * dev)10741 static int ufshcd_wl_remove(struct device *dev)
10742 {
10743 pm_runtime_forbid(dev);
10744 return 0;
10745 }
10746
10747 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
10748 #ifdef CONFIG_PM_SLEEP
10749 .suspend = ufshcd_wl_suspend,
10750 .resume = ufshcd_wl_resume,
10751 .freeze = ufshcd_wl_suspend,
10752 .thaw = ufshcd_wl_resume,
10753 .poweroff = ufshcd_wl_poweroff,
10754 .restore = ufshcd_wl_resume,
10755 #endif
10756 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
10757 };
10758
ufshcd_check_header_layout(void)10759 static void ufshcd_check_header_layout(void)
10760 {
10761 /*
10762 * gcc compilers before version 10 cannot do constant-folding for
10763 * sub-byte bitfields. Hence skip the layout checks for gcc 9 and
10764 * before.
10765 */
10766 if (IS_ENABLED(CONFIG_CC_IS_GCC) && CONFIG_GCC_VERSION < 100000)
10767 return;
10768
10769 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10770 .cci = 3})[0] != 3);
10771
10772 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10773 .ehs_length = 2})[1] != 2);
10774
10775 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10776 .enable_crypto = 1})[2]
10777 != 0x80);
10778
10779 BUILD_BUG_ON((((u8 *)&(struct request_desc_header){
10780 .command_type = 5,
10781 .data_direction = 3,
10782 .interrupt = 1,
10783 })[3]) != ((5 << 4) | (3 << 1) | 1));
10784
10785 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10786 .dunl = cpu_to_le32(0xdeadbeef)})[1] !=
10787 cpu_to_le32(0xdeadbeef));
10788
10789 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10790 .ocs = 4})[8] != 4);
10791
10792 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
10793 .cds = 5})[9] != 5);
10794
10795 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
10796 .dunu = cpu_to_le32(0xbadcafe)})[3] !=
10797 cpu_to_le32(0xbadcafe));
10798
10799 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10800 .iid = 0xf })[4] != 0xf0);
10801
10802 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
10803 .command_set_type = 0xf })[4] != 0xf);
10804 }
10805
10806 /*
10807 * ufs_dev_wlun_template - describes ufs device wlun
10808 * ufs-device wlun - used to send pm commands
10809 * All luns are consumers of ufs-device wlun.
10810 *
10811 * Currently, no sd driver is present for wluns.
10812 * Hence the no specific pm operations are performed.
10813 * With ufs design, SSU should be sent to ufs-device wlun.
10814 * Hence register a scsi driver for ufs wluns only.
10815 */
10816 static struct scsi_driver ufs_dev_wlun_template = {
10817 .gendrv = {
10818 .name = "ufs_device_wlun",
10819 .owner = THIS_MODULE,
10820 .probe = ufshcd_wl_probe,
10821 .remove = ufshcd_wl_remove,
10822 .pm = &ufshcd_wl_pm_ops,
10823 .shutdown = ufshcd_wl_shutdown,
10824 },
10825 };
10826
ufshcd_core_init(void)10827 static int __init ufshcd_core_init(void)
10828 {
10829 int ret;
10830
10831 ufshcd_check_header_layout();
10832
10833 ufs_debugfs_init();
10834
10835 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
10836 if (ret)
10837 ufs_debugfs_exit();
10838 return ret;
10839 }
10840
ufshcd_core_exit(void)10841 static void __exit ufshcd_core_exit(void)
10842 {
10843 ufs_debugfs_exit();
10844 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
10845 }
10846
10847 module_init(ufshcd_core_init);
10848 module_exit(ufshcd_core_exit);
10849
10850 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
10851 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
10852 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
10853 MODULE_SOFTDEP("pre: governor_simpleondemand");
10854 MODULE_LICENSE("GPL");
10855