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