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 && !ret)
4286 *mib_val = uic_cmd.argument3;
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 = 0, 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 (!ufshcd_is_ufs_dev_active(hba))
5070 link_startup_again = true;
5071
5072 link_startup:
5073 do {
5074 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
5075
5076 ret = ufshcd_dme_link_startup(hba);
5077
5078 /* check if device is detected by inter-connect layer */
5079 if (!ret && !ufshcd_is_device_present(hba)) {
5080 ufshcd_update_evt_hist(hba,
5081 UFS_EVT_LINK_STARTUP_FAIL,
5082 0);
5083 dev_err(hba->dev, "%s: Device not present\n", __func__);
5084 ret = -ENXIO;
5085 goto out;
5086 }
5087
5088 /*
5089 * DME link lost indication is only received when link is up,
5090 * but we can't be sure if the link is up until link startup
5091 * succeeds. So reset the local Uni-Pro and try again.
5092 */
5093 if (ret && retries && ufshcd_hba_enable(hba)) {
5094 ufshcd_update_evt_hist(hba,
5095 UFS_EVT_LINK_STARTUP_FAIL,
5096 (u32)ret);
5097 goto out;
5098 }
5099 } while (ret && retries--);
5100
5101 if (ret) {
5102 /* failed to get the link up... retire */
5103 ufshcd_update_evt_hist(hba,
5104 UFS_EVT_LINK_STARTUP_FAIL,
5105 (u32)ret);
5106 goto out;
5107 }
5108
5109 if (link_startup_again) {
5110 link_startup_again = false;
5111 retries = DME_LINKSTARTUP_RETRIES;
5112 goto link_startup;
5113 }
5114
5115 /* Mark that link is up in PWM-G1, 1-lane, SLOW-AUTO mode */
5116 ufshcd_init_pwr_info(hba);
5117 ufshcd_print_pwr_info(hba);
5118
5119 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
5120 ret = ufshcd_disable_device_tx_lcc(hba);
5121 if (ret)
5122 goto out;
5123 }
5124
5125 /* Include any host controller configuration via UIC commands */
5126 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
5127 if (ret)
5128 goto out;
5129
5130 /* Clear UECPA once due to LINERESET has happened during LINK_STARTUP */
5131 ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
5132 ret = ufshcd_make_hba_operational(hba);
5133 out:
5134 if (ret) {
5135 dev_err(hba->dev, "link startup failed %d\n", ret);
5136 ufshcd_print_host_state(hba);
5137 ufshcd_print_pwr_info(hba);
5138 ufshcd_print_evt_hist(hba);
5139 }
5140 return ret;
5141 }
5142
5143 /**
5144 * ufshcd_verify_dev_init() - Verify device initialization
5145 * @hba: per-adapter instance
5146 *
5147 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
5148 * device Transport Protocol (UTP) layer is ready after a reset.
5149 * If the UTP layer at the device side is not initialized, it may
5150 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
5151 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
5152 *
5153 * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
5154 * < 0 if another error occurred.
5155 */
ufshcd_verify_dev_init(struct ufs_hba * hba)5156 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
5157 {
5158 int err = 0;
5159 int retries;
5160
5161 ufshcd_dev_man_lock(hba);
5162
5163 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
5164 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
5165 hba->nop_out_timeout);
5166
5167 if (!err || err == -ETIMEDOUT)
5168 break;
5169
5170 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
5171 }
5172
5173 ufshcd_dev_man_unlock(hba);
5174
5175 if (err)
5176 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
5177 return err;
5178 }
5179
5180 /**
5181 * ufshcd_setup_links - associate link b/w device wlun and other luns
5182 * @sdev: pointer to SCSI device
5183 * @hba: pointer to ufs hba
5184 */
ufshcd_setup_links(struct ufs_hba * hba,struct scsi_device * sdev)5185 static void ufshcd_setup_links(struct ufs_hba *hba, struct scsi_device *sdev)
5186 {
5187 struct device_link *link;
5188
5189 /*
5190 * Device wlun is the supplier & rest of the luns are consumers.
5191 * This ensures that device wlun suspends after all other luns.
5192 */
5193 if (hba->ufs_device_wlun) {
5194 link = device_link_add(&sdev->sdev_gendev,
5195 &hba->ufs_device_wlun->sdev_gendev,
5196 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE);
5197 if (!link) {
5198 dev_err(&sdev->sdev_gendev, "Failed establishing link - %s\n",
5199 dev_name(&hba->ufs_device_wlun->sdev_gendev));
5200 return;
5201 }
5202 hba->luns_avail--;
5203 /* Ignore REPORT_LUN wlun probing */
5204 if (hba->luns_avail == 1) {
5205 ufshcd_rpm_put(hba);
5206 return;
5207 }
5208 } else {
5209 /*
5210 * Device wlun is probed. The assumption is that WLUNs are
5211 * scanned before other LUNs.
5212 */
5213 hba->luns_avail--;
5214 }
5215 }
5216
5217 /**
5218 * ufshcd_lu_init - Initialize the relevant parameters of the LU
5219 * @hba: per-adapter instance
5220 * @sdev: pointer to SCSI device
5221 */
ufshcd_lu_init(struct ufs_hba * hba,struct scsi_device * sdev)5222 static void ufshcd_lu_init(struct ufs_hba *hba, struct scsi_device *sdev)
5223 {
5224 int len = QUERY_DESC_MAX_SIZE;
5225 u8 lun = ufshcd_scsi_to_upiu_lun(sdev->lun);
5226 u8 lun_qdepth = hba->nutrs;
5227 u8 *desc_buf;
5228 int ret;
5229
5230 desc_buf = kzalloc(len, GFP_KERNEL);
5231 if (!desc_buf)
5232 goto set_qdepth;
5233
5234 ret = ufshcd_read_unit_desc_param(hba, lun, 0, desc_buf, len);
5235 if (ret < 0) {
5236 if (ret == -EOPNOTSUPP)
5237 /* If LU doesn't support unit descriptor, its queue depth is set to 1 */
5238 lun_qdepth = 1;
5239 kfree(desc_buf);
5240 goto set_qdepth;
5241 }
5242
5243 if (desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH]) {
5244 /*
5245 * In per-LU queueing architecture, bLUQueueDepth will not be 0, then we will
5246 * use the smaller between UFSHCI CAP.NUTRS and UFS LU bLUQueueDepth
5247 */
5248 lun_qdepth = min_t(int, desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH], hba->nutrs);
5249 }
5250 /*
5251 * According to UFS device specification, the write protection mode is only supported by
5252 * normal LU, not supported by WLUN.
5253 */
5254 if (hba->dev_info.f_power_on_wp_en && lun < hba->dev_info.max_lu_supported &&
5255 !hba->dev_info.is_lu_power_on_wp &&
5256 desc_buf[UNIT_DESC_PARAM_LU_WR_PROTECT] == UFS_LU_POWER_ON_WP)
5257 hba->dev_info.is_lu_power_on_wp = true;
5258
5259 /* In case of RPMB LU, check if advanced RPMB mode is enabled */
5260 if (desc_buf[UNIT_DESC_PARAM_UNIT_INDEX] == UFS_UPIU_RPMB_WLUN &&
5261 desc_buf[RPMB_UNIT_DESC_PARAM_REGION_EN] & BIT(4))
5262 hba->dev_info.b_advanced_rpmb_en = true;
5263
5264
5265 kfree(desc_buf);
5266 set_qdepth:
5267 /*
5268 * For WLUNs that don't support unit descriptor, queue depth is set to 1. For LUs whose
5269 * bLUQueueDepth == 0, the queue depth is set to a maximum value that host can queue.
5270 */
5271 dev_dbg(hba->dev, "Set LU %x queue depth %d\n", lun, lun_qdepth);
5272 scsi_change_queue_depth(sdev, lun_qdepth);
5273 }
5274
5275 /**
5276 * ufshcd_sdev_init - handle initial SCSI device configurations
5277 * @sdev: pointer to SCSI device
5278 *
5279 * Return: success.
5280 */
ufshcd_sdev_init(struct scsi_device * sdev)5281 static int ufshcd_sdev_init(struct scsi_device *sdev)
5282 {
5283 struct ufs_hba *hba;
5284
5285 hba = shost_priv(sdev->host);
5286
5287 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
5288 sdev->use_10_for_ms = 1;
5289
5290 /* DBD field should be set to 1 in mode sense(10) */
5291 sdev->set_dbd_for_ms = 1;
5292
5293 /* allow SCSI layer to restart the device in case of errors */
5294 sdev->allow_restart = 1;
5295
5296 /* REPORT SUPPORTED OPERATION CODES is not supported */
5297 sdev->no_report_opcodes = 1;
5298
5299 /* WRITE_SAME command is not supported */
5300 sdev->no_write_same = 1;
5301
5302 ufshcd_lu_init(hba, sdev);
5303
5304 ufshcd_setup_links(hba, sdev);
5305
5306 return 0;
5307 }
5308
5309 /**
5310 * ufshcd_change_queue_depth - change queue depth
5311 * @sdev: pointer to SCSI device
5312 * @depth: required depth to set
5313 *
5314 * Change queue depth and make sure the max. limits are not crossed.
5315 *
5316 * Return: new queue depth.
5317 */
ufshcd_change_queue_depth(struct scsi_device * sdev,int depth)5318 static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
5319 {
5320 return scsi_change_queue_depth(sdev, min(depth, sdev->host->can_queue));
5321 }
5322
5323 /**
5324 * ufshcd_sdev_configure - adjust SCSI device configurations
5325 * @sdev: pointer to SCSI device
5326 * @lim: queue limits
5327 *
5328 * Return: 0 (success).
5329 */
ufshcd_sdev_configure(struct scsi_device * sdev,struct queue_limits * lim)5330 static int ufshcd_sdev_configure(struct scsi_device *sdev,
5331 struct queue_limits *lim)
5332 {
5333 struct ufs_hba *hba = shost_priv(sdev->host);
5334 struct request_queue *q = sdev->request_queue;
5335
5336 lim->dma_pad_mask = PRDT_DATA_BYTE_COUNT_PAD - 1;
5337
5338 /*
5339 * Block runtime-pm until all consumers are added.
5340 * Refer ufshcd_setup_links().
5341 */
5342 if (is_device_wlun(sdev))
5343 pm_runtime_get_noresume(&sdev->sdev_gendev);
5344 else if (ufshcd_is_rpm_autosuspend_allowed(hba))
5345 sdev->rpm_autosuspend = 1;
5346 /*
5347 * Do not print messages during runtime PM to avoid never-ending cycles
5348 * of messages written back to storage by user space causing runtime
5349 * resume, causing more messages and so on.
5350 */
5351 sdev->silence_suspend = 1;
5352
5353 if (hba->vops && hba->vops->config_scsi_dev)
5354 hba->vops->config_scsi_dev(sdev);
5355
5356 ufshcd_crypto_register(hba, q);
5357
5358 return 0;
5359 }
5360
5361 /**
5362 * ufshcd_sdev_destroy - remove SCSI device configurations
5363 * @sdev: pointer to SCSI device
5364 */
ufshcd_sdev_destroy(struct scsi_device * sdev)5365 static void ufshcd_sdev_destroy(struct scsi_device *sdev)
5366 {
5367 struct ufs_hba *hba;
5368 unsigned long flags;
5369
5370 hba = shost_priv(sdev->host);
5371
5372 /* Drop the reference as it won't be needed anymore */
5373 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
5374 spin_lock_irqsave(hba->host->host_lock, flags);
5375 hba->ufs_device_wlun = NULL;
5376 spin_unlock_irqrestore(hba->host->host_lock, flags);
5377 } else if (hba->ufs_device_wlun) {
5378 struct device *supplier = NULL;
5379
5380 /* Ensure UFS Device WLUN exists and does not disappear */
5381 spin_lock_irqsave(hba->host->host_lock, flags);
5382 if (hba->ufs_device_wlun) {
5383 supplier = &hba->ufs_device_wlun->sdev_gendev;
5384 get_device(supplier);
5385 }
5386 spin_unlock_irqrestore(hba->host->host_lock, flags);
5387
5388 if (supplier) {
5389 /*
5390 * If a LUN fails to probe (e.g. absent BOOT WLUN), the
5391 * device will not have been registered but can still
5392 * have a device link holding a reference to the device.
5393 */
5394 device_link_remove(&sdev->sdev_gendev, supplier);
5395 put_device(supplier);
5396 }
5397 }
5398 }
5399
5400 /**
5401 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
5402 * @lrbp: pointer to local reference block of completed command
5403 * @scsi_status: SCSI command status
5404 *
5405 * Return: value base on SCSI command status.
5406 */
5407 static inline int
ufshcd_scsi_cmd_status(struct ufshcd_lrb * lrbp,int scsi_status)5408 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
5409 {
5410 int result = 0;
5411
5412 switch (scsi_status) {
5413 case SAM_STAT_CHECK_CONDITION:
5414 ufshcd_copy_sense_data(lrbp);
5415 fallthrough;
5416 case SAM_STAT_GOOD:
5417 result |= DID_OK << 16 | scsi_status;
5418 break;
5419 case SAM_STAT_TASK_SET_FULL:
5420 case SAM_STAT_BUSY:
5421 case SAM_STAT_TASK_ABORTED:
5422 ufshcd_copy_sense_data(lrbp);
5423 result |= scsi_status;
5424 break;
5425 default:
5426 result |= DID_ERROR << 16;
5427 break;
5428 } /* end of switch */
5429
5430 return result;
5431 }
5432
5433 /**
5434 * ufshcd_transfer_rsp_status - Get overall status of the response
5435 * @hba: per adapter instance
5436 * @lrbp: pointer to local reference block of completed command
5437 * @cqe: pointer to the completion queue entry
5438 *
5439 * Return: result of the command to notify SCSI midlayer.
5440 */
5441 static inline int
ufshcd_transfer_rsp_status(struct ufs_hba * hba,struct ufshcd_lrb * lrbp,struct cq_entry * cqe)5442 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp,
5443 struct cq_entry *cqe)
5444 {
5445 int result = 0;
5446 int scsi_status;
5447 enum utp_ocs ocs;
5448 u8 upiu_flags;
5449 u32 resid;
5450
5451 upiu_flags = lrbp->ucd_rsp_ptr->header.flags;
5452 resid = be32_to_cpu(lrbp->ucd_rsp_ptr->sr.residual_transfer_count);
5453 /*
5454 * Test !overflow instead of underflow to support UFS devices that do
5455 * not set either flag.
5456 */
5457 if (resid && !(upiu_flags & UPIU_RSP_FLAG_OVERFLOW))
5458 scsi_set_resid(lrbp->cmd, resid);
5459
5460 /* overall command status of utrd */
5461 ocs = ufshcd_get_tr_ocs(lrbp, cqe);
5462
5463 if (hba->quirks & UFSHCD_QUIRK_BROKEN_OCS_FATAL_ERROR) {
5464 if (lrbp->ucd_rsp_ptr->header.response ||
5465 lrbp->ucd_rsp_ptr->header.status)
5466 ocs = OCS_SUCCESS;
5467 }
5468
5469 switch (ocs) {
5470 case OCS_SUCCESS:
5471 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
5472 switch (ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr)) {
5473 case UPIU_TRANSACTION_RESPONSE:
5474 /*
5475 * get the result based on SCSI status response
5476 * to notify the SCSI midlayer of the command status
5477 */
5478 scsi_status = lrbp->ucd_rsp_ptr->header.status;
5479 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
5480
5481 /*
5482 * Currently we are only supporting BKOPs exception
5483 * events hence we can ignore BKOPs exception event
5484 * during power management callbacks. BKOPs exception
5485 * event is not expected to be raised in runtime suspend
5486 * callback as it allows the urgent bkops.
5487 * During system suspend, we are anyway forcefully
5488 * disabling the bkops and if urgent bkops is needed
5489 * it will be enabled on system resume. Long term
5490 * solution could be to abort the system suspend if
5491 * UFS device needs urgent BKOPs.
5492 */
5493 if (!hba->pm_op_in_progress &&
5494 !ufshcd_eh_in_progress(hba) &&
5495 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
5496 /* Flushed in suspend */
5497 schedule_work(&hba->eeh_work);
5498 break;
5499 case UPIU_TRANSACTION_REJECT_UPIU:
5500 /* TODO: handle Reject UPIU Response */
5501 result = DID_ERROR << 16;
5502 dev_err(hba->dev,
5503 "Reject UPIU not fully implemented\n");
5504 break;
5505 default:
5506 dev_err(hba->dev,
5507 "Unexpected request response code = %x\n",
5508 result);
5509 result = DID_ERROR << 16;
5510 break;
5511 }
5512 break;
5513 case OCS_ABORTED:
5514 case OCS_INVALID_COMMAND_STATUS:
5515 result |= DID_REQUEUE << 16;
5516 dev_warn(hba->dev,
5517 "OCS %s from controller for tag %d\n",
5518 (ocs == OCS_ABORTED ? "aborted" : "invalid"),
5519 lrbp->task_tag);
5520 break;
5521 case OCS_INVALID_CMD_TABLE_ATTR:
5522 case OCS_INVALID_PRDT_ATTR:
5523 case OCS_MISMATCH_DATA_BUF_SIZE:
5524 case OCS_MISMATCH_RESP_UPIU_SIZE:
5525 case OCS_PEER_COMM_FAILURE:
5526 case OCS_FATAL_ERROR:
5527 case OCS_DEVICE_FATAL_ERROR:
5528 case OCS_INVALID_CRYPTO_CONFIG:
5529 case OCS_GENERAL_CRYPTO_ERROR:
5530 default:
5531 result |= DID_ERROR << 16;
5532 dev_err(hba->dev,
5533 "OCS error from controller = %x for tag %d\n",
5534 ocs, lrbp->task_tag);
5535 ufshcd_print_evt_hist(hba);
5536 ufshcd_print_host_state(hba);
5537 break;
5538 } /* end of switch */
5539
5540 if ((host_byte(result) != DID_OK) &&
5541 (host_byte(result) != DID_REQUEUE) && !hba->silence_err_logs)
5542 ufshcd_print_tr(hba, lrbp->task_tag, true);
5543 return result;
5544 }
5545
ufshcd_is_auto_hibern8_error(struct ufs_hba * hba,u32 intr_mask)5546 static bool ufshcd_is_auto_hibern8_error(struct ufs_hba *hba,
5547 u32 intr_mask)
5548 {
5549 if (!ufshcd_is_auto_hibern8_supported(hba) ||
5550 !ufshcd_is_auto_hibern8_enabled(hba))
5551 return false;
5552
5553 if (!(intr_mask & UFSHCD_UIC_HIBERN8_MASK))
5554 return false;
5555
5556 if (hba->active_uic_cmd &&
5557 (hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_ENTER ||
5558 hba->active_uic_cmd->command == UIC_CMD_DME_HIBER_EXIT))
5559 return false;
5560
5561 return true;
5562 }
5563
5564 /**
5565 * ufshcd_uic_cmd_compl - handle completion of uic command
5566 * @hba: per adapter instance
5567 * @intr_status: interrupt status generated by the controller
5568 *
5569 * Return:
5570 * IRQ_HANDLED - If interrupt is valid
5571 * IRQ_NONE - If invalid interrupt
5572 */
ufshcd_uic_cmd_compl(struct ufs_hba * hba,u32 intr_status)5573 static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
5574 {
5575 irqreturn_t retval = IRQ_NONE;
5576 struct uic_command *cmd;
5577
5578 guard(spinlock_irqsave)(hba->host->host_lock);
5579 cmd = hba->active_uic_cmd;
5580 if (!cmd)
5581 goto unlock;
5582
5583 if (ufshcd_is_auto_hibern8_error(hba, intr_status))
5584 hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status);
5585
5586 if (intr_status & UIC_COMMAND_COMPL) {
5587 cmd->argument2 |= ufshcd_get_uic_cmd_result(hba);
5588 cmd->argument3 = ufshcd_get_dme_attr_val(hba);
5589 if (!hba->uic_async_done)
5590 cmd->cmd_active = 0;
5591 complete(&cmd->done);
5592 retval = IRQ_HANDLED;
5593 }
5594
5595 if (intr_status & UFSHCD_UIC_PWR_MASK && hba->uic_async_done) {
5596 cmd->cmd_active = 0;
5597 complete(hba->uic_async_done);
5598 retval = IRQ_HANDLED;
5599 }
5600
5601 if (retval == IRQ_HANDLED)
5602 ufshcd_add_uic_command_trace(hba, cmd, UFS_CMD_COMP);
5603
5604 unlock:
5605 return retval;
5606 }
5607
5608 /* Release the resources allocated for processing a SCSI command. */
ufshcd_release_scsi_cmd(struct ufs_hba * hba,struct ufshcd_lrb * lrbp)5609 void ufshcd_release_scsi_cmd(struct ufs_hba *hba,
5610 struct ufshcd_lrb *lrbp)
5611 {
5612 struct scsi_cmnd *cmd = lrbp->cmd;
5613
5614 scsi_dma_unmap(cmd);
5615 ufshcd_crypto_clear_prdt(hba, lrbp);
5616 ufshcd_release(hba);
5617 ufshcd_clk_scaling_update_busy(hba);
5618 }
5619
5620 /**
5621 * ufshcd_compl_one_cqe - handle a completion queue entry
5622 * @hba: per adapter instance
5623 * @task_tag: the task tag of the request to be completed
5624 * @cqe: pointer to the completion queue entry
5625 */
ufshcd_compl_one_cqe(struct ufs_hba * hba,int task_tag,struct cq_entry * cqe)5626 void ufshcd_compl_one_cqe(struct ufs_hba *hba, int task_tag,
5627 struct cq_entry *cqe)
5628 {
5629 struct ufshcd_lrb *lrbp;
5630 struct scsi_cmnd *cmd;
5631 enum utp_ocs ocs;
5632
5633 lrbp = &hba->lrb[task_tag];
5634 if (hba->monitor.enabled) {
5635 lrbp->compl_time_stamp = ktime_get();
5636 lrbp->compl_time_stamp_local_clock = local_clock();
5637 }
5638 cmd = lrbp->cmd;
5639 if (cmd) {
5640 if (unlikely(ufshcd_should_inform_monitor(hba, lrbp)))
5641 ufshcd_update_monitor(hba, lrbp);
5642 ufshcd_add_command_trace(hba, task_tag, UFS_CMD_COMP);
5643 cmd->result = ufshcd_transfer_rsp_status(hba, lrbp, cqe);
5644 ufshcd_release_scsi_cmd(hba, lrbp);
5645 /* Do not touch lrbp after scsi done */
5646 scsi_done(cmd);
5647 } else {
5648 if (cqe) {
5649 ocs = le32_to_cpu(cqe->status) & MASK_OCS;
5650 lrbp->utr_descriptor_ptr->header.ocs = ocs;
5651 }
5652 complete(&hba->dev_cmd.complete);
5653 }
5654 }
5655
5656 /**
5657 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
5658 * @hba: per adapter instance
5659 * @completed_reqs: bitmask that indicates which requests to complete
5660 */
__ufshcd_transfer_req_compl(struct ufs_hba * hba,unsigned long completed_reqs)5661 static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
5662 unsigned long completed_reqs)
5663 {
5664 int tag;
5665
5666 for_each_set_bit(tag, &completed_reqs, hba->nutrs)
5667 ufshcd_compl_one_cqe(hba, tag, NULL);
5668 }
5669
5670 /* Any value that is not an existing queue number is fine for this constant. */
5671 enum {
5672 UFSHCD_POLL_FROM_INTERRUPT_CONTEXT = -1
5673 };
5674
ufshcd_clear_polled(struct ufs_hba * hba,unsigned long * completed_reqs)5675 static void ufshcd_clear_polled(struct ufs_hba *hba,
5676 unsigned long *completed_reqs)
5677 {
5678 int tag;
5679
5680 for_each_set_bit(tag, completed_reqs, hba->nutrs) {
5681 struct scsi_cmnd *cmd = hba->lrb[tag].cmd;
5682
5683 if (!cmd)
5684 continue;
5685 if (scsi_cmd_to_rq(cmd)->cmd_flags & REQ_POLLED)
5686 __clear_bit(tag, completed_reqs);
5687 }
5688 }
5689
5690 /*
5691 * Return: > 0 if one or more commands have been completed or 0 if no
5692 * requests have been completed.
5693 */
ufshcd_poll(struct Scsi_Host * shost,unsigned int queue_num)5694 static int ufshcd_poll(struct Scsi_Host *shost, unsigned int queue_num)
5695 {
5696 struct ufs_hba *hba = shost_priv(shost);
5697 unsigned long completed_reqs, flags;
5698 u32 tr_doorbell;
5699 struct ufs_hw_queue *hwq;
5700
5701 if (hba->mcq_enabled) {
5702 hwq = &hba->uhq[queue_num];
5703
5704 return ufshcd_mcq_poll_cqe_lock(hba, hwq);
5705 }
5706
5707 spin_lock_irqsave(&hba->outstanding_lock, flags);
5708 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
5709 completed_reqs = ~tr_doorbell & hba->outstanding_reqs;
5710 WARN_ONCE(completed_reqs & ~hba->outstanding_reqs,
5711 "completed: %#lx; outstanding: %#lx\n", completed_reqs,
5712 hba->outstanding_reqs);
5713 if (queue_num == UFSHCD_POLL_FROM_INTERRUPT_CONTEXT) {
5714 /* Do not complete polled requests from interrupt context. */
5715 ufshcd_clear_polled(hba, &completed_reqs);
5716 }
5717 hba->outstanding_reqs &= ~completed_reqs;
5718 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
5719
5720 if (completed_reqs)
5721 __ufshcd_transfer_req_compl(hba, completed_reqs);
5722
5723 return completed_reqs != 0;
5724 }
5725
5726 /**
5727 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
5728 * invoked from the error handler context or ufshcd_host_reset_and_restore()
5729 * to complete the pending transfers and free the resources associated with
5730 * the scsi command.
5731 *
5732 * @hba: per adapter instance
5733 * @force_compl: This flag is set to true when invoked
5734 * from ufshcd_host_reset_and_restore() in which case it requires special
5735 * handling because the host controller has been reset by ufshcd_hba_stop().
5736 */
ufshcd_mcq_compl_pending_transfer(struct ufs_hba * hba,bool force_compl)5737 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
5738 bool force_compl)
5739 {
5740 struct ufs_hw_queue *hwq;
5741 struct ufshcd_lrb *lrbp;
5742 struct scsi_cmnd *cmd;
5743 unsigned long flags;
5744 int tag;
5745
5746 for (tag = 0; tag < hba->nutrs; tag++) {
5747 lrbp = &hba->lrb[tag];
5748 cmd = lrbp->cmd;
5749 if (!ufshcd_cmd_inflight(cmd) ||
5750 test_bit(SCMD_STATE_COMPLETE, &cmd->state))
5751 continue;
5752
5753 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(cmd));
5754 if (!hwq)
5755 continue;
5756
5757 if (force_compl) {
5758 ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
5759 /*
5760 * For those cmds of which the cqes are not present
5761 * in the cq, complete them explicitly.
5762 */
5763 spin_lock_irqsave(&hwq->cq_lock, flags);
5764 if (cmd && !test_bit(SCMD_STATE_COMPLETE, &cmd->state)) {
5765 set_host_byte(cmd, DID_REQUEUE);
5766 ufshcd_release_scsi_cmd(hba, lrbp);
5767 scsi_done(cmd);
5768 }
5769 spin_unlock_irqrestore(&hwq->cq_lock, flags);
5770 } else {
5771 ufshcd_mcq_poll_cqe_lock(hba, hwq);
5772 }
5773 }
5774 }
5775
5776 /**
5777 * ufshcd_transfer_req_compl - handle SCSI and query command completion
5778 * @hba: per adapter instance
5779 *
5780 * Return:
5781 * IRQ_HANDLED - If interrupt is valid
5782 * IRQ_NONE - If invalid interrupt
5783 */
ufshcd_transfer_req_compl(struct ufs_hba * hba)5784 static irqreturn_t ufshcd_transfer_req_compl(struct ufs_hba *hba)
5785 {
5786 /* Resetting interrupt aggregation counters first and reading the
5787 * DOOR_BELL afterward allows us to handle all the completed requests.
5788 * In order to prevent other interrupts starvation the DB is read once
5789 * after reset. The down side of this solution is the possibility of
5790 * false interrupt if device completes another request after resetting
5791 * aggregation and before reading the DB.
5792 */
5793 if (ufshcd_is_intr_aggr_allowed(hba) &&
5794 !(hba->quirks & UFSHCI_QUIRK_SKIP_RESET_INTR_AGGR))
5795 ufshcd_reset_intr_aggr(hba);
5796
5797 if (ufs_fail_completion(hba))
5798 return IRQ_HANDLED;
5799
5800 /*
5801 * Ignore the ufshcd_poll() return value and return IRQ_HANDLED since we
5802 * do not want polling to trigger spurious interrupt complaints.
5803 */
5804 ufshcd_poll(hba->host, UFSHCD_POLL_FROM_INTERRUPT_CONTEXT);
5805
5806 return IRQ_HANDLED;
5807 }
5808
__ufshcd_write_ee_control(struct ufs_hba * hba,u32 ee_ctrl_mask)5809 int __ufshcd_write_ee_control(struct ufs_hba *hba, u32 ee_ctrl_mask)
5810 {
5811 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
5812 QUERY_ATTR_IDN_EE_CONTROL, 0, 0,
5813 &ee_ctrl_mask);
5814 }
5815
ufshcd_write_ee_control(struct ufs_hba * hba)5816 int ufshcd_write_ee_control(struct ufs_hba *hba)
5817 {
5818 int err;
5819
5820 mutex_lock(&hba->ee_ctrl_mutex);
5821 err = __ufshcd_write_ee_control(hba, hba->ee_ctrl_mask);
5822 mutex_unlock(&hba->ee_ctrl_mutex);
5823 if (err)
5824 dev_err(hba->dev, "%s: failed to write ee control %d\n",
5825 __func__, err);
5826 return err;
5827 }
5828
ufshcd_update_ee_control(struct ufs_hba * hba,u16 * mask,const u16 * other_mask,u16 set,u16 clr)5829 int ufshcd_update_ee_control(struct ufs_hba *hba, u16 *mask,
5830 const u16 *other_mask, u16 set, u16 clr)
5831 {
5832 u16 new_mask, ee_ctrl_mask;
5833 int err = 0;
5834
5835 mutex_lock(&hba->ee_ctrl_mutex);
5836 new_mask = (*mask & ~clr) | set;
5837 ee_ctrl_mask = new_mask | *other_mask;
5838 if (ee_ctrl_mask != hba->ee_ctrl_mask)
5839 err = __ufshcd_write_ee_control(hba, ee_ctrl_mask);
5840 /* Still need to update 'mask' even if 'ee_ctrl_mask' was unchanged */
5841 if (!err) {
5842 hba->ee_ctrl_mask = ee_ctrl_mask;
5843 *mask = new_mask;
5844 }
5845 mutex_unlock(&hba->ee_ctrl_mutex);
5846 return err;
5847 }
5848
5849 /**
5850 * ufshcd_disable_ee - disable exception event
5851 * @hba: per-adapter instance
5852 * @mask: exception event to disable
5853 *
5854 * Disables exception event in the device so that the EVENT_ALERT
5855 * bit is not set.
5856 *
5857 * Return: zero on success, non-zero error value on failure.
5858 */
ufshcd_disable_ee(struct ufs_hba * hba,u16 mask)5859 static inline int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
5860 {
5861 return ufshcd_update_ee_drv_mask(hba, 0, mask);
5862 }
5863
5864 /**
5865 * ufshcd_enable_ee - enable exception event
5866 * @hba: per-adapter instance
5867 * @mask: exception event to enable
5868 *
5869 * Enable corresponding exception event in the device to allow
5870 * device to alert host in critical scenarios.
5871 *
5872 * Return: zero on success, non-zero error value on failure.
5873 */
ufshcd_enable_ee(struct ufs_hba * hba,u16 mask)5874 static inline int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
5875 {
5876 return ufshcd_update_ee_drv_mask(hba, mask, 0);
5877 }
5878
5879 /**
5880 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
5881 * @hba: per-adapter instance
5882 *
5883 * Allow device to manage background operations on its own. Enabling
5884 * this might lead to inconsistent latencies during normal data transfers
5885 * as the device is allowed to manage its own way of handling background
5886 * operations.
5887 *
5888 * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
5889 * < 0 if another error occurred.
5890 */
ufshcd_enable_auto_bkops(struct ufs_hba * hba)5891 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
5892 {
5893 int err = 0;
5894
5895 if (hba->auto_bkops_enabled)
5896 goto out;
5897
5898 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
5899 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5900 if (err) {
5901 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
5902 __func__, err);
5903 goto out;
5904 }
5905
5906 hba->auto_bkops_enabled = true;
5907 trace_ufshcd_auto_bkops_state(hba, "Enabled");
5908
5909 /* No need of URGENT_BKOPS exception from the device */
5910 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5911 if (err)
5912 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
5913 __func__, err);
5914 out:
5915 return err;
5916 }
5917
5918 /**
5919 * ufshcd_disable_auto_bkops - block device in doing background operations
5920 * @hba: per-adapter instance
5921 *
5922 * Disabling background operations improves command response latency but
5923 * has drawback of device moving into critical state where the device is
5924 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
5925 * host is idle so that BKOPS are managed effectively without any negative
5926 * impacts.
5927 *
5928 * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
5929 * < 0 if another error occurred.
5930 */
ufshcd_disable_auto_bkops(struct ufs_hba * hba)5931 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
5932 {
5933 int err = 0;
5934
5935 if (!hba->auto_bkops_enabled)
5936 goto out;
5937
5938 /*
5939 * If host assisted BKOPs is to be enabled, make sure
5940 * urgent bkops exception is allowed.
5941 */
5942 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
5943 if (err) {
5944 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
5945 __func__, err);
5946 goto out;
5947 }
5948
5949 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
5950 QUERY_FLAG_IDN_BKOPS_EN, 0, NULL);
5951 if (err) {
5952 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
5953 __func__, err);
5954 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
5955 goto out;
5956 }
5957
5958 hba->auto_bkops_enabled = false;
5959 trace_ufshcd_auto_bkops_state(hba, "Disabled");
5960 hba->is_urgent_bkops_lvl_checked = false;
5961 out:
5962 return err;
5963 }
5964
5965 /**
5966 * ufshcd_force_reset_auto_bkops - force reset auto bkops state
5967 * @hba: per adapter instance
5968 *
5969 * After a device reset the device may toggle the BKOPS_EN flag
5970 * to default value. The s/w tracking variables should be updated
5971 * as well. This function would change the auto-bkops state based on
5972 * UFSHCD_CAP_KEEP_AUTO_BKOPS_ENABLED_EXCEPT_SUSPEND.
5973 */
ufshcd_force_reset_auto_bkops(struct ufs_hba * hba)5974 static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
5975 {
5976 if (ufshcd_keep_autobkops_enabled_except_suspend(hba)) {
5977 hba->auto_bkops_enabled = false;
5978 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
5979 ufshcd_enable_auto_bkops(hba);
5980 } else {
5981 hba->auto_bkops_enabled = true;
5982 hba->ee_ctrl_mask &= ~MASK_EE_URGENT_BKOPS;
5983 ufshcd_disable_auto_bkops(hba);
5984 }
5985 hba->urgent_bkops_lvl = BKOPS_STATUS_PERF_IMPACT;
5986 hba->is_urgent_bkops_lvl_checked = false;
5987 }
5988
ufshcd_get_bkops_status(struct ufs_hba * hba,u32 * status)5989 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
5990 {
5991 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
5992 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
5993 }
5994
5995 /**
5996 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
5997 * @hba: per-adapter instance
5998 *
5999 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
6000 * flag in the device to permit background operations if the device
6001 * bkops_status is greater than or equal to the "hba->urgent_bkops_lvl",
6002 * disable otherwise.
6003 *
6004 * Return: 0 for success, non-zero in case of failure.
6005 *
6006 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
6007 * to know whether auto bkops is enabled or disabled after this function
6008 * returns control to it.
6009 */
ufshcd_bkops_ctrl(struct ufs_hba * hba)6010 static int ufshcd_bkops_ctrl(struct ufs_hba *hba)
6011 {
6012 enum bkops_status status = hba->urgent_bkops_lvl;
6013 u32 curr_status = 0;
6014 int err;
6015
6016 err = ufshcd_get_bkops_status(hba, &curr_status);
6017 if (err) {
6018 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
6019 __func__, err);
6020 goto out;
6021 } else if (curr_status > BKOPS_STATUS_MAX) {
6022 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
6023 __func__, curr_status);
6024 err = -EINVAL;
6025 goto out;
6026 }
6027
6028 if (curr_status >= status)
6029 err = ufshcd_enable_auto_bkops(hba);
6030 else
6031 err = ufshcd_disable_auto_bkops(hba);
6032 out:
6033 return err;
6034 }
6035
ufshcd_get_ee_status(struct ufs_hba * hba,u32 * status)6036 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
6037 {
6038 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6039 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
6040 }
6041
ufshcd_bkops_exception_event_handler(struct ufs_hba * hba)6042 static void ufshcd_bkops_exception_event_handler(struct ufs_hba *hba)
6043 {
6044 int err;
6045 u32 curr_status = 0;
6046
6047 if (hba->is_urgent_bkops_lvl_checked)
6048 goto enable_auto_bkops;
6049
6050 err = ufshcd_get_bkops_status(hba, &curr_status);
6051 if (err) {
6052 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
6053 __func__, err);
6054 goto out;
6055 }
6056
6057 /*
6058 * We are seeing that some devices are raising the urgent bkops
6059 * exception events even when BKOPS status doesn't indicate performace
6060 * impacted or critical. Handle these device by determining their urgent
6061 * bkops status at runtime.
6062 */
6063 if (curr_status < BKOPS_STATUS_PERF_IMPACT) {
6064 dev_err(hba->dev, "%s: device raised urgent BKOPS exception for bkops status %d\n",
6065 __func__, curr_status);
6066 /* update the current status as the urgent bkops level */
6067 hba->urgent_bkops_lvl = curr_status;
6068 hba->is_urgent_bkops_lvl_checked = true;
6069 }
6070
6071 enable_auto_bkops:
6072 err = ufshcd_enable_auto_bkops(hba);
6073 out:
6074 if (err < 0)
6075 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
6076 __func__, err);
6077 }
6078
6079 /*
6080 * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
6081 * < 0 if another error occurred.
6082 */
ufshcd_read_device_lvl_exception_id(struct ufs_hba * hba,u64 * exception_id)6083 int ufshcd_read_device_lvl_exception_id(struct ufs_hba *hba, u64 *exception_id)
6084 {
6085 struct utp_upiu_query_v4_0 *upiu_resp;
6086 struct ufs_query_req *request = NULL;
6087 struct ufs_query_res *response = NULL;
6088 int err;
6089
6090 if (hba->dev_info.wspecversion < 0x410)
6091 return -EOPNOTSUPP;
6092
6093 ufshcd_hold(hba);
6094 mutex_lock(&hba->dev_cmd.lock);
6095
6096 ufshcd_init_query(hba, &request, &response,
6097 UPIU_QUERY_OPCODE_READ_ATTR,
6098 QUERY_ATTR_IDN_DEV_LVL_EXCEPTION_ID, 0, 0);
6099
6100 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
6101
6102 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, dev_cmd_timeout);
6103
6104 if (err) {
6105 dev_err(hba->dev, "%s: failed to read device level exception %d\n",
6106 __func__, err);
6107 goto out;
6108 }
6109
6110 upiu_resp = (struct utp_upiu_query_v4_0 *)response;
6111 *exception_id = get_unaligned_be64(&upiu_resp->osf3);
6112 out:
6113 mutex_unlock(&hba->dev_cmd.lock);
6114 ufshcd_release(hba);
6115
6116 return err;
6117 }
6118
__ufshcd_wb_toggle(struct ufs_hba * hba,bool set,enum flag_idn idn)6119 static int __ufshcd_wb_toggle(struct ufs_hba *hba, bool set, enum flag_idn idn)
6120 {
6121 u8 index;
6122 enum query_opcode opcode = set ? UPIU_QUERY_OPCODE_SET_FLAG :
6123 UPIU_QUERY_OPCODE_CLEAR_FLAG;
6124
6125 index = ufshcd_wb_get_query_index(hba);
6126 return ufshcd_query_flag_retry(hba, opcode, idn, index, NULL);
6127 }
6128
ufshcd_wb_toggle(struct ufs_hba * hba,bool enable)6129 int ufshcd_wb_toggle(struct ufs_hba *hba, bool enable)
6130 {
6131 int ret;
6132
6133 if (!ufshcd_is_wb_allowed(hba) ||
6134 hba->dev_info.wb_enabled == enable)
6135 return 0;
6136
6137 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_EN);
6138 if (ret) {
6139 dev_err(hba->dev, "%s: Write Booster %s failed %d\n",
6140 __func__, enable ? "enabling" : "disabling", ret);
6141 return ret;
6142 }
6143
6144 hba->dev_info.wb_enabled = enable;
6145 dev_dbg(hba->dev, "%s: Write Booster %s\n",
6146 __func__, enable ? "enabled" : "disabled");
6147
6148 return ret;
6149 }
6150
ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba * hba,bool enable)6151 static void ufshcd_wb_toggle_buf_flush_during_h8(struct ufs_hba *hba,
6152 bool enable)
6153 {
6154 int ret;
6155
6156 ret = __ufshcd_wb_toggle(hba, enable,
6157 QUERY_FLAG_IDN_WB_BUFF_FLUSH_DURING_HIBERN8);
6158 if (ret) {
6159 dev_err(hba->dev, "%s: WB-Buf Flush during H8 %s failed %d\n",
6160 __func__, enable ? "enabling" : "disabling", ret);
6161 return;
6162 }
6163 dev_dbg(hba->dev, "%s: WB-Buf Flush during H8 %s\n",
6164 __func__, enable ? "enabled" : "disabled");
6165 }
6166
ufshcd_wb_toggle_buf_flush(struct ufs_hba * hba,bool enable)6167 int ufshcd_wb_toggle_buf_flush(struct ufs_hba *hba, bool enable)
6168 {
6169 int ret;
6170
6171 if (!ufshcd_is_wb_allowed(hba) ||
6172 hba->dev_info.wb_buf_flush_enabled == enable)
6173 return 0;
6174
6175 ret = __ufshcd_wb_toggle(hba, enable, QUERY_FLAG_IDN_WB_BUFF_FLUSH_EN);
6176 if (ret) {
6177 dev_err(hba->dev, "%s: WB-Buf Flush %s failed %d\n",
6178 __func__, enable ? "enabling" : "disabling", ret);
6179 return ret;
6180 }
6181
6182 hba->dev_info.wb_buf_flush_enabled = enable;
6183 dev_dbg(hba->dev, "%s: WB-Buf Flush %s\n",
6184 __func__, enable ? "enabled" : "disabled");
6185
6186 return ret;
6187 }
6188
ufshcd_wb_set_resize_en(struct ufs_hba * hba,enum wb_resize_en en_mode)6189 int ufshcd_wb_set_resize_en(struct ufs_hba *hba, enum wb_resize_en en_mode)
6190 {
6191 int ret;
6192 u8 index;
6193
6194 index = ufshcd_wb_get_query_index(hba);
6195 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
6196 QUERY_ATTR_IDN_WB_BUF_RESIZE_EN, index, 0, &en_mode);
6197 if (ret)
6198 dev_err(hba->dev, "%s: Enable WB buf resize operation failed %d\n",
6199 __func__, ret);
6200
6201 return ret;
6202 }
6203
ufshcd_wb_curr_buff_threshold_check(struct ufs_hba * hba,u32 avail_buf)6204 static bool ufshcd_wb_curr_buff_threshold_check(struct ufs_hba *hba,
6205 u32 avail_buf)
6206 {
6207 u32 cur_buf;
6208 int ret;
6209 u8 index;
6210
6211 index = ufshcd_wb_get_query_index(hba);
6212 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6213 QUERY_ATTR_IDN_CURR_WB_BUFF_SIZE,
6214 index, 0, &cur_buf);
6215 if (ret) {
6216 dev_err(hba->dev, "%s: dCurWriteBoosterBufferSize read failed %d\n",
6217 __func__, ret);
6218 return false;
6219 }
6220
6221 if (!cur_buf) {
6222 dev_info(hba->dev, "dCurWBBuf: %d WB disabled until free-space is available\n",
6223 cur_buf);
6224 return false;
6225 }
6226 /* Let it continue to flush when available buffer exceeds threshold */
6227 return avail_buf < hba->vps->wb_flush_threshold;
6228 }
6229
ufshcd_wb_force_disable(struct ufs_hba * hba)6230 static void ufshcd_wb_force_disable(struct ufs_hba *hba)
6231 {
6232 if (ufshcd_is_wb_buf_flush_allowed(hba))
6233 ufshcd_wb_toggle_buf_flush(hba, false);
6234
6235 ufshcd_wb_toggle_buf_flush_during_h8(hba, false);
6236 ufshcd_wb_toggle(hba, false);
6237 hba->caps &= ~UFSHCD_CAP_WB_EN;
6238
6239 dev_info(hba->dev, "%s: WB force disabled\n", __func__);
6240 }
6241
ufshcd_is_wb_buf_lifetime_available(struct ufs_hba * hba)6242 static bool ufshcd_is_wb_buf_lifetime_available(struct ufs_hba *hba)
6243 {
6244 u32 lifetime;
6245 int ret;
6246 u8 index;
6247
6248 index = ufshcd_wb_get_query_index(hba);
6249 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6250 QUERY_ATTR_IDN_WB_BUFF_LIFE_TIME_EST,
6251 index, 0, &lifetime);
6252 if (ret) {
6253 dev_err(hba->dev,
6254 "%s: bWriteBoosterBufferLifeTimeEst read failed %d\n",
6255 __func__, ret);
6256 return false;
6257 }
6258
6259 if (lifetime == UFS_WB_EXCEED_LIFETIME) {
6260 dev_err(hba->dev, "%s: WB buf lifetime is exhausted 0x%02X\n",
6261 __func__, lifetime);
6262 return false;
6263 }
6264
6265 dev_dbg(hba->dev, "%s: WB buf lifetime is 0x%02X\n",
6266 __func__, lifetime);
6267
6268 return true;
6269 }
6270
ufshcd_wb_need_flush(struct ufs_hba * hba)6271 static bool ufshcd_wb_need_flush(struct ufs_hba *hba)
6272 {
6273 int ret;
6274 u32 avail_buf;
6275 u8 index;
6276
6277 if (!ufshcd_is_wb_allowed(hba))
6278 return false;
6279
6280 if (!ufshcd_is_wb_buf_lifetime_available(hba)) {
6281 ufshcd_wb_force_disable(hba);
6282 return false;
6283 }
6284
6285 /*
6286 * With user-space reduction enabled, it's enough to enable flush
6287 * by checking only the available buffer. The threshold
6288 * defined here is > 90% full.
6289 * With user-space preserved enabled, the current-buffer
6290 * should be checked too because the wb buffer size can reduce
6291 * when disk tends to be full. This info is provided by current
6292 * buffer (dCurrentWriteBoosterBufferSize).
6293 */
6294 index = ufshcd_wb_get_query_index(hba);
6295 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
6296 QUERY_ATTR_IDN_AVAIL_WB_BUFF_SIZE,
6297 index, 0, &avail_buf);
6298 if (ret) {
6299 dev_warn(hba->dev, "%s: dAvailableWriteBoosterBufferSize read failed %d\n",
6300 __func__, ret);
6301 return false;
6302 }
6303
6304 if (!hba->dev_info.b_presrv_uspc_en)
6305 return avail_buf <= UFS_WB_BUF_REMAIN_PERCENT(10);
6306
6307 return ufshcd_wb_curr_buff_threshold_check(hba, avail_buf);
6308 }
6309
ufshcd_rpm_dev_flush_recheck_work(struct work_struct * work)6310 static void ufshcd_rpm_dev_flush_recheck_work(struct work_struct *work)
6311 {
6312 struct ufs_hba *hba = container_of(to_delayed_work(work),
6313 struct ufs_hba,
6314 rpm_dev_flush_recheck_work);
6315 /*
6316 * To prevent unnecessary VCC power drain after device finishes
6317 * WriteBooster buffer flush or Auto BKOPs, force runtime resume
6318 * after a certain delay to recheck the threshold by next runtime
6319 * suspend.
6320 */
6321 ufshcd_rpm_get_sync(hba);
6322 ufshcd_rpm_put_sync(hba);
6323 }
6324
6325 /**
6326 * ufshcd_exception_event_handler - handle exceptions raised by device
6327 * @work: pointer to work data
6328 *
6329 * Read bExceptionEventStatus attribute from the device and handle the
6330 * exception event accordingly.
6331 */
ufshcd_exception_event_handler(struct work_struct * work)6332 static void ufshcd_exception_event_handler(struct work_struct *work)
6333 {
6334 struct ufs_hba *hba;
6335 int err;
6336 u32 status = 0;
6337 hba = container_of(work, struct ufs_hba, eeh_work);
6338
6339 err = ufshcd_get_ee_status(hba, &status);
6340 if (err) {
6341 dev_err(hba->dev, "%s: failed to get exception status %d\n",
6342 __func__, err);
6343 return;
6344 }
6345
6346 trace_ufshcd_exception_event(hba, status);
6347
6348 if (status & hba->ee_drv_mask & MASK_EE_URGENT_BKOPS)
6349 ufshcd_bkops_exception_event_handler(hba);
6350
6351 if (status & hba->ee_drv_mask & MASK_EE_URGENT_TEMP)
6352 ufs_hwmon_notify_event(hba, status & MASK_EE_URGENT_TEMP);
6353
6354 if (status & hba->ee_drv_mask & MASK_EE_HEALTH_CRITICAL) {
6355 hba->critical_health_count++;
6356 sysfs_notify(&hba->dev->kobj, NULL, "critical_health");
6357 }
6358
6359 if (status & hba->ee_drv_mask & MASK_EE_DEV_LVL_EXCEPTION) {
6360 atomic_inc(&hba->dev_lvl_exception_count);
6361 sysfs_notify(&hba->dev->kobj, NULL, "device_lvl_exception_count");
6362 }
6363
6364 ufs_debugfs_exception_event(hba, status);
6365 }
6366
6367 /* Complete requests that have door-bell cleared */
ufshcd_complete_requests(struct ufs_hba * hba,bool force_compl)6368 static void ufshcd_complete_requests(struct ufs_hba *hba, bool force_compl)
6369 {
6370 if (hba->mcq_enabled)
6371 ufshcd_mcq_compl_pending_transfer(hba, force_compl);
6372 else
6373 ufshcd_transfer_req_compl(hba);
6374
6375 ufshcd_tmc_handler(hba);
6376 }
6377
6378 /**
6379 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
6380 * to recover from the DL NAC errors or not.
6381 * @hba: per-adapter instance
6382 *
6383 * Return: true if error handling is required, false otherwise.
6384 */
ufshcd_quirk_dl_nac_errors(struct ufs_hba * hba)6385 static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
6386 {
6387 unsigned long flags;
6388 bool err_handling = true;
6389
6390 spin_lock_irqsave(hba->host->host_lock, flags);
6391 /*
6392 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
6393 * device fatal error and/or DL NAC & REPLAY timeout errors.
6394 */
6395 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
6396 goto out;
6397
6398 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
6399 ((hba->saved_err & UIC_ERROR) &&
6400 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
6401 goto out;
6402
6403 if ((hba->saved_err & UIC_ERROR) &&
6404 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
6405 int err;
6406 /*
6407 * wait for 50ms to see if we can get any other errors or not.
6408 */
6409 spin_unlock_irqrestore(hba->host->host_lock, flags);
6410 msleep(50);
6411 spin_lock_irqsave(hba->host->host_lock, flags);
6412
6413 /*
6414 * now check if we have got any other severe errors other than
6415 * DL NAC error?
6416 */
6417 if ((hba->saved_err & INT_FATAL_ERRORS) ||
6418 ((hba->saved_err & UIC_ERROR) &&
6419 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
6420 goto out;
6421
6422 /*
6423 * As DL NAC is the only error received so far, send out NOP
6424 * command to confirm if link is still active or not.
6425 * - If we don't get any response then do error recovery.
6426 * - If we get response then clear the DL NAC error bit.
6427 */
6428
6429 spin_unlock_irqrestore(hba->host->host_lock, flags);
6430 err = ufshcd_verify_dev_init(hba);
6431 spin_lock_irqsave(hba->host->host_lock, flags);
6432
6433 if (err)
6434 goto out;
6435
6436 /* Link seems to be alive hence ignore the DL NAC errors */
6437 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
6438 hba->saved_err &= ~UIC_ERROR;
6439 /* clear NAC error */
6440 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6441 if (!hba->saved_uic_err)
6442 err_handling = false;
6443 }
6444 out:
6445 spin_unlock_irqrestore(hba->host->host_lock, flags);
6446 return err_handling;
6447 }
6448
6449 /* host lock must be held before calling this func */
ufshcd_is_saved_err_fatal(struct ufs_hba * hba)6450 static inline bool ufshcd_is_saved_err_fatal(struct ufs_hba *hba)
6451 {
6452 return (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR) ||
6453 (hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK));
6454 }
6455
ufshcd_schedule_eh_work(struct ufs_hba * hba)6456 void ufshcd_schedule_eh_work(struct ufs_hba *hba)
6457 {
6458 lockdep_assert_held(hba->host->host_lock);
6459
6460 /* handle fatal errors only when link is not in error state */
6461 if (hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6462 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6463 ufshcd_is_saved_err_fatal(hba))
6464 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_FATAL;
6465 else
6466 hba->ufshcd_state = UFSHCD_STATE_EH_SCHEDULED_NON_FATAL;
6467 queue_work(hba->eh_wq, &hba->eh_work);
6468 }
6469 }
6470
ufshcd_force_error_recovery(struct ufs_hba * hba)6471 void ufshcd_force_error_recovery(struct ufs_hba *hba)
6472 {
6473 spin_lock_irq(hba->host->host_lock);
6474 hba->force_reset = true;
6475 ufshcd_schedule_eh_work(hba);
6476 spin_unlock_irq(hba->host->host_lock);
6477 }
6478 EXPORT_SYMBOL_GPL(ufshcd_force_error_recovery);
6479
ufshcd_clk_scaling_allow(struct ufs_hba * hba,bool allow)6480 static void ufshcd_clk_scaling_allow(struct ufs_hba *hba, bool allow)
6481 {
6482 mutex_lock(&hba->wb_mutex);
6483 down_write(&hba->clk_scaling_lock);
6484 hba->clk_scaling.is_allowed = allow;
6485 up_write(&hba->clk_scaling_lock);
6486 mutex_unlock(&hba->wb_mutex);
6487 }
6488
ufshcd_clk_scaling_suspend(struct ufs_hba * hba,bool suspend)6489 static void ufshcd_clk_scaling_suspend(struct ufs_hba *hba, bool suspend)
6490 {
6491 if (suspend) {
6492 if (hba->clk_scaling.is_enabled)
6493 ufshcd_suspend_clkscaling(hba);
6494 ufshcd_clk_scaling_allow(hba, false);
6495 } else {
6496 ufshcd_clk_scaling_allow(hba, true);
6497 if (hba->clk_scaling.is_enabled)
6498 ufshcd_resume_clkscaling(hba);
6499 }
6500 }
6501
ufshcd_err_handling_prepare(struct ufs_hba * hba)6502 static void ufshcd_err_handling_prepare(struct ufs_hba *hba)
6503 {
6504 ufshcd_rpm_get_sync(hba);
6505 if (pm_runtime_status_suspended(&hba->ufs_device_wlun->sdev_gendev) ||
6506 hba->is_sys_suspended) {
6507 enum ufs_pm_op pm_op;
6508
6509 /*
6510 * Don't assume anything of resume, if
6511 * resume fails, irq and clocks can be OFF, and powers
6512 * can be OFF or in LPM.
6513 */
6514 ufshcd_setup_hba_vreg(hba, true);
6515 ufshcd_enable_irq(hba);
6516 ufshcd_setup_vreg(hba, true);
6517 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
6518 ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
6519 ufshcd_hold(hba);
6520 if (!ufshcd_is_clkgating_allowed(hba))
6521 ufshcd_setup_clocks(hba, true);
6522 pm_op = hba->is_sys_suspended ? UFS_SYSTEM_PM : UFS_RUNTIME_PM;
6523 ufshcd_vops_resume(hba, pm_op);
6524 } else {
6525 ufshcd_hold(hba);
6526 if (ufshcd_is_clkscaling_supported(hba) &&
6527 hba->clk_scaling.is_enabled)
6528 ufshcd_suspend_clkscaling(hba);
6529 ufshcd_clk_scaling_allow(hba, false);
6530 }
6531 /* Wait for ongoing ufshcd_queuecommand() calls to finish. */
6532 blk_mq_quiesce_tagset(&hba->host->tag_set);
6533 cancel_work_sync(&hba->eeh_work);
6534 }
6535
ufshcd_err_handling_unprepare(struct ufs_hba * hba)6536 static void ufshcd_err_handling_unprepare(struct ufs_hba *hba)
6537 {
6538 blk_mq_unquiesce_tagset(&hba->host->tag_set);
6539 ufshcd_release(hba);
6540 if (ufshcd_is_clkscaling_supported(hba))
6541 ufshcd_clk_scaling_suspend(hba, false);
6542 ufshcd_rpm_put(hba);
6543 }
6544
ufshcd_err_handling_should_stop(struct ufs_hba * hba)6545 static inline bool ufshcd_err_handling_should_stop(struct ufs_hba *hba)
6546 {
6547 return (!hba->is_powered || hba->shutting_down ||
6548 !hba->ufs_device_wlun ||
6549 hba->ufshcd_state == UFSHCD_STATE_ERROR ||
6550 (!(hba->saved_err || hba->saved_uic_err || hba->force_reset ||
6551 ufshcd_is_link_broken(hba))));
6552 }
6553
6554 #ifdef CONFIG_PM
ufshcd_recover_pm_error(struct ufs_hba * hba)6555 static void ufshcd_recover_pm_error(struct ufs_hba *hba)
6556 {
6557 struct Scsi_Host *shost = hba->host;
6558 struct scsi_device *sdev;
6559 struct request_queue *q;
6560 int ret;
6561
6562 hba->is_sys_suspended = false;
6563 /*
6564 * Set RPM status of wlun device to RPM_ACTIVE,
6565 * this also clears its runtime error.
6566 */
6567 ret = pm_runtime_set_active(&hba->ufs_device_wlun->sdev_gendev);
6568
6569 /* hba device might have a runtime error otherwise */
6570 if (ret)
6571 ret = pm_runtime_set_active(hba->dev);
6572 /*
6573 * If wlun device had runtime error, we also need to resume those
6574 * consumer scsi devices in case any of them has failed to be
6575 * resumed due to supplier runtime resume failure. This is to unblock
6576 * blk_queue_enter in case there are bios waiting inside it.
6577 */
6578 if (!ret) {
6579 shost_for_each_device(sdev, shost) {
6580 q = sdev->request_queue;
6581 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
6582 q->rpm_status == RPM_SUSPENDING))
6583 pm_request_resume(q->dev);
6584 }
6585 }
6586 }
6587 #else
ufshcd_recover_pm_error(struct ufs_hba * hba)6588 static inline void ufshcd_recover_pm_error(struct ufs_hba *hba)
6589 {
6590 }
6591 #endif
6592
ufshcd_is_pwr_mode_restore_needed(struct ufs_hba * hba)6593 static bool ufshcd_is_pwr_mode_restore_needed(struct ufs_hba *hba)
6594 {
6595 struct ufs_pa_layer_attr *pwr_info = &hba->pwr_info;
6596 u32 mode;
6597
6598 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_PWRMODE), &mode);
6599
6600 if (pwr_info->pwr_rx != ((mode >> PWRMODE_RX_OFFSET) & PWRMODE_MASK))
6601 return true;
6602
6603 if (pwr_info->pwr_tx != (mode & PWRMODE_MASK))
6604 return true;
6605
6606 return false;
6607 }
6608
ufshcd_abort_one(struct request * rq,void * priv)6609 static bool ufshcd_abort_one(struct request *rq, void *priv)
6610 {
6611 int *ret = priv;
6612 u32 tag = rq->tag;
6613 struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
6614 struct scsi_device *sdev = cmd->device;
6615 struct Scsi_Host *shost = sdev->host;
6616 struct ufs_hba *hba = shost_priv(shost);
6617
6618 *ret = ufshcd_try_to_abort_task(hba, tag);
6619 dev_err(hba->dev, "Aborting tag %d / CDB %#02x %s\n", tag,
6620 hba->lrb[tag].cmd ? hba->lrb[tag].cmd->cmnd[0] : -1,
6621 *ret ? "failed" : "succeeded");
6622
6623 return *ret == 0;
6624 }
6625
6626 /**
6627 * ufshcd_abort_all - Abort all pending commands.
6628 * @hba: Host bus adapter pointer.
6629 *
6630 * Return: true if and only if the host controller needs to be reset.
6631 */
ufshcd_abort_all(struct ufs_hba * hba)6632 static bool ufshcd_abort_all(struct ufs_hba *hba)
6633 {
6634 int tag, ret = 0;
6635
6636 blk_mq_tagset_busy_iter(&hba->host->tag_set, ufshcd_abort_one, &ret);
6637 if (ret)
6638 goto out;
6639
6640 /* Clear pending task management requests */
6641 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
6642 ret = ufshcd_clear_tm_cmd(hba, tag);
6643 if (ret)
6644 goto out;
6645 }
6646
6647 out:
6648 /* Complete the requests that are cleared by s/w */
6649 ufshcd_complete_requests(hba, false);
6650
6651 return ret != 0;
6652 }
6653
6654 /**
6655 * ufshcd_err_handler - handle UFS errors that require s/w attention
6656 * @work: pointer to work structure
6657 */
ufshcd_err_handler(struct work_struct * work)6658 static void ufshcd_err_handler(struct work_struct *work)
6659 {
6660 int retries = MAX_ERR_HANDLER_RETRIES;
6661 struct ufs_hba *hba;
6662 unsigned long flags;
6663 bool needs_restore;
6664 bool needs_reset;
6665 int pmc_err;
6666
6667 hba = container_of(work, struct ufs_hba, eh_work);
6668
6669 dev_info(hba->dev,
6670 "%s started; HBA state %s; powered %d; shutting down %d; saved_err = 0x%x; saved_uic_err = 0x%x; force_reset = %d%s\n",
6671 __func__, ufshcd_state_name[hba->ufshcd_state],
6672 hba->is_powered, hba->shutting_down, hba->saved_err,
6673 hba->saved_uic_err, hba->force_reset,
6674 ufshcd_is_link_broken(hba) ? "; link is broken" : "");
6675
6676 down(&hba->host_sem);
6677 spin_lock_irqsave(hba->host->host_lock, flags);
6678 if (ufshcd_err_handling_should_stop(hba)) {
6679 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6680 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6681 spin_unlock_irqrestore(hba->host->host_lock, flags);
6682 up(&hba->host_sem);
6683 return;
6684 }
6685 spin_unlock_irqrestore(hba->host->host_lock, flags);
6686
6687 ufshcd_rpm_get_noresume(hba);
6688 if (hba->pm_op_in_progress) {
6689 ufshcd_link_recovery(hba);
6690 ufshcd_rpm_put(hba);
6691 return;
6692 }
6693 ufshcd_rpm_put(hba);
6694
6695 ufshcd_err_handling_prepare(hba);
6696
6697 spin_lock_irqsave(hba->host->host_lock, flags);
6698 ufshcd_set_eh_in_progress(hba);
6699 spin_unlock_irqrestore(hba->host->host_lock, flags);
6700
6701 /* Complete requests that have door-bell cleared by h/w */
6702 ufshcd_complete_requests(hba, false);
6703 spin_lock_irqsave(hba->host->host_lock, flags);
6704 again:
6705 needs_restore = false;
6706 needs_reset = false;
6707
6708 if (hba->ufshcd_state != UFSHCD_STATE_ERROR)
6709 hba->ufshcd_state = UFSHCD_STATE_RESET;
6710 /*
6711 * A full reset and restore might have happened after preparation
6712 * is finished, double check whether we should stop.
6713 */
6714 if (ufshcd_err_handling_should_stop(hba))
6715 goto skip_err_handling;
6716
6717 if ((hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) &&
6718 !hba->force_reset) {
6719 bool ret;
6720
6721 spin_unlock_irqrestore(hba->host->host_lock, flags);
6722 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
6723 ret = ufshcd_quirk_dl_nac_errors(hba);
6724 spin_lock_irqsave(hba->host->host_lock, flags);
6725 if (!ret && ufshcd_err_handling_should_stop(hba))
6726 goto skip_err_handling;
6727 }
6728
6729 if ((hba->saved_err & (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6730 (hba->saved_uic_err &&
6731 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6732 bool pr_prdt = !!(hba->saved_err & SYSTEM_BUS_FATAL_ERROR);
6733
6734 spin_unlock_irqrestore(hba->host->host_lock, flags);
6735 ufshcd_print_host_state(hba);
6736 ufshcd_print_pwr_info(hba);
6737 ufshcd_print_evt_hist(hba);
6738 ufshcd_print_tmrs(hba, hba->outstanding_tasks);
6739 ufshcd_print_trs_all(hba, pr_prdt);
6740 spin_lock_irqsave(hba->host->host_lock, flags);
6741 }
6742
6743 /*
6744 * if host reset is required then skip clearing the pending
6745 * transfers forcefully because they will get cleared during
6746 * host reset and restore
6747 */
6748 if (hba->force_reset || ufshcd_is_link_broken(hba) ||
6749 ufshcd_is_saved_err_fatal(hba) ||
6750 ((hba->saved_err & UIC_ERROR) &&
6751 (hba->saved_uic_err & (UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
6752 UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))) {
6753 needs_reset = true;
6754 goto do_reset;
6755 }
6756
6757 /*
6758 * If LINERESET was caught, UFS might have been put to PWM mode,
6759 * check if power mode restore is needed.
6760 */
6761 if (hba->saved_uic_err & UFSHCD_UIC_PA_GENERIC_ERROR) {
6762 hba->saved_uic_err &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6763 if (!hba->saved_uic_err)
6764 hba->saved_err &= ~UIC_ERROR;
6765 spin_unlock_irqrestore(hba->host->host_lock, flags);
6766 if (ufshcd_is_pwr_mode_restore_needed(hba))
6767 needs_restore = true;
6768 spin_lock_irqsave(hba->host->host_lock, flags);
6769 if (!hba->saved_err && !needs_restore)
6770 goto skip_err_handling;
6771 }
6772
6773 hba->silence_err_logs = true;
6774 /* release lock as clear command might sleep */
6775 spin_unlock_irqrestore(hba->host->host_lock, flags);
6776
6777 needs_reset = ufshcd_abort_all(hba);
6778
6779 spin_lock_irqsave(hba->host->host_lock, flags);
6780 hba->silence_err_logs = false;
6781 if (needs_reset)
6782 goto do_reset;
6783
6784 /*
6785 * After all reqs and tasks are cleared from doorbell,
6786 * now it is safe to retore power mode.
6787 */
6788 if (needs_restore) {
6789 spin_unlock_irqrestore(hba->host->host_lock, flags);
6790 /*
6791 * Hold the scaling lock just in case dev cmds
6792 * are sent via bsg and/or sysfs.
6793 */
6794 down_write(&hba->clk_scaling_lock);
6795 hba->force_pmc = true;
6796 pmc_err = ufshcd_config_pwr_mode(hba, &(hba->pwr_info));
6797 if (pmc_err) {
6798 needs_reset = true;
6799 dev_err(hba->dev, "%s: Failed to restore power mode, err = %d\n",
6800 __func__, pmc_err);
6801 }
6802 hba->force_pmc = false;
6803 ufshcd_print_pwr_info(hba);
6804 up_write(&hba->clk_scaling_lock);
6805 spin_lock_irqsave(hba->host->host_lock, flags);
6806 }
6807
6808 do_reset:
6809 /* Fatal errors need reset */
6810 if (needs_reset) {
6811 int err;
6812
6813 hba->force_reset = false;
6814 spin_unlock_irqrestore(hba->host->host_lock, flags);
6815 err = ufshcd_reset_and_restore(hba);
6816 if (err)
6817 dev_err(hba->dev, "%s: reset and restore failed with err %d\n",
6818 __func__, err);
6819 else
6820 ufshcd_recover_pm_error(hba);
6821 spin_lock_irqsave(hba->host->host_lock, flags);
6822 }
6823
6824 skip_err_handling:
6825 if (!needs_reset) {
6826 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
6827 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
6828 if (hba->saved_err || hba->saved_uic_err)
6829 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
6830 __func__, hba->saved_err, hba->saved_uic_err);
6831 }
6832 /* Exit in an operational state or dead */
6833 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
6834 hba->ufshcd_state != UFSHCD_STATE_ERROR) {
6835 if (--retries)
6836 goto again;
6837 hba->ufshcd_state = UFSHCD_STATE_ERROR;
6838 }
6839 ufshcd_clear_eh_in_progress(hba);
6840 spin_unlock_irqrestore(hba->host->host_lock, flags);
6841 ufshcd_err_handling_unprepare(hba);
6842 up(&hba->host_sem);
6843
6844 dev_info(hba->dev, "%s finished; HBA state %s\n", __func__,
6845 ufshcd_state_name[hba->ufshcd_state]);
6846 }
6847
6848 /**
6849 * ufshcd_update_uic_error - check and set fatal UIC error flags.
6850 * @hba: per-adapter instance
6851 *
6852 * Return:
6853 * IRQ_HANDLED - If interrupt is valid
6854 * IRQ_NONE - If invalid interrupt
6855 */
ufshcd_update_uic_error(struct ufs_hba * hba)6856 static irqreturn_t ufshcd_update_uic_error(struct ufs_hba *hba)
6857 {
6858 u32 reg;
6859 irqreturn_t retval = IRQ_NONE;
6860
6861 /* PHY layer error */
6862 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_PHY_ADAPTER_LAYER);
6863 if ((reg & UIC_PHY_ADAPTER_LAYER_ERROR) &&
6864 (reg & UIC_PHY_ADAPTER_LAYER_ERROR_CODE_MASK)) {
6865 ufshcd_update_evt_hist(hba, UFS_EVT_PA_ERR, reg);
6866 /*
6867 * To know whether this error is fatal or not, DB timeout
6868 * must be checked but this error is handled separately.
6869 */
6870 if (reg & UIC_PHY_ADAPTER_LAYER_LANE_ERR_MASK)
6871 dev_dbg(hba->dev, "%s: UIC Lane error reported\n",
6872 __func__);
6873
6874 /* Got a LINERESET indication. */
6875 if (reg & UIC_PHY_ADAPTER_LAYER_GENERIC_ERROR) {
6876 struct uic_command *cmd = NULL;
6877
6878 hba->uic_error |= UFSHCD_UIC_PA_GENERIC_ERROR;
6879 if (hba->uic_async_done && hba->active_uic_cmd)
6880 cmd = hba->active_uic_cmd;
6881 /*
6882 * Ignore the LINERESET during power mode change
6883 * operation via DME_SET command.
6884 */
6885 if (cmd && (cmd->command == UIC_CMD_DME_SET))
6886 hba->uic_error &= ~UFSHCD_UIC_PA_GENERIC_ERROR;
6887 }
6888 retval |= IRQ_HANDLED;
6889 }
6890
6891 /* PA_INIT_ERROR is fatal and needs UIC reset */
6892 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
6893 if ((reg & UIC_DATA_LINK_LAYER_ERROR) &&
6894 (reg & UIC_DATA_LINK_LAYER_ERROR_CODE_MASK)) {
6895 ufshcd_update_evt_hist(hba, UFS_EVT_DL_ERR, reg);
6896
6897 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
6898 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
6899 else if (hba->dev_quirks &
6900 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
6901 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
6902 hba->uic_error |=
6903 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
6904 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
6905 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
6906 }
6907 retval |= IRQ_HANDLED;
6908 }
6909
6910 /* UIC NL/TL/DME errors needs software retry */
6911 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
6912 if ((reg & UIC_NETWORK_LAYER_ERROR) &&
6913 (reg & UIC_NETWORK_LAYER_ERROR_CODE_MASK)) {
6914 ufshcd_update_evt_hist(hba, UFS_EVT_NL_ERR, reg);
6915 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
6916 retval |= IRQ_HANDLED;
6917 }
6918
6919 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
6920 if ((reg & UIC_TRANSPORT_LAYER_ERROR) &&
6921 (reg & UIC_TRANSPORT_LAYER_ERROR_CODE_MASK)) {
6922 ufshcd_update_evt_hist(hba, UFS_EVT_TL_ERR, reg);
6923 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
6924 retval |= IRQ_HANDLED;
6925 }
6926
6927 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
6928 if ((reg & UIC_DME_ERROR) &&
6929 (reg & UIC_DME_ERROR_CODE_MASK)) {
6930 ufshcd_update_evt_hist(hba, UFS_EVT_DME_ERR, reg);
6931 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
6932 retval |= IRQ_HANDLED;
6933 }
6934
6935 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
6936 __func__, hba->uic_error);
6937 return retval;
6938 }
6939
6940 /**
6941 * ufshcd_check_errors - Check for errors that need s/w attention
6942 * @hba: per-adapter instance
6943 * @intr_status: interrupt status generated by the controller
6944 *
6945 * Return:
6946 * IRQ_HANDLED - If interrupt is valid
6947 * IRQ_NONE - If invalid interrupt
6948 */
ufshcd_check_errors(struct ufs_hba * hba,u32 intr_status)6949 static irqreturn_t ufshcd_check_errors(struct ufs_hba *hba, u32 intr_status)
6950 {
6951 bool queue_eh_work = false;
6952 irqreturn_t retval = IRQ_NONE;
6953
6954 guard(spinlock_irqsave)(hba->host->host_lock);
6955 hba->errors |= UFSHCD_ERROR_MASK & intr_status;
6956
6957 if (hba->errors & INT_FATAL_ERRORS) {
6958 ufshcd_update_evt_hist(hba, UFS_EVT_FATAL_ERR,
6959 hba->errors);
6960 queue_eh_work = true;
6961 }
6962
6963 if (hba->errors & UIC_ERROR) {
6964 hba->uic_error = 0;
6965 retval = ufshcd_update_uic_error(hba);
6966 if (hba->uic_error)
6967 queue_eh_work = true;
6968 }
6969
6970 if (hba->errors & UFSHCD_UIC_HIBERN8_MASK) {
6971 dev_err(hba->dev,
6972 "%s: Auto Hibern8 %s failed - status: 0x%08x, upmcrs: 0x%08x\n",
6973 __func__, (hba->errors & UIC_HIBERNATE_ENTER) ?
6974 "Enter" : "Exit",
6975 hba->errors, ufshcd_get_upmcrs(hba));
6976 ufshcd_update_evt_hist(hba, UFS_EVT_AUTO_HIBERN8_ERR,
6977 hba->errors);
6978 ufshcd_set_link_broken(hba);
6979 queue_eh_work = true;
6980 }
6981
6982 if (queue_eh_work) {
6983 /*
6984 * update the transfer error masks to sticky bits, let's do this
6985 * irrespective of current ufshcd_state.
6986 */
6987 hba->saved_err |= hba->errors;
6988 hba->saved_uic_err |= hba->uic_error;
6989
6990 /* dump controller state before resetting */
6991 if ((hba->saved_err &
6992 (INT_FATAL_ERRORS | UFSHCD_UIC_HIBERN8_MASK)) ||
6993 (hba->saved_uic_err &&
6994 (hba->saved_uic_err != UFSHCD_UIC_PA_GENERIC_ERROR))) {
6995 dev_err(hba->dev, "%s: saved_err 0x%x saved_uic_err 0x%x\n",
6996 __func__, hba->saved_err,
6997 hba->saved_uic_err);
6998 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE,
6999 "host_regs: ");
7000 ufshcd_print_pwr_info(hba);
7001 }
7002 ufshcd_schedule_eh_work(hba);
7003 retval |= IRQ_HANDLED;
7004 }
7005 /*
7006 * if (!queue_eh_work) -
7007 * Other errors are either non-fatal where host recovers
7008 * itself without s/w intervention or errors that will be
7009 * handled by the SCSI core layer.
7010 */
7011 hba->errors = 0;
7012 hba->uic_error = 0;
7013
7014 return retval;
7015 }
7016
7017 /**
7018 * ufshcd_tmc_handler - handle task management function completion
7019 * @hba: per adapter instance
7020 *
7021 * Return:
7022 * IRQ_HANDLED - If interrupt is valid
7023 * IRQ_NONE - If invalid interrupt
7024 */
ufshcd_tmc_handler(struct ufs_hba * hba)7025 static irqreturn_t ufshcd_tmc_handler(struct ufs_hba *hba)
7026 {
7027 unsigned long flags, pending, issued;
7028 irqreturn_t ret = IRQ_NONE;
7029 int tag;
7030
7031 spin_lock_irqsave(hba->host->host_lock, flags);
7032 pending = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
7033 issued = hba->outstanding_tasks & ~pending;
7034 for_each_set_bit(tag, &issued, hba->nutmrs) {
7035 struct request *req = hba->tmf_rqs[tag];
7036 struct completion *c = req->end_io_data;
7037
7038 complete(c);
7039 ret = IRQ_HANDLED;
7040 }
7041 spin_unlock_irqrestore(hba->host->host_lock, flags);
7042
7043 return ret;
7044 }
7045
7046 /**
7047 * ufshcd_handle_mcq_cq_events - handle MCQ completion queue events
7048 * @hba: per adapter instance
7049 *
7050 * Return: IRQ_HANDLED if interrupt is handled.
7051 */
ufshcd_handle_mcq_cq_events(struct ufs_hba * hba)7052 static irqreturn_t ufshcd_handle_mcq_cq_events(struct ufs_hba *hba)
7053 {
7054 struct ufs_hw_queue *hwq;
7055 unsigned long outstanding_cqs;
7056 unsigned int nr_queues;
7057 int i, ret;
7058 u32 events;
7059
7060 ret = ufshcd_vops_get_outstanding_cqs(hba, &outstanding_cqs);
7061 if (ret)
7062 outstanding_cqs = (1U << hba->nr_hw_queues) - 1;
7063
7064 /* Exclude the poll queues */
7065 nr_queues = hba->nr_hw_queues - hba->nr_queues[HCTX_TYPE_POLL];
7066 for_each_set_bit(i, &outstanding_cqs, nr_queues) {
7067 hwq = &hba->uhq[i];
7068
7069 events = ufshcd_mcq_read_cqis(hba, i);
7070 if (events)
7071 ufshcd_mcq_write_cqis(hba, events, i);
7072
7073 if (events & UFSHCD_MCQ_CQIS_TAIL_ENT_PUSH_STS)
7074 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7075 }
7076
7077 return IRQ_HANDLED;
7078 }
7079
7080 /**
7081 * ufshcd_sl_intr - Interrupt service routine
7082 * @hba: per adapter instance
7083 * @intr_status: contains interrupts generated by the controller
7084 *
7085 * Return:
7086 * IRQ_HANDLED - If interrupt is valid
7087 * IRQ_NONE - If invalid interrupt
7088 */
ufshcd_sl_intr(struct ufs_hba * hba,u32 intr_status)7089 static irqreturn_t ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
7090 {
7091 irqreturn_t retval = IRQ_NONE;
7092
7093 if (intr_status & UFSHCD_UIC_MASK)
7094 retval |= ufshcd_uic_cmd_compl(hba, intr_status);
7095
7096 if (intr_status & UFSHCD_ERROR_MASK || hba->errors)
7097 retval |= ufshcd_check_errors(hba, intr_status);
7098
7099 if (intr_status & UTP_TASK_REQ_COMPL)
7100 retval |= ufshcd_tmc_handler(hba);
7101
7102 if (intr_status & UTP_TRANSFER_REQ_COMPL)
7103 retval |= ufshcd_transfer_req_compl(hba);
7104
7105 if (intr_status & MCQ_CQ_EVENT_STATUS)
7106 retval |= ufshcd_handle_mcq_cq_events(hba);
7107
7108 return retval;
7109 }
7110
7111 /**
7112 * ufshcd_threaded_intr - Threaded interrupt service routine
7113 * @irq: irq number
7114 * @__hba: pointer to adapter instance
7115 *
7116 * Return:
7117 * IRQ_HANDLED - If interrupt is valid
7118 * IRQ_NONE - If invalid interrupt
7119 */
ufshcd_threaded_intr(int irq,void * __hba)7120 static irqreturn_t ufshcd_threaded_intr(int irq, void *__hba)
7121 {
7122 u32 last_intr_status, intr_status, enabled_intr_status = 0;
7123 irqreturn_t retval = IRQ_NONE;
7124 struct ufs_hba *hba = __hba;
7125 int retries = hba->nutrs;
7126
7127 last_intr_status = intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7128
7129 /*
7130 * There could be max of hba->nutrs reqs in flight and in worst case
7131 * if the reqs get finished 1 by 1 after the interrupt status is
7132 * read, make sure we handle them by checking the interrupt status
7133 * again in a loop until we process all of the reqs before returning.
7134 */
7135 while (intr_status && retries--) {
7136 enabled_intr_status =
7137 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
7138 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
7139 if (enabled_intr_status)
7140 retval |= ufshcd_sl_intr(hba, enabled_intr_status);
7141
7142 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7143 }
7144
7145 if (enabled_intr_status && retval == IRQ_NONE &&
7146 (!(enabled_intr_status & UTP_TRANSFER_REQ_COMPL) ||
7147 hba->outstanding_reqs) && !ufshcd_eh_in_progress(hba)) {
7148 dev_err(hba->dev, "%s: Unhandled interrupt 0x%08x (0x%08x, 0x%08x)\n",
7149 __func__,
7150 intr_status,
7151 last_intr_status,
7152 enabled_intr_status);
7153 ufshcd_dump_regs(hba, 0, UFSHCI_REG_SPACE_SIZE, "host_regs: ");
7154 }
7155
7156 return retval;
7157 }
7158
7159 /**
7160 * ufshcd_intr - Main interrupt service routine
7161 * @irq: irq number
7162 * @__hba: pointer to adapter instance
7163 *
7164 * Return:
7165 * IRQ_HANDLED - If interrupt is valid
7166 * IRQ_WAKE_THREAD - If handling is moved to threaded handled
7167 * IRQ_NONE - If invalid interrupt
7168 */
ufshcd_intr(int irq,void * __hba)7169 static irqreturn_t ufshcd_intr(int irq, void *__hba)
7170 {
7171 struct ufs_hba *hba = __hba;
7172 u32 intr_status, enabled_intr_status;
7173
7174 /* Move interrupt handling to thread when MCQ & ESI are not enabled */
7175 if (!hba->mcq_enabled || !hba->mcq_esi_enabled)
7176 return IRQ_WAKE_THREAD;
7177
7178 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
7179 enabled_intr_status = intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
7180
7181 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
7182
7183 /* Directly handle interrupts since MCQ ESI handlers does the hard job */
7184 return ufshcd_sl_intr(hba, enabled_intr_status);
7185 }
7186
ufshcd_clear_tm_cmd(struct ufs_hba * hba,int tag)7187 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
7188 {
7189 int err = 0;
7190 u32 mask = 1 << tag;
7191
7192 if (!test_bit(tag, &hba->outstanding_tasks))
7193 goto out;
7194
7195 ufshcd_utmrl_clear(hba, tag);
7196
7197 /* poll for max. 1 sec to clear door bell register by h/w */
7198 err = ufshcd_wait_for_register(hba,
7199 REG_UTP_TASK_REQ_DOOR_BELL,
7200 mask, 0, 1000, 1000);
7201
7202 dev_err(hba->dev, "Clearing task management function with tag %d %s\n",
7203 tag, err < 0 ? "failed" : "succeeded");
7204
7205 out:
7206 return err;
7207 }
7208
__ufshcd_issue_tm_cmd(struct ufs_hba * hba,struct utp_task_req_desc * treq,u8 tm_function)7209 static int __ufshcd_issue_tm_cmd(struct ufs_hba *hba,
7210 struct utp_task_req_desc *treq, u8 tm_function)
7211 {
7212 struct request_queue *q = hba->tmf_queue;
7213 struct Scsi_Host *host = hba->host;
7214 DECLARE_COMPLETION_ONSTACK(wait);
7215 struct request *req;
7216 unsigned long flags;
7217 int task_tag, err;
7218
7219 /*
7220 * blk_mq_alloc_request() is used here only to get a free tag.
7221 */
7222 req = blk_mq_alloc_request(q, REQ_OP_DRV_OUT, 0);
7223 if (IS_ERR(req))
7224 return PTR_ERR(req);
7225
7226 req->end_io_data = &wait;
7227 ufshcd_hold(hba);
7228
7229 spin_lock_irqsave(host->host_lock, flags);
7230
7231 task_tag = req->tag;
7232 hba->tmf_rqs[req->tag] = req;
7233 treq->upiu_req.req_header.task_tag = task_tag;
7234
7235 memcpy(hba->utmrdl_base_addr + task_tag, treq, sizeof(*treq));
7236 ufshcd_vops_setup_task_mgmt(hba, task_tag, tm_function);
7237
7238 __set_bit(task_tag, &hba->outstanding_tasks);
7239
7240 spin_unlock_irqrestore(host->host_lock, flags);
7241
7242 /* send command to the controller */
7243 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TASK_REQ_DOOR_BELL);
7244
7245 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_SEND);
7246
7247 /* wait until the task management command is completed */
7248 err = wait_for_completion_io_timeout(&wait,
7249 msecs_to_jiffies(TM_CMD_TIMEOUT));
7250 if (!err) {
7251 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_ERR);
7252 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
7253 __func__, tm_function);
7254 if (ufshcd_clear_tm_cmd(hba, task_tag))
7255 dev_WARN(hba->dev, "%s: unable to clear tm cmd (slot %d) after timeout\n",
7256 __func__, task_tag);
7257 err = -ETIMEDOUT;
7258 } else {
7259 err = 0;
7260 memcpy(treq, hba->utmrdl_base_addr + task_tag, sizeof(*treq));
7261
7262 ufshcd_add_tm_upiu_trace(hba, task_tag, UFS_TM_COMP);
7263 }
7264
7265 spin_lock_irqsave(hba->host->host_lock, flags);
7266 hba->tmf_rqs[req->tag] = NULL;
7267 __clear_bit(task_tag, &hba->outstanding_tasks);
7268 spin_unlock_irqrestore(hba->host->host_lock, flags);
7269
7270 ufshcd_release(hba);
7271 blk_mq_free_request(req);
7272
7273 return err;
7274 }
7275
7276 /**
7277 * ufshcd_issue_tm_cmd - issues task management commands to controller
7278 * @hba: per adapter instance
7279 * @lun_id: LUN ID to which TM command is sent
7280 * @task_id: task ID to which the TM command is applicable
7281 * @tm_function: task management function opcode
7282 * @tm_response: task management service response return value
7283 *
7284 * Return: non-zero value on error, zero on success.
7285 */
ufshcd_issue_tm_cmd(struct ufs_hba * hba,int lun_id,int task_id,u8 tm_function,u8 * tm_response)7286 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
7287 u8 tm_function, u8 *tm_response)
7288 {
7289 struct utp_task_req_desc treq = { };
7290 enum utp_ocs ocs_value;
7291 int err;
7292
7293 /* Configure task request descriptor */
7294 treq.header.interrupt = 1;
7295 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7296
7297 /* Configure task request UPIU */
7298 treq.upiu_req.req_header.transaction_code = UPIU_TRANSACTION_TASK_REQ;
7299 treq.upiu_req.req_header.lun = lun_id;
7300 treq.upiu_req.req_header.tm_function = tm_function;
7301
7302 /*
7303 * The host shall provide the same value for LUN field in the basic
7304 * header and for Input Parameter.
7305 */
7306 treq.upiu_req.input_param1 = cpu_to_be32(lun_id);
7307 treq.upiu_req.input_param2 = cpu_to_be32(task_id);
7308
7309 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_function);
7310 if (err == -ETIMEDOUT)
7311 return err;
7312
7313 ocs_value = treq.header.ocs & MASK_OCS;
7314 if (ocs_value != OCS_SUCCESS)
7315 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
7316 __func__, ocs_value);
7317 else if (tm_response)
7318 *tm_response = be32_to_cpu(treq.upiu_rsp.output_param1) &
7319 MASK_TM_SERVICE_RESP;
7320 return err;
7321 }
7322
7323 /**
7324 * ufshcd_issue_devman_upiu_cmd - API for sending "utrd" type requests
7325 * @hba: per-adapter instance
7326 * @req_upiu: upiu request
7327 * @rsp_upiu: upiu reply
7328 * @desc_buff: pointer to descriptor buffer, NULL if NA
7329 * @buff_len: descriptor size, 0 if NA
7330 * @cmd_type: specifies the type (NOP, Query...)
7331 * @desc_op: descriptor operation
7332 *
7333 * Those type of requests uses UTP Transfer Request Descriptor - utrd.
7334 * Therefore, it "rides" the device management infrastructure: uses its tag and
7335 * tasks work queues.
7336 *
7337 * Since there is only one available tag for device management commands,
7338 * the caller is expected to hold the hba->dev_cmd.lock mutex.
7339 *
7340 * Return: 0 upon success; < 0 upon failure.
7341 */
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)7342 static int ufshcd_issue_devman_upiu_cmd(struct ufs_hba *hba,
7343 struct utp_upiu_req *req_upiu,
7344 struct utp_upiu_req *rsp_upiu,
7345 u8 *desc_buff, int *buff_len,
7346 enum dev_cmd_type cmd_type,
7347 enum query_opcode desc_op)
7348 {
7349 const u32 tag = hba->reserved_slot;
7350 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7351 int err = 0;
7352 u8 upiu_flags;
7353
7354 /* Protects use of hba->reserved_slot. */
7355 lockdep_assert_held(&hba->dev_cmd.lock);
7356
7357 ufshcd_setup_dev_cmd(hba, lrbp, cmd_type, 0, tag);
7358
7359 ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags, DMA_NONE, 0);
7360
7361 /* update the task tag in the request upiu */
7362 req_upiu->header.task_tag = tag;
7363
7364 /* just copy the upiu request as it is */
7365 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7366 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_WRITE_DESC) {
7367 /* The Data Segment Area is optional depending upon the query
7368 * function value. for WRITE DESCRIPTOR, the data segment
7369 * follows right after the tsf.
7370 */
7371 memcpy(lrbp->ucd_req_ptr + 1, desc_buff, *buff_len);
7372 *buff_len = 0;
7373 }
7374
7375 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7376
7377 /*
7378 * ignore the returning value here - ufshcd_check_query_response is
7379 * bound to fail since dev_cmd.query and dev_cmd.type were left empty.
7380 * read the response directly ignoring all errors.
7381 */
7382 ufshcd_issue_dev_cmd(hba, lrbp, tag, dev_cmd_timeout);
7383
7384 /* just copy the upiu response as it is */
7385 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7386 if (desc_buff && desc_op == UPIU_QUERY_OPCODE_READ_DESC) {
7387 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr + sizeof(*rsp_upiu);
7388 u16 resp_len = be16_to_cpu(lrbp->ucd_rsp_ptr->header
7389 .data_segment_length);
7390
7391 if (*buff_len >= resp_len) {
7392 memcpy(desc_buff, descp, resp_len);
7393 *buff_len = resp_len;
7394 } else {
7395 dev_warn(hba->dev,
7396 "%s: rsp size %d is bigger than buffer size %d",
7397 __func__, resp_len, *buff_len);
7398 *buff_len = 0;
7399 err = -EINVAL;
7400 }
7401 }
7402
7403 return err;
7404 }
7405
7406 /**
7407 * ufshcd_exec_raw_upiu_cmd - API function for sending raw upiu commands
7408 * @hba: per-adapter instance
7409 * @req_upiu: upiu request
7410 * @rsp_upiu: upiu reply - only 8 DW as we do not support scsi commands
7411 * @msgcode: message code, one of UPIU Transaction Codes Initiator to Target
7412 * @desc_buff: pointer to descriptor buffer, NULL if NA
7413 * @buff_len: descriptor size, 0 if NA
7414 * @desc_op: descriptor operation
7415 *
7416 * Supports UTP Transfer requests (nop and query), and UTP Task
7417 * Management requests.
7418 * It is up to the caller to fill the upiu conent properly, as it will
7419 * be copied without any further input validations.
7420 *
7421 * Return: 0 upon success; < 0 upon failure.
7422 */
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)7423 int ufshcd_exec_raw_upiu_cmd(struct ufs_hba *hba,
7424 struct utp_upiu_req *req_upiu,
7425 struct utp_upiu_req *rsp_upiu,
7426 enum upiu_request_transaction msgcode,
7427 u8 *desc_buff, int *buff_len,
7428 enum query_opcode desc_op)
7429 {
7430 int err;
7431 enum dev_cmd_type cmd_type = DEV_CMD_TYPE_QUERY;
7432 struct utp_task_req_desc treq = { };
7433 enum utp_ocs ocs_value;
7434 u8 tm_f = req_upiu->header.tm_function;
7435
7436 switch (msgcode) {
7437 case UPIU_TRANSACTION_NOP_OUT:
7438 cmd_type = DEV_CMD_TYPE_NOP;
7439 fallthrough;
7440 case UPIU_TRANSACTION_QUERY_REQ:
7441 ufshcd_dev_man_lock(hba);
7442 err = ufshcd_issue_devman_upiu_cmd(hba, req_upiu, rsp_upiu,
7443 desc_buff, buff_len,
7444 cmd_type, desc_op);
7445 ufshcd_dev_man_unlock(hba);
7446
7447 break;
7448 case UPIU_TRANSACTION_TASK_REQ:
7449 treq.header.interrupt = 1;
7450 treq.header.ocs = OCS_INVALID_COMMAND_STATUS;
7451
7452 memcpy(&treq.upiu_req, req_upiu, sizeof(*req_upiu));
7453
7454 err = __ufshcd_issue_tm_cmd(hba, &treq, tm_f);
7455 if (err == -ETIMEDOUT)
7456 break;
7457
7458 ocs_value = treq.header.ocs & MASK_OCS;
7459 if (ocs_value != OCS_SUCCESS) {
7460 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n", __func__,
7461 ocs_value);
7462 break;
7463 }
7464
7465 memcpy(rsp_upiu, &treq.upiu_rsp, sizeof(*rsp_upiu));
7466
7467 break;
7468 default:
7469 err = -EINVAL;
7470
7471 break;
7472 }
7473
7474 return err;
7475 }
7476
7477 /**
7478 * ufshcd_advanced_rpmb_req_handler - handle advanced RPMB request
7479 * @hba: per adapter instance
7480 * @req_upiu: upiu request
7481 * @rsp_upiu: upiu reply
7482 * @req_ehs: EHS field which contains Advanced RPMB Request Message
7483 * @rsp_ehs: EHS field which returns Advanced RPMB Response Message
7484 * @sg_cnt: The number of sg lists actually used
7485 * @sg_list: Pointer to SG list when DATA IN/OUT UPIU is required in ARPMB operation
7486 * @dir: DMA direction
7487 *
7488 * Return: 0 upon success; > 0 in case the UFS device reported an OCS error;
7489 * < 0 if another error occurred.
7490 */
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)7491 int ufshcd_advanced_rpmb_req_handler(struct ufs_hba *hba, struct utp_upiu_req *req_upiu,
7492 struct utp_upiu_req *rsp_upiu, struct ufs_ehs *req_ehs,
7493 struct ufs_ehs *rsp_ehs, int sg_cnt, struct scatterlist *sg_list,
7494 enum dma_data_direction dir)
7495 {
7496 const u32 tag = hba->reserved_slot;
7497 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7498 int err = 0;
7499 int result;
7500 u8 upiu_flags;
7501 u8 *ehs_data;
7502 u16 ehs_len;
7503 int ehs = (hba->capabilities & MASK_EHSLUTRD_SUPPORTED) ? 2 : 0;
7504
7505 /* Protects use of hba->reserved_slot. */
7506 ufshcd_dev_man_lock(hba);
7507
7508 ufshcd_setup_dev_cmd(hba, lrbp, DEV_CMD_TYPE_RPMB, UFS_UPIU_RPMB_WLUN, tag);
7509
7510 ufshcd_prepare_req_desc_hdr(hba, lrbp, &upiu_flags, DMA_NONE, ehs);
7511
7512 /* update the task tag */
7513 req_upiu->header.task_tag = tag;
7514
7515 /* copy the UPIU(contains CDB) request as it is */
7516 memcpy(lrbp->ucd_req_ptr, req_upiu, sizeof(*lrbp->ucd_req_ptr));
7517 /* Copy EHS, starting with byte32, immediately after the CDB package */
7518 memcpy(lrbp->ucd_req_ptr + 1, req_ehs, sizeof(*req_ehs));
7519
7520 if (dir != DMA_NONE && sg_list)
7521 ufshcd_sgl_to_prdt(hba, lrbp, sg_cnt, sg_list);
7522
7523 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
7524
7525 err = ufshcd_issue_dev_cmd(hba, lrbp, tag, ADVANCED_RPMB_REQ_TIMEOUT);
7526
7527 if (!err) {
7528 /* Just copy the upiu response as it is */
7529 memcpy(rsp_upiu, lrbp->ucd_rsp_ptr, sizeof(*rsp_upiu));
7530 /* Get the response UPIU result */
7531 result = (lrbp->ucd_rsp_ptr->header.response << 8) |
7532 lrbp->ucd_rsp_ptr->header.status;
7533
7534 ehs_len = lrbp->ucd_rsp_ptr->header.ehs_length;
7535 /*
7536 * Since the bLength in EHS indicates the total size of the EHS Header and EHS Data
7537 * in 32 Byte units, the value of the bLength Request/Response for Advanced RPMB
7538 * Message is 02h
7539 */
7540 if (ehs_len == 2 && rsp_ehs) {
7541 /*
7542 * ucd_rsp_ptr points to a buffer with a length of 512 bytes
7543 * (ALIGNED_UPIU_SIZE = 512), and the EHS data just starts from byte32
7544 */
7545 ehs_data = (u8 *)lrbp->ucd_rsp_ptr + EHS_OFFSET_IN_RESPONSE;
7546 memcpy(rsp_ehs, ehs_data, ehs_len * 32);
7547 }
7548 }
7549
7550 ufshcd_dev_man_unlock(hba);
7551
7552 return err ? : result;
7553 }
7554
7555 /**
7556 * ufshcd_eh_device_reset_handler() - Reset a single logical unit.
7557 * @cmd: SCSI command pointer
7558 *
7559 * Return: SUCCESS or FAILED.
7560 */
ufshcd_eh_device_reset_handler(struct scsi_cmnd * cmd)7561 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7562 {
7563 unsigned long flags, pending_reqs = 0, not_cleared = 0;
7564 struct Scsi_Host *host;
7565 struct ufs_hba *hba;
7566 struct ufs_hw_queue *hwq;
7567 struct ufshcd_lrb *lrbp;
7568 u32 pos, not_cleared_mask = 0;
7569 int err;
7570 u8 resp = 0xF, lun;
7571
7572 host = cmd->device->host;
7573 hba = shost_priv(host);
7574
7575 lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
7576 err = ufshcd_issue_tm_cmd(hba, lun, 0, UFS_LOGICAL_RESET, &resp);
7577 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7578 if (!err)
7579 err = resp;
7580 goto out;
7581 }
7582
7583 if (hba->mcq_enabled) {
7584 for (pos = 0; pos < hba->nutrs; pos++) {
7585 lrbp = &hba->lrb[pos];
7586 if (ufshcd_cmd_inflight(lrbp->cmd) &&
7587 lrbp->lun == lun) {
7588 ufshcd_clear_cmd(hba, pos);
7589 hwq = ufshcd_mcq_req_to_hwq(hba, scsi_cmd_to_rq(lrbp->cmd));
7590 ufshcd_mcq_poll_cqe_lock(hba, hwq);
7591 }
7592 }
7593 err = 0;
7594 goto out;
7595 }
7596
7597 /* clear the commands that were pending for corresponding LUN */
7598 spin_lock_irqsave(&hba->outstanding_lock, flags);
7599 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs)
7600 if (hba->lrb[pos].lun == lun)
7601 __set_bit(pos, &pending_reqs);
7602 hba->outstanding_reqs &= ~pending_reqs;
7603 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7604
7605 for_each_set_bit(pos, &pending_reqs, hba->nutrs) {
7606 if (ufshcd_clear_cmd(hba, pos) < 0) {
7607 spin_lock_irqsave(&hba->outstanding_lock, flags);
7608 not_cleared = 1U << pos &
7609 ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7610 hba->outstanding_reqs |= not_cleared;
7611 not_cleared_mask |= not_cleared;
7612 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7613
7614 dev_err(hba->dev, "%s: failed to clear request %d\n",
7615 __func__, pos);
7616 }
7617 }
7618 __ufshcd_transfer_req_compl(hba, pending_reqs & ~not_cleared_mask);
7619
7620 out:
7621 hba->req_abort_count = 0;
7622 ufshcd_update_evt_hist(hba, UFS_EVT_DEV_RESET, (u32)err);
7623 if (!err) {
7624 err = SUCCESS;
7625 } else {
7626 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7627 err = FAILED;
7628 }
7629 return err;
7630 }
7631
ufshcd_set_req_abort_skip(struct ufs_hba * hba,unsigned long bitmap)7632 static void ufshcd_set_req_abort_skip(struct ufs_hba *hba, unsigned long bitmap)
7633 {
7634 struct ufshcd_lrb *lrbp;
7635 int tag;
7636
7637 for_each_set_bit(tag, &bitmap, hba->nutrs) {
7638 lrbp = &hba->lrb[tag];
7639 lrbp->req_abort_skip = true;
7640 }
7641 }
7642
7643 /**
7644 * ufshcd_try_to_abort_task - abort a specific task
7645 * @hba: Pointer to adapter instance
7646 * @tag: Task tag/index to be aborted
7647 *
7648 * Abort the pending command in device by sending UFS_ABORT_TASK task management
7649 * command, and in host controller by clearing the door-bell register. There can
7650 * be race between controller sending the command to the device while abort is
7651 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
7652 * really issued and then try to abort it.
7653 *
7654 * Return: zero on success, non-zero on failure.
7655 */
ufshcd_try_to_abort_task(struct ufs_hba * hba,int tag)7656 int ufshcd_try_to_abort_task(struct ufs_hba *hba, int tag)
7657 {
7658 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7659 int err;
7660 int poll_cnt;
7661 u8 resp = 0xF;
7662
7663 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
7664 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7665 UFS_QUERY_TASK, &resp);
7666 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
7667 /* cmd pending in the device */
7668 dev_err(hba->dev, "%s: cmd pending in the device. tag = %d\n",
7669 __func__, tag);
7670 break;
7671 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7672 /*
7673 * cmd not pending in the device, check if it is
7674 * in transition.
7675 */
7676 dev_info(
7677 hba->dev,
7678 "%s: cmd with tag %d not pending in the device.\n",
7679 __func__, tag);
7680 if (!ufshcd_cmd_inflight(lrbp->cmd)) {
7681 dev_info(hba->dev,
7682 "%s: cmd with tag=%d completed.\n",
7683 __func__, tag);
7684 return 0;
7685 }
7686 usleep_range(100, 200);
7687 } else {
7688 dev_err(hba->dev,
7689 "%s: no response from device. tag = %d, err %d\n",
7690 __func__, tag, err);
7691 return err ? : resp;
7692 }
7693 }
7694
7695 if (!poll_cnt)
7696 return -EBUSY;
7697
7698 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
7699 UFS_ABORT_TASK, &resp);
7700 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
7701 if (!err) {
7702 err = resp; /* service response error */
7703 dev_err(hba->dev, "%s: issued. tag = %d, err %d\n",
7704 __func__, tag, err);
7705 }
7706 return err;
7707 }
7708
7709 err = ufshcd_clear_cmd(hba, tag);
7710 if (err)
7711 dev_err(hba->dev, "%s: Failed clearing cmd at tag %d, err %d\n",
7712 __func__, tag, err);
7713
7714 return err;
7715 }
7716
7717 /**
7718 * ufshcd_abort - scsi host template eh_abort_handler callback
7719 * @cmd: SCSI command pointer
7720 *
7721 * Return: SUCCESS or FAILED.
7722 */
ufshcd_abort(struct scsi_cmnd * cmd)7723 static int ufshcd_abort(struct scsi_cmnd *cmd)
7724 {
7725 struct Scsi_Host *host = cmd->device->host;
7726 struct ufs_hba *hba = shost_priv(host);
7727 int tag = scsi_cmd_to_rq(cmd)->tag;
7728 struct ufshcd_lrb *lrbp = &hba->lrb[tag];
7729 unsigned long flags;
7730 int err = FAILED;
7731 bool outstanding;
7732 u32 reg;
7733
7734 ufshcd_hold(hba);
7735
7736 if (!hba->mcq_enabled) {
7737 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7738 if (!test_bit(tag, &hba->outstanding_reqs)) {
7739 /* If command is already aborted/completed, return FAILED. */
7740 dev_err(hba->dev,
7741 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
7742 __func__, tag, hba->outstanding_reqs, reg);
7743 goto release;
7744 }
7745 }
7746
7747 /* Print Transfer Request of aborted task */
7748 dev_info(hba->dev, "%s: Device abort task at tag %d\n", __func__, tag);
7749
7750 /*
7751 * Print detailed info about aborted request.
7752 * As more than one request might get aborted at the same time,
7753 * print full information only for the first aborted request in order
7754 * to reduce repeated printouts. For other aborted requests only print
7755 * basic details.
7756 */
7757 scsi_print_command(cmd);
7758 if (!hba->req_abort_count) {
7759 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, tag);
7760 ufshcd_print_evt_hist(hba);
7761 ufshcd_print_host_state(hba);
7762 ufshcd_print_pwr_info(hba);
7763 ufshcd_print_tr(hba, tag, true);
7764 } else {
7765 ufshcd_print_tr(hba, tag, false);
7766 }
7767 hba->req_abort_count++;
7768
7769 if (!hba->mcq_enabled && !(reg & (1 << tag))) {
7770 /* only execute this code in single doorbell mode */
7771 dev_err(hba->dev,
7772 "%s: cmd was completed, but without a notifying intr, tag = %d",
7773 __func__, tag);
7774 __ufshcd_transfer_req_compl(hba, 1UL << tag);
7775 goto release;
7776 }
7777
7778 /*
7779 * Task abort to the device W-LUN is illegal. When this command
7780 * will fail, due to spec violation, scsi err handling next step
7781 * will be to send LU reset which, again, is a spec violation.
7782 * To avoid these unnecessary/illegal steps, first we clean up
7783 * the lrb taken by this cmd and re-set it in outstanding_reqs,
7784 * then queue the eh_work and bail.
7785 */
7786 if (lrbp->lun == UFS_UPIU_UFS_DEVICE_WLUN) {
7787 ufshcd_update_evt_hist(hba, UFS_EVT_ABORT, lrbp->lun);
7788
7789 spin_lock_irqsave(host->host_lock, flags);
7790 hba->force_reset = true;
7791 ufshcd_schedule_eh_work(hba);
7792 spin_unlock_irqrestore(host->host_lock, flags);
7793 goto release;
7794 }
7795
7796 if (hba->mcq_enabled) {
7797 /* MCQ mode. Branch off to handle abort for mcq mode */
7798 err = ufshcd_mcq_abort(cmd);
7799 goto release;
7800 }
7801
7802 /* Skip task abort in case previous aborts failed and report failure */
7803 if (lrbp->req_abort_skip) {
7804 dev_err(hba->dev, "%s: skipping abort\n", __func__);
7805 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7806 goto release;
7807 }
7808
7809 err = ufshcd_try_to_abort_task(hba, tag);
7810 if (err) {
7811 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
7812 ufshcd_set_req_abort_skip(hba, hba->outstanding_reqs);
7813 err = FAILED;
7814 goto release;
7815 }
7816
7817 /*
7818 * Clear the corresponding bit from outstanding_reqs since the command
7819 * has been aborted successfully.
7820 */
7821 spin_lock_irqsave(&hba->outstanding_lock, flags);
7822 outstanding = __test_and_clear_bit(tag, &hba->outstanding_reqs);
7823 spin_unlock_irqrestore(&hba->outstanding_lock, flags);
7824
7825 if (outstanding)
7826 ufshcd_release_scsi_cmd(hba, lrbp);
7827
7828 err = SUCCESS;
7829
7830 release:
7831 /* Matches the ufshcd_hold() call at the start of this function. */
7832 ufshcd_release(hba);
7833 return err;
7834 }
7835
7836 /**
7837 * ufshcd_process_probe_result - Process the ufshcd_probe_hba() result.
7838 * @hba: UFS host controller instance.
7839 * @probe_start: time when the ufshcd_probe_hba() call started.
7840 * @ret: ufshcd_probe_hba() return value.
7841 */
ufshcd_process_probe_result(struct ufs_hba * hba,ktime_t probe_start,int ret)7842 static void ufshcd_process_probe_result(struct ufs_hba *hba,
7843 ktime_t probe_start, int ret)
7844 {
7845 unsigned long flags;
7846
7847 spin_lock_irqsave(hba->host->host_lock, flags);
7848 if (ret)
7849 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7850 else if (hba->ufshcd_state == UFSHCD_STATE_RESET)
7851 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
7852 spin_unlock_irqrestore(hba->host->host_lock, flags);
7853
7854 trace_ufshcd_init(hba, ret,
7855 ktime_to_us(ktime_sub(ktime_get(), probe_start)),
7856 hba->curr_dev_pwr_mode, hba->uic_link_state);
7857 }
7858
7859 /**
7860 * ufshcd_host_reset_and_restore - reset and restore host controller
7861 * @hba: per-adapter instance
7862 *
7863 * Note that host controller reset may issue DME_RESET to
7864 * local and remote (device) Uni-Pro stack and the attributes
7865 * are reset to default state.
7866 *
7867 * Return: zero on success, non-zero on failure.
7868 */
ufshcd_host_reset_and_restore(struct ufs_hba * hba)7869 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
7870 {
7871 int err;
7872
7873 /*
7874 * Stop the host controller and complete the requests
7875 * cleared by h/w
7876 */
7877 ufshcd_hba_stop(hba);
7878 hba->silence_err_logs = true;
7879 ufshcd_complete_requests(hba, true);
7880 hba->silence_err_logs = false;
7881
7882 /* scale up clocks to max frequency before full reinitialization */
7883 if (ufshcd_is_clkscaling_supported(hba))
7884 ufshcd_scale_clks(hba, ULONG_MAX, true);
7885
7886 err = ufshcd_hba_enable(hba);
7887
7888 /* Establish the link again and restore the device */
7889 if (!err) {
7890 ktime_t probe_start = ktime_get();
7891
7892 err = ufshcd_device_init(hba, /*init_dev_params=*/false);
7893 if (!err)
7894 err = ufshcd_probe_hba(hba, false);
7895 ufshcd_process_probe_result(hba, probe_start, err);
7896 }
7897
7898 if (err)
7899 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
7900 ufshcd_update_evt_hist(hba, UFS_EVT_HOST_RESET, (u32)err);
7901 return err;
7902 }
7903
7904 /**
7905 * ufshcd_reset_and_restore - reset and re-initialize host/device
7906 * @hba: per-adapter instance
7907 *
7908 * Reset and recover device, host and re-establish link. This
7909 * is helpful to recover the communication in fatal error conditions.
7910 *
7911 * Return: zero on success, non-zero on failure.
7912 */
ufshcd_reset_and_restore(struct ufs_hba * hba)7913 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
7914 {
7915 u32 saved_err = 0;
7916 u32 saved_uic_err = 0;
7917 int err = 0;
7918 unsigned long flags;
7919 int retries = MAX_HOST_RESET_RETRIES;
7920
7921 spin_lock_irqsave(hba->host->host_lock, flags);
7922 do {
7923 /*
7924 * This is a fresh start, cache and clear saved error first,
7925 * in case new error generated during reset and restore.
7926 */
7927 saved_err |= hba->saved_err;
7928 saved_uic_err |= hba->saved_uic_err;
7929 hba->saved_err = 0;
7930 hba->saved_uic_err = 0;
7931 hba->force_reset = false;
7932 hba->ufshcd_state = UFSHCD_STATE_RESET;
7933 spin_unlock_irqrestore(hba->host->host_lock, flags);
7934
7935 /* Reset the attached device */
7936 ufshcd_device_reset(hba);
7937
7938 err = ufshcd_host_reset_and_restore(hba);
7939
7940 spin_lock_irqsave(hba->host->host_lock, flags);
7941 if (err)
7942 continue;
7943 /* Do not exit unless operational or dead */
7944 if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL &&
7945 hba->ufshcd_state != UFSHCD_STATE_ERROR &&
7946 hba->ufshcd_state != UFSHCD_STATE_EH_SCHEDULED_NON_FATAL)
7947 err = -EAGAIN;
7948 } while (err && --retries);
7949
7950 /*
7951 * Inform scsi mid-layer that we did reset and allow to handle
7952 * Unit Attention properly.
7953 */
7954 scsi_report_bus_reset(hba->host, 0);
7955 if (err) {
7956 hba->ufshcd_state = UFSHCD_STATE_ERROR;
7957 hba->saved_err |= saved_err;
7958 hba->saved_uic_err |= saved_uic_err;
7959 }
7960 spin_unlock_irqrestore(hba->host->host_lock, flags);
7961
7962 return err;
7963 }
7964
7965 /**
7966 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
7967 * @cmd: SCSI command pointer
7968 *
7969 * Return: SUCCESS or FAILED.
7970 */
ufshcd_eh_host_reset_handler(struct scsi_cmnd * cmd)7971 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
7972 {
7973 int err = SUCCESS;
7974 unsigned long flags;
7975 struct ufs_hba *hba;
7976
7977 hba = shost_priv(cmd->device->host);
7978
7979 /*
7980 * If runtime PM sent SSU and got a timeout, scsi_error_handler is
7981 * stuck in this function waiting for flush_work(&hba->eh_work). And
7982 * ufshcd_err_handler(eh_work) is stuck waiting for runtime PM. Do
7983 * ufshcd_link_recovery instead of eh_work to prevent deadlock.
7984 */
7985 if (hba->pm_op_in_progress) {
7986 if (ufshcd_link_recovery(hba))
7987 err = FAILED;
7988
7989 return err;
7990 }
7991
7992 spin_lock_irqsave(hba->host->host_lock, flags);
7993 hba->force_reset = true;
7994 ufshcd_schedule_eh_work(hba);
7995 dev_err(hba->dev, "%s: reset in progress - 1\n", __func__);
7996 spin_unlock_irqrestore(hba->host->host_lock, flags);
7997
7998 flush_work(&hba->eh_work);
7999
8000 spin_lock_irqsave(hba->host->host_lock, flags);
8001 if (hba->ufshcd_state == UFSHCD_STATE_ERROR)
8002 err = FAILED;
8003 spin_unlock_irqrestore(hba->host->host_lock, flags);
8004
8005 return err;
8006 }
8007
8008 /**
8009 * ufshcd_get_max_icc_level - calculate the ICC level
8010 * @sup_curr_uA: max. current supported by the regulator
8011 * @start_scan: row at the desc table to start scan from
8012 * @buff: power descriptor buffer
8013 *
8014 * Return: calculated max ICC level for specific regulator.
8015 */
ufshcd_get_max_icc_level(int sup_curr_uA,u32 start_scan,const char * buff)8016 static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan,
8017 const char *buff)
8018 {
8019 int i;
8020 int curr_uA;
8021 u16 data;
8022 u16 unit;
8023
8024 for (i = start_scan; i >= 0; i--) {
8025 data = get_unaligned_be16(&buff[2 * i]);
8026 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
8027 ATTR_ICC_LVL_UNIT_OFFSET;
8028 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
8029 switch (unit) {
8030 case UFSHCD_NANO_AMP:
8031 curr_uA = curr_uA / 1000;
8032 break;
8033 case UFSHCD_MILI_AMP:
8034 curr_uA = curr_uA * 1000;
8035 break;
8036 case UFSHCD_AMP:
8037 curr_uA = curr_uA * 1000 * 1000;
8038 break;
8039 case UFSHCD_MICRO_AMP:
8040 default:
8041 break;
8042 }
8043 if (sup_curr_uA >= curr_uA)
8044 break;
8045 }
8046 if (i < 0) {
8047 i = 0;
8048 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
8049 }
8050
8051 return (u32)i;
8052 }
8053
8054 /**
8055 * ufshcd_find_max_sup_active_icc_level - calculate the max ICC level
8056 * In case regulators are not initialized we'll return 0
8057 * @hba: per-adapter instance
8058 * @desc_buf: power descriptor buffer to extract ICC levels from.
8059 *
8060 * Return: calculated ICC level.
8061 */
ufshcd_find_max_sup_active_icc_level(struct ufs_hba * hba,const u8 * desc_buf)8062 static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
8063 const u8 *desc_buf)
8064 {
8065 u32 icc_level = 0;
8066
8067 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
8068 !hba->vreg_info.vccq2) {
8069 /*
8070 * Using dev_dbg to avoid messages during runtime PM to avoid
8071 * never-ending cycles of messages written back to storage by
8072 * user space causing runtime resume, causing more messages and
8073 * so on.
8074 */
8075 dev_dbg(hba->dev,
8076 "%s: Regulator capability was not set, actvIccLevel=%d",
8077 __func__, icc_level);
8078 goto out;
8079 }
8080
8081 if (hba->vreg_info.vcc->max_uA)
8082 icc_level = ufshcd_get_max_icc_level(
8083 hba->vreg_info.vcc->max_uA,
8084 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
8085 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
8086
8087 if (hba->vreg_info.vccq->max_uA)
8088 icc_level = ufshcd_get_max_icc_level(
8089 hba->vreg_info.vccq->max_uA,
8090 icc_level,
8091 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
8092
8093 if (hba->vreg_info.vccq2->max_uA)
8094 icc_level = ufshcd_get_max_icc_level(
8095 hba->vreg_info.vccq2->max_uA,
8096 icc_level,
8097 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
8098 out:
8099 return icc_level;
8100 }
8101
ufshcd_set_active_icc_lvl(struct ufs_hba * hba)8102 static void ufshcd_set_active_icc_lvl(struct ufs_hba *hba)
8103 {
8104 int ret;
8105 u8 *desc_buf;
8106 u32 icc_level;
8107
8108 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8109 if (!desc_buf)
8110 return;
8111
8112 ret = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_POWER, 0, 0,
8113 desc_buf, QUERY_DESC_MAX_SIZE);
8114 if (ret) {
8115 dev_err(hba->dev,
8116 "%s: Failed reading power descriptor ret = %d",
8117 __func__, ret);
8118 goto out;
8119 }
8120
8121 icc_level = ufshcd_find_max_sup_active_icc_level(hba, desc_buf);
8122 dev_dbg(hba->dev, "%s: setting icc_level 0x%x", __func__, icc_level);
8123
8124 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8125 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0, &icc_level);
8126
8127 if (ret)
8128 dev_err(hba->dev,
8129 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
8130 __func__, icc_level, ret);
8131
8132 out:
8133 kfree(desc_buf);
8134 }
8135
ufshcd_blk_pm_runtime_init(struct scsi_device * sdev)8136 static inline void ufshcd_blk_pm_runtime_init(struct scsi_device *sdev)
8137 {
8138 struct Scsi_Host *shost = sdev->host;
8139
8140 scsi_autopm_get_device(sdev);
8141 blk_pm_runtime_init(sdev->request_queue, &sdev->sdev_gendev);
8142 if (sdev->rpm_autosuspend)
8143 pm_runtime_set_autosuspend_delay(&sdev->sdev_gendev,
8144 shost->rpm_autosuspend_delay);
8145 scsi_autopm_put_device(sdev);
8146 }
8147
8148 /**
8149 * ufshcd_scsi_add_wlus - Adds required W-LUs
8150 * @hba: per-adapter instance
8151 *
8152 * UFS device specification requires the UFS devices to support 4 well known
8153 * logical units:
8154 * "REPORT_LUNS" (address: 01h)
8155 * "UFS Device" (address: 50h)
8156 * "RPMB" (address: 44h)
8157 * "BOOT" (address: 30h)
8158 * UFS device's power management needs to be controlled by "POWER CONDITION"
8159 * field of SSU (START STOP UNIT) command. But this "power condition" field
8160 * will take effect only when its sent to "UFS device" well known logical unit
8161 * hence we require the scsi_device instance to represent this logical unit in
8162 * order for the UFS host driver to send the SSU command for power management.
8163 *
8164 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
8165 * Block) LU so user space process can control this LU. User space may also
8166 * want to have access to BOOT LU.
8167 *
8168 * This function adds scsi device instances for each of all well known LUs
8169 * (except "REPORT LUNS" LU).
8170 *
8171 * Return: zero on success (all required W-LUs are added successfully),
8172 * non-zero error value on failure (if failed to add any of the required W-LU).
8173 */
ufshcd_scsi_add_wlus(struct ufs_hba * hba)8174 static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
8175 {
8176 int ret = 0;
8177 struct scsi_device *sdev_boot, *sdev_rpmb;
8178
8179 hba->ufs_device_wlun = __scsi_add_device(hba->host, 0, 0,
8180 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
8181 if (IS_ERR(hba->ufs_device_wlun)) {
8182 ret = PTR_ERR(hba->ufs_device_wlun);
8183 hba->ufs_device_wlun = NULL;
8184 goto out;
8185 }
8186 scsi_device_put(hba->ufs_device_wlun);
8187
8188 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
8189 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
8190 if (IS_ERR(sdev_rpmb)) {
8191 ret = PTR_ERR(sdev_rpmb);
8192 goto remove_ufs_device_wlun;
8193 }
8194 ufshcd_blk_pm_runtime_init(sdev_rpmb);
8195 scsi_device_put(sdev_rpmb);
8196
8197 sdev_boot = __scsi_add_device(hba->host, 0, 0,
8198 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
8199 if (IS_ERR(sdev_boot)) {
8200 dev_err(hba->dev, "%s: BOOT WLUN not found\n", __func__);
8201 } else {
8202 ufshcd_blk_pm_runtime_init(sdev_boot);
8203 scsi_device_put(sdev_boot);
8204 }
8205 goto out;
8206
8207 remove_ufs_device_wlun:
8208 scsi_remove_device(hba->ufs_device_wlun);
8209 out:
8210 return ret;
8211 }
8212
ufshcd_wb_probe(struct ufs_hba * hba,const u8 * desc_buf)8213 static void ufshcd_wb_probe(struct ufs_hba *hba, const u8 *desc_buf)
8214 {
8215 struct ufs_dev_info *dev_info = &hba->dev_info;
8216 u8 lun;
8217 u32 d_lu_wb_buf_alloc;
8218 u32 ext_ufs_feature;
8219
8220 if (!ufshcd_is_wb_allowed(hba))
8221 return;
8222
8223 /*
8224 * Probe WB only for UFS-2.2 and UFS-3.1 (and later) devices or
8225 * UFS devices with quirk UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES
8226 * enabled
8227 */
8228 if (!(dev_info->wspecversion >= 0x310 ||
8229 dev_info->wspecversion == 0x220 ||
8230 (hba->dev_quirks & UFS_DEVICE_QUIRK_SUPPORT_EXTENDED_FEATURES)))
8231 goto wb_disabled;
8232
8233 ext_ufs_feature = get_unaligned_be32(desc_buf +
8234 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8235
8236 if (!(ext_ufs_feature & UFS_DEV_WRITE_BOOSTER_SUP))
8237 goto wb_disabled;
8238
8239 /*
8240 * WB may be supported but not configured while provisioning. The spec
8241 * says, in dedicated wb buffer mode, a max of 1 lun would have wb
8242 * buffer configured.
8243 */
8244 dev_info->wb_buffer_type = desc_buf[DEVICE_DESC_PARAM_WB_TYPE];
8245
8246 dev_info->ext_wb_sup = get_unaligned_be16(desc_buf +
8247 DEVICE_DESC_PARAM_EXT_WB_SUP);
8248
8249 dev_info->b_presrv_uspc_en =
8250 desc_buf[DEVICE_DESC_PARAM_WB_PRESRV_USRSPC_EN];
8251
8252 if (dev_info->wb_buffer_type == WB_BUF_MODE_SHARED) {
8253 if (!get_unaligned_be32(desc_buf +
8254 DEVICE_DESC_PARAM_WB_SHARED_ALLOC_UNITS))
8255 goto wb_disabled;
8256 } else {
8257 for (lun = 0; lun < UFS_UPIU_MAX_WB_LUN_ID; lun++) {
8258 d_lu_wb_buf_alloc = 0;
8259 ufshcd_read_unit_desc_param(hba,
8260 lun,
8261 UNIT_DESC_PARAM_WB_BUF_ALLOC_UNITS,
8262 (u8 *)&d_lu_wb_buf_alloc,
8263 sizeof(d_lu_wb_buf_alloc));
8264 if (d_lu_wb_buf_alloc) {
8265 dev_info->wb_dedicated_lu = lun;
8266 break;
8267 }
8268 }
8269
8270 if (!d_lu_wb_buf_alloc)
8271 goto wb_disabled;
8272 }
8273
8274 if (!ufshcd_is_wb_buf_lifetime_available(hba))
8275 goto wb_disabled;
8276
8277 return;
8278
8279 wb_disabled:
8280 hba->caps &= ~UFSHCD_CAP_WB_EN;
8281 }
8282
ufshcd_temp_notif_probe(struct ufs_hba * hba,const u8 * desc_buf)8283 static void ufshcd_temp_notif_probe(struct ufs_hba *hba, const u8 *desc_buf)
8284 {
8285 struct ufs_dev_info *dev_info = &hba->dev_info;
8286 u32 ext_ufs_feature;
8287 u8 mask = 0;
8288
8289 if (!(hba->caps & UFSHCD_CAP_TEMP_NOTIF) || dev_info->wspecversion < 0x300)
8290 return;
8291
8292 ext_ufs_feature = get_unaligned_be32(desc_buf + DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8293
8294 if (ext_ufs_feature & UFS_DEV_LOW_TEMP_NOTIF)
8295 mask |= MASK_EE_TOO_LOW_TEMP;
8296
8297 if (ext_ufs_feature & UFS_DEV_HIGH_TEMP_NOTIF)
8298 mask |= MASK_EE_TOO_HIGH_TEMP;
8299
8300 if (mask) {
8301 ufshcd_enable_ee(hba, mask);
8302 ufs_hwmon_probe(hba, mask);
8303 }
8304 }
8305
ufshcd_device_lvl_exception_probe(struct ufs_hba * hba,u8 * desc_buf)8306 static void ufshcd_device_lvl_exception_probe(struct ufs_hba *hba, u8 *desc_buf)
8307 {
8308 u32 ext_ufs_feature;
8309
8310 if (hba->dev_info.wspecversion < 0x410)
8311 return;
8312
8313 ext_ufs_feature = get_unaligned_be32(desc_buf +
8314 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP);
8315 if (!(ext_ufs_feature & UFS_DEV_LVL_EXCEPTION_SUP))
8316 return;
8317
8318 atomic_set(&hba->dev_lvl_exception_count, 0);
8319 ufshcd_enable_ee(hba, MASK_EE_DEV_LVL_EXCEPTION);
8320 }
8321
ufshcd_set_rtt(struct ufs_hba * hba)8322 static void ufshcd_set_rtt(struct ufs_hba *hba)
8323 {
8324 struct ufs_dev_info *dev_info = &hba->dev_info;
8325 u32 rtt = 0;
8326 u32 dev_rtt = 0;
8327 int host_rtt_cap = hba->vops && hba->vops->max_num_rtt ?
8328 hba->vops->max_num_rtt : hba->nortt;
8329
8330 /* RTT override makes sense only for UFS-4.0 and above */
8331 if (dev_info->wspecversion < 0x400)
8332 return;
8333
8334 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8335 QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &dev_rtt)) {
8336 dev_err(hba->dev, "failed reading bMaxNumOfRTT\n");
8337 return;
8338 }
8339
8340 /* do not override if it was already written */
8341 if (dev_rtt != DEFAULT_MAX_NUM_RTT)
8342 return;
8343
8344 rtt = min_t(int, dev_info->rtt_cap, host_rtt_cap);
8345
8346 if (rtt == dev_rtt)
8347 return;
8348
8349 if (ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8350 QUERY_ATTR_IDN_MAX_NUM_OF_RTT, 0, 0, &rtt))
8351 dev_err(hba->dev, "failed writing bMaxNumOfRTT\n");
8352 }
8353
ufshcd_fixup_dev_quirks(struct ufs_hba * hba,const struct ufs_dev_quirk * fixups)8354 void ufshcd_fixup_dev_quirks(struct ufs_hba *hba,
8355 const struct ufs_dev_quirk *fixups)
8356 {
8357 const struct ufs_dev_quirk *f;
8358 struct ufs_dev_info *dev_info = &hba->dev_info;
8359
8360 if (!fixups)
8361 return;
8362
8363 for (f = fixups; f->quirk; f++) {
8364 if ((f->wmanufacturerid == dev_info->wmanufacturerid ||
8365 f->wmanufacturerid == UFS_ANY_VENDOR) &&
8366 ((dev_info->model &&
8367 STR_PRFX_EQUAL(f->model, dev_info->model)) ||
8368 !strcmp(f->model, UFS_ANY_MODEL)))
8369 hba->dev_quirks |= f->quirk;
8370 }
8371 }
8372 EXPORT_SYMBOL_GPL(ufshcd_fixup_dev_quirks);
8373
ufs_fixup_device_setup(struct ufs_hba * hba)8374 static void ufs_fixup_device_setup(struct ufs_hba *hba)
8375 {
8376 /* fix by general quirk table */
8377 ufshcd_fixup_dev_quirks(hba, ufs_fixups);
8378
8379 /* allow vendors to fix quirks */
8380 ufshcd_vops_fixup_dev_quirks(hba);
8381 }
8382
ufshcd_update_rtc(struct ufs_hba * hba)8383 static void ufshcd_update_rtc(struct ufs_hba *hba)
8384 {
8385 struct timespec64 ts64;
8386 int err;
8387 u32 val;
8388
8389 ktime_get_real_ts64(&ts64);
8390
8391 if (ts64.tv_sec < hba->dev_info.rtc_time_baseline) {
8392 dev_warn_once(hba->dev, "%s: Current time precedes previous setting!\n", __func__);
8393 return;
8394 }
8395
8396 /*
8397 * The Absolute RTC mode has a 136-year limit, spanning from 2010 to 2146. If a time beyond
8398 * 2146 is required, it is recommended to choose the relative RTC mode.
8399 */
8400 val = ts64.tv_sec - hba->dev_info.rtc_time_baseline;
8401
8402 /* Skip update RTC if RPM state is not RPM_ACTIVE */
8403 if (ufshcd_rpm_get_if_active(hba) <= 0)
8404 return;
8405
8406 err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR, QUERY_ATTR_IDN_SECONDS_PASSED,
8407 0, 0, &val);
8408 ufshcd_rpm_put(hba);
8409
8410 if (err)
8411 dev_err(hba->dev, "%s: Failed to update rtc %d\n", __func__, err);
8412 else if (hba->dev_info.rtc_type == UFS_RTC_RELATIVE)
8413 hba->dev_info.rtc_time_baseline = ts64.tv_sec;
8414 }
8415
ufshcd_rtc_work(struct work_struct * work)8416 static void ufshcd_rtc_work(struct work_struct *work)
8417 {
8418 struct ufs_hba *hba;
8419
8420 hba = container_of(to_delayed_work(work), struct ufs_hba, ufs_rtc_update_work);
8421
8422 /* Update RTC only when there are no requests in progress and UFSHCI is operational */
8423 if (!ufshcd_is_ufs_dev_busy(hba) &&
8424 hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL &&
8425 !hba->clk_gating.active_reqs)
8426 ufshcd_update_rtc(hba);
8427
8428 if (ufshcd_is_ufs_dev_active(hba) && hba->dev_info.rtc_update_period)
8429 schedule_delayed_work(&hba->ufs_rtc_update_work,
8430 msecs_to_jiffies(hba->dev_info.rtc_update_period));
8431 }
8432
ufs_init_rtc(struct ufs_hba * hba,u8 * desc_buf)8433 static void ufs_init_rtc(struct ufs_hba *hba, u8 *desc_buf)
8434 {
8435 u16 periodic_rtc_update = get_unaligned_be16(&desc_buf[DEVICE_DESC_PARAM_FRQ_RTC]);
8436 struct ufs_dev_info *dev_info = &hba->dev_info;
8437
8438 if (periodic_rtc_update & UFS_RTC_TIME_BASELINE) {
8439 dev_info->rtc_type = UFS_RTC_ABSOLUTE;
8440
8441 /*
8442 * The concept of measuring time in Linux as the number of seconds elapsed since
8443 * 00:00:00 UTC on January 1, 1970, and UFS ABS RTC is elapsed from January 1st
8444 * 2010 00:00, here we need to adjust ABS baseline.
8445 */
8446 dev_info->rtc_time_baseline = mktime64(2010, 1, 1, 0, 0, 0) -
8447 mktime64(1970, 1, 1, 0, 0, 0);
8448 } else {
8449 dev_info->rtc_type = UFS_RTC_RELATIVE;
8450 dev_info->rtc_time_baseline = 0;
8451 }
8452
8453 /*
8454 * We ignore TIME_PERIOD defined in wPeriodicRTCUpdate because Spec does not clearly state
8455 * how to calculate the specific update period for each time unit. And we disable periodic
8456 * RTC update work, let user configure by sysfs node according to specific circumstance.
8457 */
8458 dev_info->rtc_update_period = 0;
8459 }
8460
ufs_get_device_desc(struct ufs_hba * hba)8461 static int ufs_get_device_desc(struct ufs_hba *hba)
8462 {
8463 int err;
8464 u8 model_index;
8465 u8 *desc_buf;
8466 struct ufs_dev_info *dev_info = &hba->dev_info;
8467
8468 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8469 if (!desc_buf) {
8470 err = -ENOMEM;
8471 goto out;
8472 }
8473
8474 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_DEVICE, 0, 0, desc_buf,
8475 QUERY_DESC_MAX_SIZE);
8476 if (err) {
8477 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
8478 __func__, err);
8479 goto out;
8480 }
8481
8482 /*
8483 * getting vendor (manufacturerID) and Bank Index in big endian
8484 * format
8485 */
8486 dev_info->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
8487 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
8488
8489 /* getting Specification Version in big endian format */
8490 dev_info->wspecversion = desc_buf[DEVICE_DESC_PARAM_SPEC_VER] << 8 |
8491 desc_buf[DEVICE_DESC_PARAM_SPEC_VER + 1];
8492 dev_info->bqueuedepth = desc_buf[DEVICE_DESC_PARAM_Q_DPTH];
8493
8494 dev_info->rtt_cap = desc_buf[DEVICE_DESC_PARAM_RTT_CAP];
8495
8496 dev_info->hid_sup = get_unaligned_be32(desc_buf +
8497 DEVICE_DESC_PARAM_EXT_UFS_FEATURE_SUP) &
8498 UFS_DEV_HID_SUPPORT;
8499
8500 sysfs_update_group(&hba->dev->kobj, &ufs_sysfs_hid_group);
8501
8502 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
8503
8504 err = ufshcd_read_string_desc(hba, model_index,
8505 &dev_info->model, SD_ASCII_STD);
8506 if (err < 0) {
8507 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
8508 __func__, err);
8509 goto out;
8510 }
8511
8512 hba->luns_avail = desc_buf[DEVICE_DESC_PARAM_NUM_LU] +
8513 desc_buf[DEVICE_DESC_PARAM_NUM_WLU];
8514
8515 ufs_fixup_device_setup(hba);
8516
8517 ufshcd_wb_probe(hba, desc_buf);
8518
8519 ufshcd_temp_notif_probe(hba, desc_buf);
8520
8521 if (dev_info->wspecversion >= 0x410) {
8522 hba->critical_health_count = 0;
8523 ufshcd_enable_ee(hba, MASK_EE_HEALTH_CRITICAL);
8524 }
8525
8526 ufs_init_rtc(hba, desc_buf);
8527
8528 ufshcd_device_lvl_exception_probe(hba, desc_buf);
8529
8530 /*
8531 * ufshcd_read_string_desc returns size of the string
8532 * reset the error value
8533 */
8534 err = 0;
8535
8536 out:
8537 kfree(desc_buf);
8538 return err;
8539 }
8540
ufs_put_device_desc(struct ufs_hba * hba)8541 static void ufs_put_device_desc(struct ufs_hba *hba)
8542 {
8543 struct ufs_dev_info *dev_info = &hba->dev_info;
8544
8545 kfree(dev_info->model);
8546 dev_info->model = NULL;
8547 }
8548
8549 /**
8550 * ufshcd_quirk_tune_host_pa_tactivate - Ensures that host PA_TACTIVATE is
8551 * less than device PA_TACTIVATE time.
8552 * @hba: per-adapter instance
8553 *
8554 * Some UFS devices require host PA_TACTIVATE to be lower than device
8555 * PA_TACTIVATE, we need to enable UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE quirk
8556 * for such devices.
8557 *
8558 * Return: zero on success, non-zero error value on failure.
8559 */
ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba * hba)8560 static int ufshcd_quirk_tune_host_pa_tactivate(struct ufs_hba *hba)
8561 {
8562 int ret = 0;
8563 u32 granularity, peer_granularity;
8564 u32 pa_tactivate, peer_pa_tactivate;
8565 u32 pa_tactivate_us, peer_pa_tactivate_us;
8566 static const u8 gran_to_us_table[] = {1, 4, 8, 16, 32, 100};
8567
8568 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8569 &granularity);
8570 if (ret)
8571 goto out;
8572
8573 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_GRANULARITY),
8574 &peer_granularity);
8575 if (ret)
8576 goto out;
8577
8578 if ((granularity < PA_GRANULARITY_MIN_VAL) ||
8579 (granularity > PA_GRANULARITY_MAX_VAL)) {
8580 dev_err(hba->dev, "%s: invalid host PA_GRANULARITY %d",
8581 __func__, granularity);
8582 return -EINVAL;
8583 }
8584
8585 if ((peer_granularity < PA_GRANULARITY_MIN_VAL) ||
8586 (peer_granularity > PA_GRANULARITY_MAX_VAL)) {
8587 dev_err(hba->dev, "%s: invalid device PA_GRANULARITY %d",
8588 __func__, peer_granularity);
8589 return -EINVAL;
8590 }
8591
8592 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_TACTIVATE), &pa_tactivate);
8593 if (ret)
8594 goto out;
8595
8596 ret = ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_TACTIVATE),
8597 &peer_pa_tactivate);
8598 if (ret)
8599 goto out;
8600
8601 pa_tactivate_us = pa_tactivate * gran_to_us_table[granularity - 1];
8602 peer_pa_tactivate_us = peer_pa_tactivate *
8603 gran_to_us_table[peer_granularity - 1];
8604
8605 if (pa_tactivate_us >= peer_pa_tactivate_us) {
8606 u32 new_peer_pa_tactivate;
8607
8608 new_peer_pa_tactivate = pa_tactivate_us /
8609 gran_to_us_table[peer_granularity - 1];
8610 new_peer_pa_tactivate++;
8611 ret = ufshcd_dme_peer_set(hba, UIC_ARG_MIB(PA_TACTIVATE),
8612 new_peer_pa_tactivate);
8613 }
8614
8615 out:
8616 return ret;
8617 }
8618
8619 /**
8620 * ufshcd_quirk_override_pa_h8time - Ensures proper adjustment of PA_HIBERN8TIME.
8621 * @hba: per-adapter instance
8622 *
8623 * Some UFS devices require specific adjustments to the PA_HIBERN8TIME parameter
8624 * to ensure proper hibernation timing. This function retrieves the current
8625 * PA_HIBERN8TIME value and increments it by 100us.
8626 */
ufshcd_quirk_override_pa_h8time(struct ufs_hba * hba)8627 static void ufshcd_quirk_override_pa_h8time(struct ufs_hba *hba)
8628 {
8629 u32 pa_h8time;
8630 int ret;
8631
8632 ret = ufshcd_dme_get(hba, UIC_ARG_MIB(PA_HIBERN8TIME), &pa_h8time);
8633 if (ret) {
8634 dev_err(hba->dev, "Failed to get PA_HIBERN8TIME: %d\n", ret);
8635 return;
8636 }
8637
8638 /* Increment by 1 to increase hibernation time by 100 µs */
8639 ret = ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HIBERN8TIME), pa_h8time + 1);
8640 if (ret)
8641 dev_err(hba->dev, "Failed updating PA_HIBERN8TIME: %d\n", ret);
8642 }
8643
ufshcd_tune_unipro_params(struct ufs_hba * hba)8644 static void ufshcd_tune_unipro_params(struct ufs_hba *hba)
8645 {
8646 ufshcd_vops_apply_dev_quirks(hba);
8647
8648 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_TACTIVATE)
8649 /* set 1ms timeout for PA_TACTIVATE */
8650 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TACTIVATE), 10);
8651
8652 if (hba->dev_quirks & UFS_DEVICE_QUIRK_HOST_PA_TACTIVATE)
8653 ufshcd_quirk_tune_host_pa_tactivate(hba);
8654
8655 if (hba->dev_quirks & UFS_DEVICE_QUIRK_PA_HIBER8TIME)
8656 ufshcd_quirk_override_pa_h8time(hba);
8657 }
8658
ufshcd_clear_dbg_ufs_stats(struct ufs_hba * hba)8659 static void ufshcd_clear_dbg_ufs_stats(struct ufs_hba *hba)
8660 {
8661 hba->ufs_stats.hibern8_exit_cnt = 0;
8662 hba->ufs_stats.last_hibern8_exit_tstamp = ktime_set(0, 0);
8663 hba->req_abort_count = 0;
8664 }
8665
ufshcd_device_geo_params_init(struct ufs_hba * hba)8666 static int ufshcd_device_geo_params_init(struct ufs_hba *hba)
8667 {
8668 int err;
8669 u8 *desc_buf;
8670
8671 desc_buf = kzalloc(QUERY_DESC_MAX_SIZE, GFP_KERNEL);
8672 if (!desc_buf) {
8673 err = -ENOMEM;
8674 goto out;
8675 }
8676
8677 err = ufshcd_read_desc_param(hba, QUERY_DESC_IDN_GEOMETRY, 0, 0,
8678 desc_buf, QUERY_DESC_MAX_SIZE);
8679 if (err) {
8680 dev_err(hba->dev, "%s: Failed reading Geometry Desc. err = %d\n",
8681 __func__, err);
8682 goto out;
8683 }
8684
8685 if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 1)
8686 hba->dev_info.max_lu_supported = 32;
8687 else if (desc_buf[GEOMETRY_DESC_PARAM_MAX_NUM_LUN] == 0)
8688 hba->dev_info.max_lu_supported = 8;
8689
8690 out:
8691 kfree(desc_buf);
8692 return err;
8693 }
8694
8695 struct ufs_ref_clk {
8696 unsigned long freq_hz;
8697 enum ufs_ref_clk_freq val;
8698 };
8699
8700 static const struct ufs_ref_clk ufs_ref_clk_freqs[] = {
8701 {19200000, REF_CLK_FREQ_19_2_MHZ},
8702 {26000000, REF_CLK_FREQ_26_MHZ},
8703 {38400000, REF_CLK_FREQ_38_4_MHZ},
8704 {52000000, REF_CLK_FREQ_52_MHZ},
8705 {0, REF_CLK_FREQ_INVAL},
8706 };
8707
8708 static enum ufs_ref_clk_freq
ufs_get_bref_clk_from_hz(unsigned long freq)8709 ufs_get_bref_clk_from_hz(unsigned long freq)
8710 {
8711 int i;
8712
8713 for (i = 0; ufs_ref_clk_freqs[i].freq_hz; i++)
8714 if (ufs_ref_clk_freqs[i].freq_hz == freq)
8715 return ufs_ref_clk_freqs[i].val;
8716
8717 return REF_CLK_FREQ_INVAL;
8718 }
8719
ufshcd_parse_dev_ref_clk_freq(struct ufs_hba * hba,struct clk * refclk)8720 void ufshcd_parse_dev_ref_clk_freq(struct ufs_hba *hba, struct clk *refclk)
8721 {
8722 unsigned long freq;
8723
8724 freq = clk_get_rate(refclk);
8725
8726 hba->dev_ref_clk_freq =
8727 ufs_get_bref_clk_from_hz(freq);
8728
8729 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
8730 dev_err(hba->dev,
8731 "invalid ref_clk setting = %ld\n", freq);
8732 }
8733
ufshcd_set_dev_ref_clk(struct ufs_hba * hba)8734 static int ufshcd_set_dev_ref_clk(struct ufs_hba *hba)
8735 {
8736 int err;
8737 u32 ref_clk;
8738 u32 freq = hba->dev_ref_clk_freq;
8739
8740 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
8741 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &ref_clk);
8742
8743 if (err) {
8744 dev_err(hba->dev, "failed reading bRefClkFreq. err = %d\n",
8745 err);
8746 goto out;
8747 }
8748
8749 if (ref_clk == freq)
8750 goto out; /* nothing to update */
8751
8752 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
8753 QUERY_ATTR_IDN_REF_CLK_FREQ, 0, 0, &freq);
8754
8755 if (err) {
8756 dev_err(hba->dev, "bRefClkFreq setting to %lu Hz failed\n",
8757 ufs_ref_clk_freqs[freq].freq_hz);
8758 goto out;
8759 }
8760
8761 dev_dbg(hba->dev, "bRefClkFreq setting to %lu Hz succeeded\n",
8762 ufs_ref_clk_freqs[freq].freq_hz);
8763
8764 out:
8765 return err;
8766 }
8767
ufshcd_device_params_init(struct ufs_hba * hba)8768 static int ufshcd_device_params_init(struct ufs_hba *hba)
8769 {
8770 bool flag;
8771 int ret;
8772
8773 /* Init UFS geometry descriptor related parameters */
8774 ret = ufshcd_device_geo_params_init(hba);
8775 if (ret)
8776 goto out;
8777
8778 /* Check and apply UFS device quirks */
8779 ret = ufs_get_device_desc(hba);
8780 if (ret) {
8781 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
8782 __func__, ret);
8783 goto out;
8784 }
8785
8786 ufshcd_set_rtt(hba);
8787
8788 ufshcd_get_ref_clk_gating_wait(hba);
8789
8790 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
8791 QUERY_FLAG_IDN_PWR_ON_WPE, 0, &flag))
8792 hba->dev_info.f_power_on_wp_en = flag;
8793
8794 /* Probe maximum power mode co-supported by both UFS host and device */
8795 if (ufshcd_get_max_pwr_mode(hba))
8796 dev_err(hba->dev,
8797 "%s: Failed getting max supported power mode\n",
8798 __func__);
8799 out:
8800 return ret;
8801 }
8802
ufshcd_set_timestamp_attr(struct ufs_hba * hba)8803 static void ufshcd_set_timestamp_attr(struct ufs_hba *hba)
8804 {
8805 int err;
8806 struct ufs_query_req *request = NULL;
8807 struct ufs_query_res *response = NULL;
8808 struct ufs_dev_info *dev_info = &hba->dev_info;
8809 struct utp_upiu_query_v4_0 *upiu_data;
8810
8811 if (dev_info->wspecversion < 0x400 ||
8812 hba->dev_quirks & UFS_DEVICE_QUIRK_NO_TIMESTAMP_SUPPORT)
8813 return;
8814
8815 ufshcd_dev_man_lock(hba);
8816
8817 ufshcd_init_query(hba, &request, &response,
8818 UPIU_QUERY_OPCODE_WRITE_ATTR,
8819 QUERY_ATTR_IDN_TIMESTAMP, 0, 0);
8820
8821 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
8822
8823 upiu_data = (struct utp_upiu_query_v4_0 *)&request->upiu_req;
8824
8825 put_unaligned_be64(ktime_get_real_ns(), &upiu_data->osf3);
8826
8827 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, dev_cmd_timeout);
8828
8829 if (err)
8830 dev_err(hba->dev, "%s: failed to set timestamp %d\n",
8831 __func__, err);
8832
8833 ufshcd_dev_man_unlock(hba);
8834 }
8835
8836 /**
8837 * ufshcd_add_lus - probe and add UFS logical units
8838 * @hba: per-adapter instance
8839 *
8840 * Return: 0 upon success; < 0 upon failure.
8841 */
ufshcd_add_lus(struct ufs_hba * hba)8842 static int ufshcd_add_lus(struct ufs_hba *hba)
8843 {
8844 int ret;
8845
8846 /* Add required well known logical units to scsi mid layer */
8847 ret = ufshcd_scsi_add_wlus(hba);
8848 if (ret)
8849 goto out;
8850
8851 /* Initialize devfreq after UFS device is detected */
8852 if (ufshcd_is_clkscaling_supported(hba)) {
8853 memcpy(&hba->clk_scaling.saved_pwr_info,
8854 &hba->pwr_info,
8855 sizeof(struct ufs_pa_layer_attr));
8856 hba->clk_scaling.is_allowed = true;
8857
8858 ret = ufshcd_devfreq_init(hba);
8859 if (ret)
8860 goto out;
8861
8862 hba->clk_scaling.is_enabled = true;
8863 ufshcd_init_clk_scaling_sysfs(hba);
8864 }
8865
8866 /*
8867 * The RTC update code accesses the hba->ufs_device_wlun->sdev_gendev
8868 * pointer and hence must only be started after the WLUN pointer has
8869 * been initialized by ufshcd_scsi_add_wlus().
8870 */
8871 schedule_delayed_work(&hba->ufs_rtc_update_work,
8872 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
8873
8874 ufs_bsg_probe(hba);
8875 scsi_scan_host(hba->host);
8876
8877 out:
8878 return ret;
8879 }
8880
8881 /* SDB - Single Doorbell */
ufshcd_release_sdb_queue(struct ufs_hba * hba,int nutrs)8882 static void ufshcd_release_sdb_queue(struct ufs_hba *hba, int nutrs)
8883 {
8884 size_t ucdl_size, utrdl_size;
8885
8886 ucdl_size = ufshcd_get_ucd_size(hba) * nutrs;
8887 dmam_free_coherent(hba->dev, ucdl_size, hba->ucdl_base_addr,
8888 hba->ucdl_dma_addr);
8889
8890 utrdl_size = sizeof(struct utp_transfer_req_desc) * nutrs;
8891 dmam_free_coherent(hba->dev, utrdl_size, hba->utrdl_base_addr,
8892 hba->utrdl_dma_addr);
8893
8894 devm_kfree(hba->dev, hba->lrb);
8895 }
8896
ufshcd_alloc_mcq(struct ufs_hba * hba)8897 static int ufshcd_alloc_mcq(struct ufs_hba *hba)
8898 {
8899 int ret;
8900 int old_nutrs = hba->nutrs;
8901
8902 ret = ufshcd_mcq_decide_queue_depth(hba);
8903 if (ret < 0)
8904 return ret;
8905
8906 hba->nutrs = ret;
8907 ret = ufshcd_mcq_init(hba);
8908 if (ret)
8909 goto err;
8910
8911 /*
8912 * Previously allocated memory for nutrs may not be enough in MCQ mode.
8913 * Number of supported tags in MCQ mode may be larger than SDB mode.
8914 */
8915 if (hba->nutrs != old_nutrs) {
8916 ufshcd_release_sdb_queue(hba, old_nutrs);
8917 ret = ufshcd_memory_alloc(hba);
8918 if (ret)
8919 goto err;
8920 ufshcd_host_memory_configure(hba);
8921 }
8922
8923 ret = ufshcd_mcq_memory_alloc(hba);
8924 if (ret)
8925 goto err;
8926
8927 hba->host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
8928 hba->reserved_slot = hba->nutrs - UFSHCD_NUM_RESERVED;
8929
8930 return 0;
8931 err:
8932 hba->nutrs = old_nutrs;
8933 return ret;
8934 }
8935
ufshcd_config_mcq(struct ufs_hba * hba)8936 static void ufshcd_config_mcq(struct ufs_hba *hba)
8937 {
8938 int ret;
8939
8940 ret = ufshcd_mcq_vops_config_esi(hba);
8941 hba->mcq_esi_enabled = !ret;
8942 dev_info(hba->dev, "ESI %sconfigured\n", ret ? "is not " : "");
8943
8944 ufshcd_mcq_make_queues_operational(hba);
8945 ufshcd_mcq_config_mac(hba, hba->nutrs);
8946
8947 dev_info(hba->dev, "MCQ configured, nr_queues=%d, io_queues=%d, read_queue=%d, poll_queues=%d, queue_depth=%d\n",
8948 hba->nr_hw_queues, hba->nr_queues[HCTX_TYPE_DEFAULT],
8949 hba->nr_queues[HCTX_TYPE_READ], hba->nr_queues[HCTX_TYPE_POLL],
8950 hba->nutrs);
8951 }
8952
ufshcd_post_device_init(struct ufs_hba * hba)8953 static int ufshcd_post_device_init(struct ufs_hba *hba)
8954 {
8955 int ret;
8956
8957 ufshcd_tune_unipro_params(hba);
8958
8959 /* UFS device is also active now */
8960 ufshcd_set_ufs_dev_active(hba);
8961 ufshcd_force_reset_auto_bkops(hba);
8962
8963 ufshcd_set_timestamp_attr(hba);
8964
8965 if (!hba->max_pwr_info.is_valid)
8966 return 0;
8967
8968 /*
8969 * Set the right value to bRefClkFreq before attempting to
8970 * switch to HS gears.
8971 */
8972 if (hba->dev_ref_clk_freq != REF_CLK_FREQ_INVAL)
8973 ufshcd_set_dev_ref_clk(hba);
8974 /* Gear up to HS gear. */
8975 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
8976 if (ret) {
8977 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
8978 __func__, ret);
8979 return ret;
8980 }
8981
8982 return 0;
8983 }
8984
ufshcd_device_init(struct ufs_hba * hba,bool init_dev_params)8985 static int ufshcd_device_init(struct ufs_hba *hba, bool init_dev_params)
8986 {
8987 int ret;
8988
8989 WARN_ON_ONCE(!hba->scsi_host_added);
8990
8991 hba->ufshcd_state = UFSHCD_STATE_RESET;
8992
8993 ret = ufshcd_link_startup(hba);
8994 if (ret)
8995 return ret;
8996
8997 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
8998 return ret;
8999
9000 /* Debug counters initialization */
9001 ufshcd_clear_dbg_ufs_stats(hba);
9002
9003 /* UniPro link is active now */
9004 ufshcd_set_link_active(hba);
9005
9006 /* Reconfigure MCQ upon reset */
9007 if (hba->mcq_enabled && !init_dev_params) {
9008 ufshcd_config_mcq(hba);
9009 ufshcd_mcq_enable(hba);
9010 }
9011
9012 /* Verify device initialization by sending NOP OUT UPIU */
9013 ret = ufshcd_verify_dev_init(hba);
9014 if (ret)
9015 return ret;
9016
9017 /* Initiate UFS initialization, and waiting until completion */
9018 ret = ufshcd_complete_dev_init(hba);
9019 if (ret)
9020 return ret;
9021
9022 /*
9023 * Initialize UFS device parameters used by driver, these
9024 * parameters are associated with UFS descriptors.
9025 */
9026 if (init_dev_params) {
9027 ret = ufshcd_device_params_init(hba);
9028 if (ret)
9029 return ret;
9030 if (is_mcq_supported(hba) &&
9031 hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH) {
9032 ufshcd_config_mcq(hba);
9033 ufshcd_mcq_enable(hba);
9034 }
9035 }
9036
9037 return ufshcd_post_device_init(hba);
9038 }
9039
9040 /**
9041 * ufshcd_probe_hba - probe hba to detect device and initialize it
9042 * @hba: per-adapter instance
9043 * @init_dev_params: whether or not to call ufshcd_device_params_init().
9044 *
9045 * Execute link-startup and verify device initialization
9046 *
9047 * Return: 0 upon success; < 0 upon failure.
9048 */
ufshcd_probe_hba(struct ufs_hba * hba,bool init_dev_params)9049 static int ufshcd_probe_hba(struct ufs_hba *hba, bool init_dev_params)
9050 {
9051 int ret;
9052
9053 if (!hba->pm_op_in_progress &&
9054 (hba->quirks & UFSHCD_QUIRK_REINIT_AFTER_MAX_GEAR_SWITCH)) {
9055 /* Reset the device and controller before doing reinit */
9056 ufshcd_device_reset(hba);
9057 ufs_put_device_desc(hba);
9058 ufshcd_hba_stop(hba);
9059 ret = ufshcd_hba_enable(hba);
9060 if (ret) {
9061 dev_err(hba->dev, "Host controller enable failed\n");
9062 ufshcd_print_evt_hist(hba);
9063 ufshcd_print_host_state(hba);
9064 return ret;
9065 }
9066
9067 /* Reinit the device */
9068 ret = ufshcd_device_init(hba, init_dev_params);
9069 if (ret)
9070 return ret;
9071 }
9072
9073 ufshcd_print_pwr_info(hba);
9074
9075 /*
9076 * bActiveICCLevel is volatile for UFS device (as per latest v2.1 spec)
9077 * and for removable UFS card as well, hence always set the parameter.
9078 * Note: Error handler may issue the device reset hence resetting
9079 * bActiveICCLevel as well so it is always safe to set this here.
9080 */
9081 ufshcd_set_active_icc_lvl(hba);
9082
9083 /* Enable UFS Write Booster if supported */
9084 ufshcd_configure_wb(hba);
9085
9086 if (hba->ee_usr_mask)
9087 ufshcd_write_ee_control(hba);
9088 ufshcd_configure_auto_hibern8(hba);
9089
9090 return 0;
9091 }
9092
9093 /**
9094 * ufshcd_async_scan - asynchronous execution for probing hba
9095 * @data: data pointer to pass to this function
9096 * @cookie: cookie data
9097 */
ufshcd_async_scan(void * data,async_cookie_t cookie)9098 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
9099 {
9100 struct ufs_hba *hba = (struct ufs_hba *)data;
9101 ktime_t probe_start;
9102 int ret;
9103
9104 down(&hba->host_sem);
9105 /* Initialize hba, detect and initialize UFS device */
9106 probe_start = ktime_get();
9107 ret = ufshcd_probe_hba(hba, true);
9108 ufshcd_process_probe_result(hba, probe_start, ret);
9109 up(&hba->host_sem);
9110 if (ret)
9111 goto out;
9112
9113 /* Probe and add UFS logical units */
9114 ret = ufshcd_add_lus(hba);
9115
9116 out:
9117 pm_runtime_put_sync(hba->dev);
9118
9119 if (ret)
9120 dev_err(hba->dev, "%s failed: %d\n", __func__, ret);
9121 }
9122
ufshcd_eh_timed_out(struct scsi_cmnd * scmd)9123 static enum scsi_timeout_action ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
9124 {
9125 struct ufs_hba *hba = shost_priv(scmd->device->host);
9126
9127 if (!hba->system_suspending) {
9128 /* Activate the error handler in the SCSI core. */
9129 return SCSI_EH_NOT_HANDLED;
9130 }
9131
9132 /*
9133 * If we get here we know that no TMFs are outstanding and also that
9134 * the only pending command is a START STOP UNIT command. Handle the
9135 * timeout of that command directly to prevent a deadlock between
9136 * ufshcd_set_dev_pwr_mode() and ufshcd_err_handler().
9137 */
9138 ufshcd_link_recovery(hba);
9139 dev_info(hba->dev, "%s() finished; outstanding_tasks = %#lx.\n",
9140 __func__, hba->outstanding_tasks);
9141
9142 return scsi_host_busy(hba->host) ? SCSI_EH_RESET_TIMER : SCSI_EH_DONE;
9143 }
9144
9145 static const struct attribute_group *ufshcd_driver_groups[] = {
9146 &ufs_sysfs_unit_descriptor_group,
9147 &ufs_sysfs_lun_attributes_group,
9148 NULL,
9149 };
9150
9151 static struct ufs_hba_variant_params ufs_hba_vps = {
9152 .hba_enable_delay_us = 1000,
9153 .wb_flush_threshold = UFS_WB_BUF_REMAIN_PERCENT(40),
9154 .devfreq_profile.polling_ms = 100,
9155 .devfreq_profile.target = ufshcd_devfreq_target,
9156 .devfreq_profile.get_dev_status = ufshcd_devfreq_get_dev_status,
9157 .ondemand_data.upthreshold = 70,
9158 .ondemand_data.downdifferential = 5,
9159 };
9160
9161 static const struct scsi_host_template ufshcd_driver_template = {
9162 .module = THIS_MODULE,
9163 .name = UFSHCD,
9164 .proc_name = UFSHCD,
9165 .map_queues = ufshcd_map_queues,
9166 .queuecommand = ufshcd_queuecommand,
9167 .mq_poll = ufshcd_poll,
9168 .sdev_init = ufshcd_sdev_init,
9169 .sdev_configure = ufshcd_sdev_configure,
9170 .sdev_destroy = ufshcd_sdev_destroy,
9171 .change_queue_depth = ufshcd_change_queue_depth,
9172 .eh_abort_handler = ufshcd_abort,
9173 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
9174 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
9175 .eh_timed_out = ufshcd_eh_timed_out,
9176 .this_id = -1,
9177 .sg_tablesize = SG_ALL,
9178 .max_segment_size = PRDT_DATA_BYTE_COUNT_MAX,
9179 .max_sectors = SZ_1M / SECTOR_SIZE,
9180 .max_host_blocked = 1,
9181 .track_queue_depth = 1,
9182 .skip_settle_delay = 1,
9183 .sdev_groups = ufshcd_driver_groups,
9184 };
9185
ufshcd_config_vreg_load(struct device * dev,struct ufs_vreg * vreg,int ua)9186 static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
9187 int ua)
9188 {
9189 int ret;
9190
9191 if (!vreg)
9192 return 0;
9193
9194 /*
9195 * "set_load" operation shall be required on those regulators
9196 * which specifically configured current limitation. Otherwise
9197 * zero max_uA may cause unexpected behavior when regulator is
9198 * enabled or set as high power mode.
9199 */
9200 if (!vreg->max_uA)
9201 return 0;
9202
9203 ret = regulator_set_load(vreg->reg, ua);
9204 if (ret < 0) {
9205 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
9206 __func__, vreg->name, ua, ret);
9207 }
9208
9209 return ret;
9210 }
9211
ufshcd_config_vreg_lpm(struct ufs_hba * hba,struct ufs_vreg * vreg)9212 static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
9213 struct ufs_vreg *vreg)
9214 {
9215 return ufshcd_config_vreg_load(hba->dev, vreg, UFS_VREG_LPM_LOAD_UA);
9216 }
9217
ufshcd_config_vreg_hpm(struct ufs_hba * hba,struct ufs_vreg * vreg)9218 static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
9219 struct ufs_vreg *vreg)
9220 {
9221 if (!vreg)
9222 return 0;
9223
9224 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
9225 }
9226
ufshcd_config_vreg(struct device * dev,struct ufs_vreg * vreg,bool on)9227 static int ufshcd_config_vreg(struct device *dev,
9228 struct ufs_vreg *vreg, bool on)
9229 {
9230 if (regulator_count_voltages(vreg->reg) <= 0)
9231 return 0;
9232
9233 return ufshcd_config_vreg_load(dev, vreg, on ? vreg->max_uA : 0);
9234 }
9235
ufshcd_enable_vreg(struct device * dev,struct ufs_vreg * vreg)9236 static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
9237 {
9238 int ret = 0;
9239
9240 if (!vreg || vreg->enabled)
9241 goto out;
9242
9243 ret = ufshcd_config_vreg(dev, vreg, true);
9244 if (!ret)
9245 ret = regulator_enable(vreg->reg);
9246
9247 if (!ret)
9248 vreg->enabled = true;
9249 else
9250 dev_err(dev, "%s: %s enable failed, err=%d\n",
9251 __func__, vreg->name, ret);
9252 out:
9253 return ret;
9254 }
9255
ufshcd_disable_vreg(struct device * dev,struct ufs_vreg * vreg)9256 static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
9257 {
9258 int ret = 0;
9259
9260 if (!vreg || !vreg->enabled || vreg->always_on)
9261 goto out;
9262
9263 ret = regulator_disable(vreg->reg);
9264
9265 if (!ret) {
9266 /* ignore errors on applying disable config */
9267 ufshcd_config_vreg(dev, vreg, false);
9268 vreg->enabled = false;
9269 } else {
9270 dev_err(dev, "%s: %s disable failed, err=%d\n",
9271 __func__, vreg->name, ret);
9272 }
9273 out:
9274 return ret;
9275 }
9276
ufshcd_setup_vreg(struct ufs_hba * hba,bool on)9277 static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
9278 {
9279 int ret = 0;
9280 struct device *dev = hba->dev;
9281 struct ufs_vreg_info *info = &hba->vreg_info;
9282
9283 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
9284 if (ret)
9285 goto out;
9286
9287 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
9288 if (ret)
9289 goto out;
9290
9291 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
9292
9293 out:
9294 if (ret) {
9295 ufshcd_toggle_vreg(dev, info->vccq2, false);
9296 ufshcd_toggle_vreg(dev, info->vccq, false);
9297 ufshcd_toggle_vreg(dev, info->vcc, false);
9298 }
9299 return ret;
9300 }
9301
ufshcd_setup_hba_vreg(struct ufs_hba * hba,bool on)9302 static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
9303 {
9304 struct ufs_vreg_info *info = &hba->vreg_info;
9305
9306 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
9307 }
9308
ufshcd_get_vreg(struct device * dev,struct ufs_vreg * vreg)9309 int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
9310 {
9311 int ret = 0;
9312
9313 if (!vreg)
9314 goto out;
9315
9316 vreg->reg = devm_regulator_get(dev, vreg->name);
9317 if (IS_ERR(vreg->reg)) {
9318 ret = PTR_ERR(vreg->reg);
9319 dev_err(dev, "%s: %s get failed, err=%d\n",
9320 __func__, vreg->name, ret);
9321 }
9322 out:
9323 return ret;
9324 }
9325 EXPORT_SYMBOL_GPL(ufshcd_get_vreg);
9326
ufshcd_init_vreg(struct ufs_hba * hba)9327 static int ufshcd_init_vreg(struct ufs_hba *hba)
9328 {
9329 int ret = 0;
9330 struct device *dev = hba->dev;
9331 struct ufs_vreg_info *info = &hba->vreg_info;
9332
9333 ret = ufshcd_get_vreg(dev, info->vcc);
9334 if (ret)
9335 goto out;
9336
9337 ret = ufshcd_get_vreg(dev, info->vccq);
9338 if (!ret)
9339 ret = ufshcd_get_vreg(dev, info->vccq2);
9340 out:
9341 return ret;
9342 }
9343
ufshcd_init_hba_vreg(struct ufs_hba * hba)9344 static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
9345 {
9346 struct ufs_vreg_info *info = &hba->vreg_info;
9347
9348 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
9349 }
9350
ufshcd_setup_clocks(struct ufs_hba * hba,bool on)9351 static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
9352 {
9353 int ret = 0;
9354 struct ufs_clk_info *clki;
9355 struct list_head *head = &hba->clk_list_head;
9356 ktime_t start = ktime_get();
9357 bool clk_state_changed = false;
9358
9359 if (list_empty(head))
9360 goto out;
9361
9362 ret = ufshcd_vops_setup_clocks(hba, on, PRE_CHANGE);
9363 if (ret)
9364 return ret;
9365
9366 list_for_each_entry(clki, head, list) {
9367 if (!IS_ERR_OR_NULL(clki->clk)) {
9368 /*
9369 * Don't disable clocks which are needed
9370 * to keep the link active.
9371 */
9372 if (ufshcd_is_link_active(hba) &&
9373 clki->keep_link_active)
9374 continue;
9375
9376 clk_state_changed = on ^ clki->enabled;
9377 if (on && !clki->enabled) {
9378 ret = clk_prepare_enable(clki->clk);
9379 if (ret) {
9380 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
9381 __func__, clki->name, ret);
9382 goto out;
9383 }
9384 } else if (!on && clki->enabled) {
9385 clk_disable_unprepare(clki->clk);
9386 }
9387 clki->enabled = on;
9388 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
9389 clki->name, on ? "en" : "dis");
9390 }
9391 }
9392
9393 ret = ufshcd_vops_setup_clocks(hba, on, POST_CHANGE);
9394 if (ret)
9395 return ret;
9396
9397 if (!ufshcd_is_clkscaling_supported(hba))
9398 ufshcd_pm_qos_update(hba, on);
9399 out:
9400 if (ret) {
9401 list_for_each_entry(clki, head, list) {
9402 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
9403 clk_disable_unprepare(clki->clk);
9404 }
9405 } else if (!ret && on && hba->clk_gating.is_initialized) {
9406 scoped_guard(spinlock_irqsave, &hba->clk_gating.lock)
9407 hba->clk_gating.state = CLKS_ON;
9408 trace_ufshcd_clk_gating(hba,
9409 hba->clk_gating.state);
9410 }
9411
9412 if (clk_state_changed)
9413 trace_ufshcd_profile_clk_gating(hba,
9414 (on ? "on" : "off"),
9415 ktime_to_us(ktime_sub(ktime_get(), start)), ret);
9416 return ret;
9417 }
9418
ufshcd_parse_ref_clk_property(struct ufs_hba * hba)9419 static enum ufs_ref_clk_freq ufshcd_parse_ref_clk_property(struct ufs_hba *hba)
9420 {
9421 u32 freq;
9422 int ret = device_property_read_u32(hba->dev, "ref-clk-freq", &freq);
9423
9424 if (ret) {
9425 dev_dbg(hba->dev, "Cannot query 'ref-clk-freq' property = %d", ret);
9426 return REF_CLK_FREQ_INVAL;
9427 }
9428
9429 return ufs_get_bref_clk_from_hz(freq);
9430 }
9431
ufshcd_init_clocks(struct ufs_hba * hba)9432 static int ufshcd_init_clocks(struct ufs_hba *hba)
9433 {
9434 int ret = 0;
9435 struct ufs_clk_info *clki;
9436 struct device *dev = hba->dev;
9437 struct list_head *head = &hba->clk_list_head;
9438
9439 if (list_empty(head))
9440 goto out;
9441
9442 list_for_each_entry(clki, head, list) {
9443 if (!clki->name)
9444 continue;
9445
9446 clki->clk = devm_clk_get(dev, clki->name);
9447 if (IS_ERR(clki->clk)) {
9448 ret = PTR_ERR(clki->clk);
9449 dev_err(dev, "%s: %s clk get failed, %d\n",
9450 __func__, clki->name, ret);
9451 goto out;
9452 }
9453
9454 /*
9455 * Parse device ref clk freq as per device tree "ref_clk".
9456 * Default dev_ref_clk_freq is set to REF_CLK_FREQ_INVAL
9457 * in ufshcd_alloc_host().
9458 */
9459 if (!strcmp(clki->name, "ref_clk"))
9460 ufshcd_parse_dev_ref_clk_freq(hba, clki->clk);
9461
9462 if (clki->max_freq) {
9463 ret = clk_set_rate(clki->clk, clki->max_freq);
9464 if (ret) {
9465 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
9466 __func__, clki->name,
9467 clki->max_freq, ret);
9468 goto out;
9469 }
9470 clki->curr_freq = clki->max_freq;
9471 }
9472 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
9473 clki->name, clk_get_rate(clki->clk));
9474 }
9475
9476 /* Set Max. frequency for all clocks */
9477 if (hba->use_pm_opp) {
9478 ret = ufshcd_opp_set_rate(hba, ULONG_MAX);
9479 if (ret) {
9480 dev_err(hba->dev, "%s: failed to set OPP: %d", __func__,
9481 ret);
9482 goto out;
9483 }
9484 }
9485
9486 out:
9487 return ret;
9488 }
9489
ufshcd_variant_hba_init(struct ufs_hba * hba)9490 static int ufshcd_variant_hba_init(struct ufs_hba *hba)
9491 {
9492 int err = 0;
9493
9494 if (!hba->vops)
9495 goto out;
9496
9497 err = ufshcd_vops_init(hba);
9498 if (err)
9499 dev_err_probe(hba->dev, err,
9500 "%s: variant %s init failed with err %d\n",
9501 __func__, ufshcd_get_var_name(hba), err);
9502 out:
9503 return err;
9504 }
9505
ufshcd_variant_hba_exit(struct ufs_hba * hba)9506 static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
9507 {
9508 if (!hba->vops)
9509 return;
9510
9511 ufshcd_vops_exit(hba);
9512 }
9513
ufshcd_hba_init(struct ufs_hba * hba)9514 static int ufshcd_hba_init(struct ufs_hba *hba)
9515 {
9516 int err;
9517
9518 /*
9519 * Handle host controller power separately from the UFS device power
9520 * rails as it will help controlling the UFS host controller power
9521 * collapse easily which is different than UFS device power collapse.
9522 * Also, enable the host controller power before we go ahead with rest
9523 * of the initialization here.
9524 */
9525 err = ufshcd_init_hba_vreg(hba);
9526 if (err)
9527 goto out;
9528
9529 err = ufshcd_setup_hba_vreg(hba, true);
9530 if (err)
9531 goto out;
9532
9533 err = ufshcd_init_clocks(hba);
9534 if (err)
9535 goto out_disable_hba_vreg;
9536
9537 if (hba->dev_ref_clk_freq == REF_CLK_FREQ_INVAL)
9538 hba->dev_ref_clk_freq = ufshcd_parse_ref_clk_property(hba);
9539
9540 err = ufshcd_setup_clocks(hba, true);
9541 if (err)
9542 goto out_disable_hba_vreg;
9543
9544 err = ufshcd_init_vreg(hba);
9545 if (err)
9546 goto out_disable_clks;
9547
9548 err = ufshcd_setup_vreg(hba, true);
9549 if (err)
9550 goto out_disable_clks;
9551
9552 err = ufshcd_variant_hba_init(hba);
9553 if (err)
9554 goto out_disable_vreg;
9555
9556 ufs_debugfs_hba_init(hba);
9557 ufs_fault_inject_hba_init(hba);
9558
9559 hba->is_powered = true;
9560 goto out;
9561
9562 out_disable_vreg:
9563 ufshcd_setup_vreg(hba, false);
9564 out_disable_clks:
9565 ufshcd_setup_clocks(hba, false);
9566 out_disable_hba_vreg:
9567 ufshcd_setup_hba_vreg(hba, false);
9568 out:
9569 return err;
9570 }
9571
ufshcd_hba_exit(struct ufs_hba * hba)9572 static void ufshcd_hba_exit(struct ufs_hba *hba)
9573 {
9574 if (hba->is_powered) {
9575 ufshcd_pm_qos_exit(hba);
9576 ufshcd_exit_clk_scaling(hba);
9577 ufshcd_exit_clk_gating(hba);
9578 if (hba->eh_wq)
9579 destroy_workqueue(hba->eh_wq);
9580 ufs_debugfs_hba_exit(hba);
9581 ufshcd_variant_hba_exit(hba);
9582 ufshcd_setup_vreg(hba, false);
9583 ufshcd_setup_clocks(hba, false);
9584 ufshcd_setup_hba_vreg(hba, false);
9585 hba->is_powered = false;
9586 ufs_put_device_desc(hba);
9587 }
9588 }
9589
ufshcd_execute_start_stop(struct scsi_device * sdev,enum ufs_dev_pwr_mode pwr_mode,struct scsi_sense_hdr * sshdr)9590 static int ufshcd_execute_start_stop(struct scsi_device *sdev,
9591 enum ufs_dev_pwr_mode pwr_mode,
9592 struct scsi_sense_hdr *sshdr)
9593 {
9594 const unsigned char cdb[6] = { START_STOP, 0, 0, 0, pwr_mode << 4, 0 };
9595 struct scsi_failure failure_defs[] = {
9596 {
9597 .allowed = 2,
9598 .result = SCMD_FAILURE_RESULT_ANY,
9599 },
9600 };
9601 struct scsi_failures failures = {
9602 .failure_definitions = failure_defs,
9603 };
9604 const struct scsi_exec_args args = {
9605 .failures = &failures,
9606 .sshdr = sshdr,
9607 .req_flags = BLK_MQ_REQ_PM,
9608 .scmd_flags = SCMD_FAIL_IF_RECOVERING,
9609 };
9610
9611 return scsi_execute_cmd(sdev, cdb, REQ_OP_DRV_IN, /*buffer=*/NULL,
9612 /*bufflen=*/0, /*timeout=*/10 * HZ, /*retries=*/0,
9613 &args);
9614 }
9615
9616 /**
9617 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
9618 * power mode
9619 * @hba: per adapter instance
9620 * @pwr_mode: device power mode to set
9621 *
9622 * Return: 0 if requested power mode is set successfully;
9623 * < 0 if failed to set the requested power mode.
9624 */
ufshcd_set_dev_pwr_mode(struct ufs_hba * hba,enum ufs_dev_pwr_mode pwr_mode)9625 static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
9626 enum ufs_dev_pwr_mode pwr_mode)
9627 {
9628 struct scsi_sense_hdr sshdr;
9629 struct scsi_device *sdp;
9630 unsigned long flags;
9631 int ret;
9632
9633 spin_lock_irqsave(hba->host->host_lock, flags);
9634 sdp = hba->ufs_device_wlun;
9635 if (sdp && scsi_device_online(sdp))
9636 ret = scsi_device_get(sdp);
9637 else
9638 ret = -ENODEV;
9639 spin_unlock_irqrestore(hba->host->host_lock, flags);
9640
9641 if (ret)
9642 return ret;
9643
9644 /*
9645 * If scsi commands fail, the scsi mid-layer schedules scsi error-
9646 * handling, which would wait for host to be resumed. Since we know
9647 * we are functional while we are here, skip host resume in error
9648 * handling context.
9649 */
9650 hba->host->eh_noresume = 1;
9651
9652 /*
9653 * Current function would be generally called from the power management
9654 * callbacks hence set the RQF_PM flag so that it doesn't resume the
9655 * already suspended childs.
9656 */
9657 ret = ufshcd_execute_start_stop(sdp, pwr_mode, &sshdr);
9658 if (ret) {
9659 sdev_printk(KERN_WARNING, sdp,
9660 "START_STOP failed for power mode: %d, result %x\n",
9661 pwr_mode, ret);
9662 if (ret > 0) {
9663 if (scsi_sense_valid(&sshdr))
9664 scsi_print_sense_hdr(sdp, NULL, &sshdr);
9665 ret = -EIO;
9666 }
9667 } else {
9668 hba->curr_dev_pwr_mode = pwr_mode;
9669 }
9670
9671 scsi_device_put(sdp);
9672 hba->host->eh_noresume = 0;
9673 return ret;
9674 }
9675
ufshcd_link_state_transition(struct ufs_hba * hba,enum uic_link_state req_link_state,bool check_for_bkops)9676 static int ufshcd_link_state_transition(struct ufs_hba *hba,
9677 enum uic_link_state req_link_state,
9678 bool check_for_bkops)
9679 {
9680 int ret = 0;
9681
9682 if (req_link_state == hba->uic_link_state)
9683 return 0;
9684
9685 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
9686 ret = ufshcd_uic_hibern8_enter(hba);
9687 if (!ret) {
9688 ufshcd_set_link_hibern8(hba);
9689 } else {
9690 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9691 __func__, ret);
9692 goto out;
9693 }
9694 }
9695 /*
9696 * If autobkops is enabled, link can't be turned off because
9697 * turning off the link would also turn off the device, except in the
9698 * case of DeepSleep where the device is expected to remain powered.
9699 */
9700 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
9701 (!check_for_bkops || !hba->auto_bkops_enabled)) {
9702 /*
9703 * Let's make sure that link is in low power mode, we are doing
9704 * this currently by putting the link in Hibern8. Otherway to
9705 * put the link in low power mode is to send the DME end point
9706 * to device and then send the DME reset command to local
9707 * unipro. But putting the link in hibern8 is much faster.
9708 *
9709 * Note also that putting the link in Hibern8 is a requirement
9710 * for entering DeepSleep.
9711 */
9712 ret = ufshcd_uic_hibern8_enter(hba);
9713 if (ret) {
9714 dev_err(hba->dev, "%s: hibern8 enter failed %d\n",
9715 __func__, ret);
9716 goto out;
9717 }
9718 /*
9719 * Change controller state to "reset state" which
9720 * should also put the link in off/reset state
9721 */
9722 ufshcd_hba_stop(hba);
9723 /*
9724 * TODO: Check if we need any delay to make sure that
9725 * controller is reset
9726 */
9727 ufshcd_set_link_off(hba);
9728 }
9729
9730 out:
9731 return ret;
9732 }
9733
ufshcd_vreg_set_lpm(struct ufs_hba * hba)9734 static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
9735 {
9736 bool vcc_off = false;
9737
9738 /*
9739 * It seems some UFS devices may keep drawing more than sleep current
9740 * (atleast for 500us) from UFS rails (especially from VCCQ rail).
9741 * To avoid this situation, add 2ms delay before putting these UFS
9742 * rails in LPM mode.
9743 */
9744 if (!ufshcd_is_link_active(hba) &&
9745 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_BEFORE_LPM)
9746 usleep_range(2000, 2100);
9747
9748 /*
9749 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
9750 * power.
9751 *
9752 * If UFS device and link is in OFF state, all power supplies (VCC,
9753 * VCCQ, VCCQ2) can be turned off if power on write protect is not
9754 * required. If UFS link is inactive (Hibern8 or OFF state) and device
9755 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
9756 *
9757 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
9758 * in low power state which would save some power.
9759 *
9760 * If Write Booster is enabled and the device needs to flush the WB
9761 * buffer OR if bkops status is urgent for WB, keep Vcc on.
9762 */
9763 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9764 !hba->dev_info.is_lu_power_on_wp) {
9765 ufshcd_setup_vreg(hba, false);
9766 vcc_off = true;
9767 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9768 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9769 vcc_off = true;
9770 if (ufshcd_is_link_hibern8(hba) || ufshcd_is_link_off(hba)) {
9771 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9772 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
9773 }
9774 }
9775
9776 /*
9777 * Some UFS devices require delay after VCC power rail is turned-off.
9778 */
9779 if (vcc_off && hba->vreg_info.vcc &&
9780 hba->dev_quirks & UFS_DEVICE_QUIRK_DELAY_AFTER_LPM)
9781 usleep_range(5000, 5100);
9782 }
9783
9784 #ifdef CONFIG_PM
ufshcd_vreg_set_hpm(struct ufs_hba * hba)9785 static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
9786 {
9787 int ret = 0;
9788
9789 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
9790 !hba->dev_info.is_lu_power_on_wp) {
9791 ret = ufshcd_setup_vreg(hba, true);
9792 } else if (!ufshcd_is_ufs_dev_active(hba)) {
9793 if (!ufshcd_is_link_active(hba)) {
9794 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
9795 if (ret)
9796 goto vcc_disable;
9797 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
9798 if (ret)
9799 goto vccq_lpm;
9800 }
9801 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
9802 }
9803 goto out;
9804
9805 vccq_lpm:
9806 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
9807 vcc_disable:
9808 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
9809 out:
9810 return ret;
9811 }
9812 #endif /* CONFIG_PM */
9813
ufshcd_hba_vreg_set_lpm(struct ufs_hba * hba)9814 static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
9815 {
9816 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9817 ufshcd_setup_hba_vreg(hba, false);
9818 }
9819
ufshcd_hba_vreg_set_hpm(struct ufs_hba * hba)9820 static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
9821 {
9822 if (ufshcd_is_link_off(hba) || ufshcd_can_aggressive_pc(hba))
9823 ufshcd_setup_hba_vreg(hba, true);
9824 }
9825
__ufshcd_wl_suspend(struct ufs_hba * hba,enum ufs_pm_op pm_op)9826 static int __ufshcd_wl_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
9827 {
9828 int ret = 0;
9829 bool check_for_bkops;
9830 enum ufs_pm_level pm_lvl;
9831 enum ufs_dev_pwr_mode req_dev_pwr_mode;
9832 enum uic_link_state req_link_state;
9833
9834 hba->pm_op_in_progress = true;
9835 if (pm_op != UFS_SHUTDOWN_PM) {
9836 pm_lvl = pm_op == UFS_RUNTIME_PM ?
9837 hba->rpm_lvl : hba->spm_lvl;
9838 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
9839 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
9840 } else {
9841 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
9842 req_link_state = UIC_LINK_OFF_STATE;
9843 }
9844
9845 /*
9846 * If we can't transition into any of the low power modes
9847 * just gate the clocks.
9848 */
9849 ufshcd_hold(hba);
9850 hba->clk_gating.is_suspended = true;
9851
9852 if (ufshcd_is_clkscaling_supported(hba))
9853 ufshcd_clk_scaling_suspend(hba, true);
9854
9855 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
9856 req_link_state == UIC_LINK_ACTIVE_STATE) {
9857 goto vops_suspend;
9858 }
9859
9860 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
9861 (req_link_state == hba->uic_link_state))
9862 goto enable_scaling;
9863
9864 /* UFS device & link must be active before we enter in this function */
9865 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
9866 /* Wait err handler finish or trigger err recovery */
9867 if (!ufshcd_eh_in_progress(hba))
9868 ufshcd_force_error_recovery(hba);
9869 ret = -EBUSY;
9870 goto enable_scaling;
9871 }
9872
9873 if (pm_op == UFS_RUNTIME_PM) {
9874 if (ufshcd_can_autobkops_during_suspend(hba)) {
9875 /*
9876 * The device is idle with no requests in the queue,
9877 * allow background operations if bkops status shows
9878 * that performance might be impacted.
9879 */
9880 ret = ufshcd_bkops_ctrl(hba);
9881 if (ret) {
9882 /*
9883 * If return err in suspend flow, IO will hang.
9884 * Trigger error handler and break suspend for
9885 * error recovery.
9886 */
9887 ufshcd_force_error_recovery(hba);
9888 ret = -EBUSY;
9889 goto enable_scaling;
9890 }
9891 } else {
9892 /* make sure that auto bkops is disabled */
9893 ufshcd_disable_auto_bkops(hba);
9894 }
9895 /*
9896 * If device needs to do BKOP or WB buffer flush during
9897 * Hibern8, keep device power mode as "active power mode"
9898 * and VCC supply.
9899 */
9900 hba->dev_info.b_rpm_dev_flush_capable =
9901 hba->auto_bkops_enabled ||
9902 (((req_link_state == UIC_LINK_HIBERN8_STATE) ||
9903 ((req_link_state == UIC_LINK_ACTIVE_STATE) &&
9904 ufshcd_is_auto_hibern8_enabled(hba))) &&
9905 ufshcd_wb_need_flush(hba));
9906 }
9907
9908 flush_work(&hba->eeh_work);
9909
9910 ret = ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
9911 if (ret)
9912 goto enable_scaling;
9913
9914 if (req_dev_pwr_mode != hba->curr_dev_pwr_mode) {
9915 if (pm_op != UFS_RUNTIME_PM)
9916 /* ensure that bkops is disabled */
9917 ufshcd_disable_auto_bkops(hba);
9918
9919 if (!hba->dev_info.b_rpm_dev_flush_capable) {
9920 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
9921 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9922 /*
9923 * If return err in suspend flow, IO will hang.
9924 * Trigger error handler and break suspend for
9925 * error recovery.
9926 */
9927 ufshcd_force_error_recovery(hba);
9928 ret = -EBUSY;
9929 }
9930 if (ret)
9931 goto enable_scaling;
9932 }
9933 }
9934
9935 /*
9936 * In the case of DeepSleep, the device is expected to remain powered
9937 * with the link off, so do not check for bkops.
9938 */
9939 check_for_bkops = !ufshcd_is_ufs_dev_deepsleep(hba);
9940 ret = ufshcd_link_state_transition(hba, req_link_state, check_for_bkops);
9941 if (ret && pm_op != UFS_SHUTDOWN_PM) {
9942 /*
9943 * If return err in suspend flow, IO will hang.
9944 * Trigger error handler and break suspend for
9945 * error recovery.
9946 */
9947 ufshcd_force_error_recovery(hba);
9948 ret = -EBUSY;
9949 }
9950 if (ret)
9951 goto set_dev_active;
9952
9953 vops_suspend:
9954 /*
9955 * Call vendor specific suspend callback. As these callbacks may access
9956 * vendor specific host controller register space call them before the
9957 * host clocks are ON.
9958 */
9959 ret = ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
9960 if (ret)
9961 goto set_link_active;
9962
9963 cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
9964 goto out;
9965
9966 set_link_active:
9967 /*
9968 * Device hardware reset is required to exit DeepSleep. Also, for
9969 * DeepSleep, the link is off so host reset and restore will be done
9970 * further below.
9971 */
9972 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9973 ufshcd_device_reset(hba);
9974 WARN_ON(!ufshcd_is_link_off(hba));
9975 }
9976 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
9977 ufshcd_set_link_active(hba);
9978 else if (ufshcd_is_link_off(hba))
9979 ufshcd_host_reset_and_restore(hba);
9980 set_dev_active:
9981 /* Can also get here needing to exit DeepSleep */
9982 if (ufshcd_is_ufs_dev_deepsleep(hba)) {
9983 ufshcd_device_reset(hba);
9984 ufshcd_host_reset_and_restore(hba);
9985 }
9986 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
9987 ufshcd_disable_auto_bkops(hba);
9988 enable_scaling:
9989 if (ufshcd_is_clkscaling_supported(hba))
9990 ufshcd_clk_scaling_suspend(hba, false);
9991
9992 hba->dev_info.b_rpm_dev_flush_capable = false;
9993 out:
9994 if (hba->dev_info.b_rpm_dev_flush_capable) {
9995 schedule_delayed_work(&hba->rpm_dev_flush_recheck_work,
9996 msecs_to_jiffies(RPM_DEV_FLUSH_RECHECK_WORK_DELAY_MS));
9997 }
9998
9999 if (ret) {
10000 ufshcd_update_evt_hist(hba, UFS_EVT_WL_SUSP_ERR, (u32)ret);
10001 hba->clk_gating.is_suspended = false;
10002 ufshcd_release(hba);
10003 }
10004 hba->pm_op_in_progress = false;
10005 return ret;
10006 }
10007
10008 #ifdef CONFIG_PM
__ufshcd_wl_resume(struct ufs_hba * hba,enum ufs_pm_op pm_op)10009 static int __ufshcd_wl_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
10010 {
10011 int ret;
10012 enum uic_link_state old_link_state = hba->uic_link_state;
10013
10014 hba->pm_op_in_progress = true;
10015
10016 /*
10017 * Call vendor specific resume callback. As these callbacks may access
10018 * vendor specific host controller register space call them when the
10019 * host clocks are ON.
10020 */
10021 ret = ufshcd_vops_resume(hba, pm_op);
10022 if (ret)
10023 goto out;
10024
10025 /* For DeepSleep, the only supported option is to have the link off */
10026 WARN_ON(ufshcd_is_ufs_dev_deepsleep(hba) && !ufshcd_is_link_off(hba));
10027
10028 if (ufshcd_is_link_hibern8(hba)) {
10029 ret = ufshcd_uic_hibern8_exit(hba);
10030 if (!ret) {
10031 ufshcd_set_link_active(hba);
10032 } else {
10033 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
10034 __func__, ret);
10035 goto vendor_suspend;
10036 }
10037 } else if (ufshcd_is_link_off(hba)) {
10038 /*
10039 * A full initialization of the host and the device is
10040 * required since the link was put to off during suspend.
10041 * Note, in the case of DeepSleep, the device will exit
10042 * DeepSleep due to device reset.
10043 */
10044 ret = ufshcd_reset_and_restore(hba);
10045 /*
10046 * ufshcd_reset_and_restore() should have already
10047 * set the link state as active
10048 */
10049 if (ret || !ufshcd_is_link_active(hba))
10050 goto vendor_suspend;
10051 }
10052
10053 if (!ufshcd_is_ufs_dev_active(hba)) {
10054 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
10055 if (ret)
10056 goto set_old_link_state;
10057 ufshcd_set_timestamp_attr(hba);
10058 schedule_delayed_work(&hba->ufs_rtc_update_work,
10059 msecs_to_jiffies(UFS_RTC_UPDATE_INTERVAL_MS));
10060 }
10061
10062 if (ufshcd_keep_autobkops_enabled_except_suspend(hba))
10063 ufshcd_enable_auto_bkops(hba);
10064 else
10065 /*
10066 * If BKOPs operations are urgently needed at this moment then
10067 * keep auto-bkops enabled or else disable it.
10068 */
10069 ufshcd_bkops_ctrl(hba);
10070
10071 if (hba->ee_usr_mask)
10072 ufshcd_write_ee_control(hba);
10073
10074 if (ufshcd_is_clkscaling_supported(hba))
10075 ufshcd_clk_scaling_suspend(hba, false);
10076
10077 if (hba->dev_info.b_rpm_dev_flush_capable) {
10078 hba->dev_info.b_rpm_dev_flush_capable = false;
10079 cancel_delayed_work(&hba->rpm_dev_flush_recheck_work);
10080 }
10081
10082 ufshcd_configure_auto_hibern8(hba);
10083
10084 goto out;
10085
10086 set_old_link_state:
10087 ufshcd_link_state_transition(hba, old_link_state, 0);
10088 vendor_suspend:
10089 ufshcd_vops_suspend(hba, pm_op, PRE_CHANGE);
10090 ufshcd_vops_suspend(hba, pm_op, POST_CHANGE);
10091 out:
10092 if (ret)
10093 ufshcd_update_evt_hist(hba, UFS_EVT_WL_RES_ERR, (u32)ret);
10094 hba->clk_gating.is_suspended = false;
10095 ufshcd_release(hba);
10096 hba->pm_op_in_progress = false;
10097 return ret;
10098 }
10099
ufshcd_wl_runtime_suspend(struct device * dev)10100 static int ufshcd_wl_runtime_suspend(struct device *dev)
10101 {
10102 struct scsi_device *sdev = to_scsi_device(dev);
10103 struct ufs_hba *hba;
10104 int ret;
10105 ktime_t start = ktime_get();
10106
10107 hba = shost_priv(sdev->host);
10108
10109 ret = __ufshcd_wl_suspend(hba, UFS_RUNTIME_PM);
10110 if (ret)
10111 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10112
10113 trace_ufshcd_wl_runtime_suspend(hba, ret,
10114 ktime_to_us(ktime_sub(ktime_get(), start)),
10115 hba->curr_dev_pwr_mode, hba->uic_link_state);
10116
10117 return ret;
10118 }
10119
ufshcd_wl_runtime_resume(struct device * dev)10120 static int ufshcd_wl_runtime_resume(struct device *dev)
10121 {
10122 struct scsi_device *sdev = to_scsi_device(dev);
10123 struct ufs_hba *hba;
10124 int ret = 0;
10125 ktime_t start = ktime_get();
10126
10127 hba = shost_priv(sdev->host);
10128
10129 ret = __ufshcd_wl_resume(hba, UFS_RUNTIME_PM);
10130 if (ret)
10131 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10132
10133 trace_ufshcd_wl_runtime_resume(hba, ret,
10134 ktime_to_us(ktime_sub(ktime_get(), start)),
10135 hba->curr_dev_pwr_mode, hba->uic_link_state);
10136
10137 return ret;
10138 }
10139 #endif
10140
10141 #ifdef CONFIG_PM_SLEEP
ufshcd_wl_suspend(struct device * dev)10142 static int ufshcd_wl_suspend(struct device *dev)
10143 {
10144 struct scsi_device *sdev = to_scsi_device(dev);
10145 struct ufs_hba *hba;
10146 int ret = 0;
10147 ktime_t start = ktime_get();
10148
10149 hba = shost_priv(sdev->host);
10150 down(&hba->host_sem);
10151 hba->system_suspending = true;
10152
10153 if (pm_runtime_suspended(dev))
10154 goto out;
10155
10156 ret = __ufshcd_wl_suspend(hba, UFS_SYSTEM_PM);
10157 if (ret) {
10158 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10159 up(&hba->host_sem);
10160 }
10161
10162 out:
10163 if (!ret)
10164 hba->is_sys_suspended = true;
10165 trace_ufshcd_wl_suspend(hba, ret,
10166 ktime_to_us(ktime_sub(ktime_get(), start)),
10167 hba->curr_dev_pwr_mode, hba->uic_link_state);
10168
10169 return ret;
10170 }
10171
ufshcd_wl_resume(struct device * dev)10172 static int ufshcd_wl_resume(struct device *dev)
10173 {
10174 struct scsi_device *sdev = to_scsi_device(dev);
10175 struct ufs_hba *hba;
10176 int ret = 0;
10177 ktime_t start = ktime_get();
10178
10179 hba = shost_priv(sdev->host);
10180
10181 if (pm_runtime_suspended(dev))
10182 goto out;
10183
10184 ret = __ufshcd_wl_resume(hba, UFS_SYSTEM_PM);
10185 if (ret)
10186 dev_err(&sdev->sdev_gendev, "%s failed: %d\n", __func__, ret);
10187 out:
10188 trace_ufshcd_wl_resume(hba, ret,
10189 ktime_to_us(ktime_sub(ktime_get(), start)),
10190 hba->curr_dev_pwr_mode, hba->uic_link_state);
10191 if (!ret)
10192 hba->is_sys_suspended = false;
10193 hba->system_suspending = false;
10194 up(&hba->host_sem);
10195 return ret;
10196 }
10197 #endif
10198
10199 /**
10200 * ufshcd_suspend - helper function for suspend operations
10201 * @hba: per adapter instance
10202 *
10203 * This function will put disable irqs, turn off clocks
10204 * and set vreg and hba-vreg in lpm mode.
10205 *
10206 * Return: 0 upon success; < 0 upon failure.
10207 */
ufshcd_suspend(struct ufs_hba * hba)10208 static int ufshcd_suspend(struct ufs_hba *hba)
10209 {
10210 int ret;
10211
10212 if (!hba->is_powered)
10213 return 0;
10214 /*
10215 * Disable the host irq as host controller as there won't be any
10216 * host controller transaction expected till resume.
10217 */
10218 ufshcd_disable_irq(hba);
10219 ret = ufshcd_setup_clocks(hba, false);
10220 if (ret) {
10221 ufshcd_enable_irq(hba);
10222 return ret;
10223 }
10224 if (ufshcd_is_clkgating_allowed(hba)) {
10225 hba->clk_gating.state = CLKS_OFF;
10226 trace_ufshcd_clk_gating(hba,
10227 hba->clk_gating.state);
10228 }
10229
10230 ufshcd_vreg_set_lpm(hba);
10231 /* Put the host controller in low power mode if possible */
10232 ufshcd_hba_vreg_set_lpm(hba);
10233 ufshcd_pm_qos_update(hba, false);
10234 return ret;
10235 }
10236
10237 #ifdef CONFIG_PM
10238 /**
10239 * ufshcd_resume - helper function for resume operations
10240 * @hba: per adapter instance
10241 *
10242 * This function basically turns on the regulators, clocks and
10243 * irqs of the hba.
10244 *
10245 * Return: 0 for success and non-zero for failure.
10246 */
ufshcd_resume(struct ufs_hba * hba)10247 static int ufshcd_resume(struct ufs_hba *hba)
10248 {
10249 int ret;
10250
10251 if (!hba->is_powered)
10252 return 0;
10253
10254 ufshcd_hba_vreg_set_hpm(hba);
10255 ret = ufshcd_vreg_set_hpm(hba);
10256 if (ret)
10257 goto out;
10258
10259 /* Make sure clocks are enabled before accessing controller */
10260 ret = ufshcd_setup_clocks(hba, true);
10261 if (ret)
10262 goto disable_vreg;
10263
10264 /* enable the host irq as host controller would be active soon */
10265 ufshcd_enable_irq(hba);
10266
10267 goto out;
10268
10269 disable_vreg:
10270 ufshcd_vreg_set_lpm(hba);
10271 out:
10272 if (ret)
10273 ufshcd_update_evt_hist(hba, UFS_EVT_RESUME_ERR, (u32)ret);
10274 return ret;
10275 }
10276 #endif /* CONFIG_PM */
10277
10278 #ifdef CONFIG_PM_SLEEP
10279 /**
10280 * ufshcd_system_suspend - system suspend callback
10281 * @dev: Device associated with the UFS controller.
10282 *
10283 * Executed before putting the system into a sleep state in which the contents
10284 * of main memory are preserved.
10285 *
10286 * Return: 0 for success and non-zero for failure.
10287 */
ufshcd_system_suspend(struct device * dev)10288 int ufshcd_system_suspend(struct device *dev)
10289 {
10290 struct ufs_hba *hba = dev_get_drvdata(dev);
10291 int ret = 0;
10292 ktime_t start = ktime_get();
10293
10294 if (pm_runtime_suspended(hba->dev))
10295 goto out;
10296
10297 ret = ufshcd_suspend(hba);
10298 out:
10299 trace_ufshcd_system_suspend(hba, ret,
10300 ktime_to_us(ktime_sub(ktime_get(), start)),
10301 hba->curr_dev_pwr_mode, hba->uic_link_state);
10302 return ret;
10303 }
10304 EXPORT_SYMBOL(ufshcd_system_suspend);
10305
10306 /**
10307 * ufshcd_system_resume - system resume callback
10308 * @dev: Device associated with the UFS controller.
10309 *
10310 * Executed after waking the system up from a sleep state in which the contents
10311 * of main memory were preserved.
10312 *
10313 * Return: 0 for success and non-zero for failure.
10314 */
ufshcd_system_resume(struct device * dev)10315 int ufshcd_system_resume(struct device *dev)
10316 {
10317 struct ufs_hba *hba = dev_get_drvdata(dev);
10318 ktime_t start = ktime_get();
10319 int ret = 0;
10320
10321 if (pm_runtime_suspended(hba->dev))
10322 goto out;
10323
10324 ret = ufshcd_resume(hba);
10325
10326 out:
10327 trace_ufshcd_system_resume(hba, ret,
10328 ktime_to_us(ktime_sub(ktime_get(), start)),
10329 hba->curr_dev_pwr_mode, hba->uic_link_state);
10330
10331 return ret;
10332 }
10333 EXPORT_SYMBOL(ufshcd_system_resume);
10334 #endif /* CONFIG_PM_SLEEP */
10335
10336 #ifdef CONFIG_PM
10337 /**
10338 * ufshcd_runtime_suspend - runtime suspend callback
10339 * @dev: Device associated with the UFS controller.
10340 *
10341 * Check the description of ufshcd_suspend() function for more details.
10342 *
10343 * Return: 0 for success and non-zero for failure.
10344 */
ufshcd_runtime_suspend(struct device * dev)10345 int ufshcd_runtime_suspend(struct device *dev)
10346 {
10347 struct ufs_hba *hba = dev_get_drvdata(dev);
10348 int ret;
10349 ktime_t start = ktime_get();
10350
10351 ret = ufshcd_suspend(hba);
10352
10353 trace_ufshcd_runtime_suspend(hba, ret,
10354 ktime_to_us(ktime_sub(ktime_get(), start)),
10355 hba->curr_dev_pwr_mode, hba->uic_link_state);
10356 return ret;
10357 }
10358 EXPORT_SYMBOL(ufshcd_runtime_suspend);
10359
10360 /**
10361 * ufshcd_runtime_resume - runtime resume routine
10362 * @dev: Device associated with the UFS controller.
10363 *
10364 * This function basically brings controller
10365 * to active state. Following operations are done in this function:
10366 *
10367 * 1. Turn on all the controller related clocks
10368 * 2. Turn ON VCC rail
10369 *
10370 * Return: 0 upon success; < 0 upon failure.
10371 */
ufshcd_runtime_resume(struct device * dev)10372 int ufshcd_runtime_resume(struct device *dev)
10373 {
10374 struct ufs_hba *hba = dev_get_drvdata(dev);
10375 int ret;
10376 ktime_t start = ktime_get();
10377
10378 ret = ufshcd_resume(hba);
10379
10380 trace_ufshcd_runtime_resume(hba, ret,
10381 ktime_to_us(ktime_sub(ktime_get(), start)),
10382 hba->curr_dev_pwr_mode, hba->uic_link_state);
10383 return ret;
10384 }
10385 EXPORT_SYMBOL(ufshcd_runtime_resume);
10386 #endif /* CONFIG_PM */
10387
ufshcd_wl_shutdown(struct device * dev)10388 static void ufshcd_wl_shutdown(struct device *dev)
10389 {
10390 struct scsi_device *sdev = to_scsi_device(dev);
10391 struct ufs_hba *hba = shost_priv(sdev->host);
10392
10393 down(&hba->host_sem);
10394 hba->shutting_down = true;
10395 up(&hba->host_sem);
10396
10397 /* Turn on everything while shutting down */
10398 ufshcd_rpm_get_sync(hba);
10399 scsi_device_quiesce(sdev);
10400 shost_for_each_device(sdev, hba->host) {
10401 if (sdev == hba->ufs_device_wlun)
10402 continue;
10403 mutex_lock(&sdev->state_mutex);
10404 scsi_device_set_state(sdev, SDEV_OFFLINE);
10405 mutex_unlock(&sdev->state_mutex);
10406 }
10407 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10408
10409 /*
10410 * Next, turn off the UFS controller and the UFS regulators. Disable
10411 * clocks.
10412 */
10413 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
10414 ufshcd_suspend(hba);
10415
10416 hba->is_powered = false;
10417 }
10418
10419 /**
10420 * ufshcd_remove - de-allocate SCSI host and host memory space
10421 * data structure memory
10422 * @hba: per adapter instance
10423 */
ufshcd_remove(struct ufs_hba * hba)10424 void ufshcd_remove(struct ufs_hba *hba)
10425 {
10426 if (hba->ufs_device_wlun)
10427 ufshcd_rpm_get_sync(hba);
10428 ufs_hwmon_remove(hba);
10429 ufs_bsg_remove(hba);
10430 ufs_sysfs_remove_nodes(hba->dev);
10431 cancel_delayed_work_sync(&hba->ufs_rtc_update_work);
10432 blk_mq_destroy_queue(hba->tmf_queue);
10433 blk_put_queue(hba->tmf_queue);
10434 blk_mq_free_tag_set(&hba->tmf_tag_set);
10435 if (hba->scsi_host_added)
10436 scsi_remove_host(hba->host);
10437 /* disable interrupts */
10438 ufshcd_disable_intr(hba, hba->intr_mask);
10439 ufshcd_hba_stop(hba);
10440 ufshcd_hba_exit(hba);
10441 }
10442 EXPORT_SYMBOL_GPL(ufshcd_remove);
10443
10444 #ifdef CONFIG_PM_SLEEP
ufshcd_system_freeze(struct device * dev)10445 int ufshcd_system_freeze(struct device *dev)
10446 {
10447
10448 return ufshcd_system_suspend(dev);
10449
10450 }
10451 EXPORT_SYMBOL_GPL(ufshcd_system_freeze);
10452
ufshcd_system_restore(struct device * dev)10453 int ufshcd_system_restore(struct device *dev)
10454 {
10455
10456 struct ufs_hba *hba = dev_get_drvdata(dev);
10457 int ret;
10458
10459 ret = ufshcd_system_resume(dev);
10460 if (ret)
10461 return ret;
10462
10463 /* Configure UTRL and UTMRL base address registers */
10464 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
10465 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
10466 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
10467 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
10468 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
10469 REG_UTP_TASK_REQ_LIST_BASE_L);
10470 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
10471 REG_UTP_TASK_REQ_LIST_BASE_H);
10472 /*
10473 * Make sure that UTRL and UTMRL base address registers
10474 * are updated with the latest queue addresses. Only after
10475 * updating these addresses, we can queue the new commands.
10476 */
10477 ufshcd_readl(hba, REG_UTP_TASK_REQ_LIST_BASE_H);
10478
10479 return 0;
10480
10481 }
10482 EXPORT_SYMBOL_GPL(ufshcd_system_restore);
10483
ufshcd_system_thaw(struct device * dev)10484 int ufshcd_system_thaw(struct device *dev)
10485 {
10486 return ufshcd_system_resume(dev);
10487 }
10488 EXPORT_SYMBOL_GPL(ufshcd_system_thaw);
10489 #endif /* CONFIG_PM_SLEEP */
10490
10491 /**
10492 * ufshcd_set_dma_mask - Set dma mask based on the controller
10493 * addressing capability
10494 * @hba: per adapter instance
10495 *
10496 * Return: 0 for success, non-zero for failure.
10497 */
ufshcd_set_dma_mask(struct ufs_hba * hba)10498 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
10499 {
10500 if (hba->vops && hba->vops->set_dma_mask)
10501 return hba->vops->set_dma_mask(hba);
10502 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
10503 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
10504 return 0;
10505 }
10506 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
10507 }
10508
10509 /**
10510 * ufshcd_devres_release - devres cleanup handler, invoked during release of
10511 * hba->dev
10512 * @host: pointer to SCSI host
10513 */
ufshcd_devres_release(void * host)10514 static void ufshcd_devres_release(void *host)
10515 {
10516 scsi_host_put(host);
10517 }
10518
10519 /**
10520 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
10521 * @dev: pointer to device handle
10522 * @hba_handle: driver private handle
10523 *
10524 * Return: 0 on success, non-zero value on failure.
10525 *
10526 * NOTE: There is no corresponding ufshcd_dealloc_host() because this function
10527 * keeps track of its allocations using devres and deallocates everything on
10528 * device removal automatically.
10529 */
ufshcd_alloc_host(struct device * dev,struct ufs_hba ** hba_handle)10530 int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
10531 {
10532 struct Scsi_Host *host;
10533 struct ufs_hba *hba;
10534 int err = 0;
10535
10536 if (!dev) {
10537 dev_err(dev,
10538 "Invalid memory reference for dev is NULL\n");
10539 err = -ENODEV;
10540 goto out_error;
10541 }
10542
10543 host = scsi_host_alloc(&ufshcd_driver_template,
10544 sizeof(struct ufs_hba));
10545 if (!host) {
10546 dev_err(dev, "scsi_host_alloc failed\n");
10547 err = -ENOMEM;
10548 goto out_error;
10549 }
10550
10551 err = devm_add_action_or_reset(dev, ufshcd_devres_release,
10552 host);
10553 if (err)
10554 return err;
10555
10556 host->nr_maps = HCTX_TYPE_POLL + 1;
10557 hba = shost_priv(host);
10558 hba->host = host;
10559 hba->dev = dev;
10560 hba->dev_ref_clk_freq = REF_CLK_FREQ_INVAL;
10561 hba->nop_out_timeout = NOP_OUT_TIMEOUT;
10562 ufshcd_set_sg_entry_size(hba, sizeof(struct ufshcd_sg_entry));
10563 INIT_LIST_HEAD(&hba->clk_list_head);
10564 spin_lock_init(&hba->outstanding_lock);
10565
10566 *hba_handle = hba;
10567
10568 out_error:
10569 return err;
10570 }
10571 EXPORT_SYMBOL(ufshcd_alloc_host);
10572
10573 /* 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)10574 static blk_status_t ufshcd_queue_tmf(struct blk_mq_hw_ctx *hctx,
10575 const struct blk_mq_queue_data *qd)
10576 {
10577 WARN_ON_ONCE(true);
10578 return BLK_STS_NOTSUPP;
10579 }
10580
10581 static const struct blk_mq_ops ufshcd_tmf_ops = {
10582 .queue_rq = ufshcd_queue_tmf,
10583 };
10584
ufshcd_add_scsi_host(struct ufs_hba * hba)10585 static int ufshcd_add_scsi_host(struct ufs_hba *hba)
10586 {
10587 int err;
10588
10589 if (is_mcq_supported(hba)) {
10590 ufshcd_mcq_enable(hba);
10591 err = ufshcd_alloc_mcq(hba);
10592 if (!err) {
10593 ufshcd_config_mcq(hba);
10594 } else {
10595 /* Continue with SDB mode */
10596 ufshcd_mcq_disable(hba);
10597 use_mcq_mode = false;
10598 dev_err(hba->dev, "MCQ mode is disabled, err=%d\n",
10599 err);
10600 }
10601 }
10602 if (!is_mcq_supported(hba) && !hba->lsdb_sup) {
10603 dev_err(hba->dev,
10604 "%s: failed to initialize (legacy doorbell mode not supported)\n",
10605 __func__);
10606 return -EINVAL;
10607 }
10608
10609 err = scsi_add_host(hba->host, hba->dev);
10610 if (err) {
10611 dev_err(hba->dev, "scsi_add_host failed\n");
10612 return err;
10613 }
10614 hba->scsi_host_added = true;
10615
10616 hba->tmf_tag_set = (struct blk_mq_tag_set) {
10617 .nr_hw_queues = 1,
10618 .queue_depth = hba->nutmrs,
10619 .ops = &ufshcd_tmf_ops,
10620 };
10621 err = blk_mq_alloc_tag_set(&hba->tmf_tag_set);
10622 if (err < 0)
10623 goto remove_scsi_host;
10624 hba->tmf_queue = blk_mq_alloc_queue(&hba->tmf_tag_set, NULL, NULL);
10625 if (IS_ERR(hba->tmf_queue)) {
10626 err = PTR_ERR(hba->tmf_queue);
10627 goto free_tmf_tag_set;
10628 }
10629 hba->tmf_rqs = devm_kcalloc(hba->dev, hba->nutmrs,
10630 sizeof(*hba->tmf_rqs), GFP_KERNEL);
10631 if (!hba->tmf_rqs) {
10632 err = -ENOMEM;
10633 goto free_tmf_queue;
10634 }
10635
10636 return 0;
10637
10638 free_tmf_queue:
10639 blk_mq_destroy_queue(hba->tmf_queue);
10640 blk_put_queue(hba->tmf_queue);
10641
10642 free_tmf_tag_set:
10643 blk_mq_free_tag_set(&hba->tmf_tag_set);
10644
10645 remove_scsi_host:
10646 if (hba->scsi_host_added)
10647 scsi_remove_host(hba->host);
10648
10649 return err;
10650 }
10651
10652 /**
10653 * ufshcd_init - Driver initialization routine
10654 * @hba: per-adapter instance
10655 * @mmio_base: base register address
10656 * @irq: Interrupt line of device
10657 *
10658 * Return: 0 on success, non-zero value on failure.
10659 */
ufshcd_init(struct ufs_hba * hba,void __iomem * mmio_base,unsigned int irq)10660 int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
10661 {
10662 int err;
10663 struct Scsi_Host *host = hba->host;
10664 struct device *dev = hba->dev;
10665
10666 /*
10667 * dev_set_drvdata() must be called before any callbacks are registered
10668 * that use dev_get_drvdata() (frequency scaling, clock scaling, hwmon,
10669 * sysfs).
10670 */
10671 dev_set_drvdata(dev, hba);
10672
10673 if (!mmio_base) {
10674 dev_err(hba->dev,
10675 "Invalid memory reference for mmio_base is NULL\n");
10676 err = -ENODEV;
10677 goto out_error;
10678 }
10679
10680 hba->mmio_base = mmio_base;
10681 hba->irq = irq;
10682 hba->vps = &ufs_hba_vps;
10683
10684 /*
10685 * Initialize clk_gating.lock early since it is being used in
10686 * ufshcd_setup_clocks()
10687 */
10688 spin_lock_init(&hba->clk_gating.lock);
10689
10690 /* Initialize mutex for PM QoS request synchronization */
10691 mutex_init(&hba->pm_qos_mutex);
10692
10693 /*
10694 * Set the default power management level for runtime and system PM.
10695 * Host controller drivers can override them in their
10696 * 'ufs_hba_variant_ops::init' callback.
10697 *
10698 * Default power saving mode is to keep UFS link in Hibern8 state
10699 * and UFS device in sleep state.
10700 */
10701 hba->rpm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10702 UFS_SLEEP_PWR_MODE,
10703 UIC_LINK_HIBERN8_STATE);
10704 hba->spm_lvl = ufs_get_desired_pm_lvl_for_dev_link_state(
10705 UFS_SLEEP_PWR_MODE,
10706 UIC_LINK_HIBERN8_STATE);
10707
10708 init_completion(&hba->dev_cmd.complete);
10709
10710 err = ufshcd_hba_init(hba);
10711 if (err)
10712 goto out_error;
10713
10714 /* Read capabilities registers */
10715 err = ufshcd_hba_capabilities(hba);
10716 if (err)
10717 goto out_disable;
10718
10719 /* Get UFS version supported by the controller */
10720 hba->ufs_version = ufshcd_get_ufs_version(hba);
10721
10722 /* Get Interrupt bit mask per version */
10723 hba->intr_mask = ufshcd_get_intr_mask(hba);
10724
10725 err = ufshcd_set_dma_mask(hba);
10726 if (err) {
10727 dev_err(hba->dev, "set dma mask failed\n");
10728 goto out_disable;
10729 }
10730
10731 /* Allocate memory for host memory space */
10732 err = ufshcd_memory_alloc(hba);
10733 if (err) {
10734 dev_err(hba->dev, "Memory allocation failed\n");
10735 goto out_disable;
10736 }
10737
10738 /* Configure LRB */
10739 ufshcd_host_memory_configure(hba);
10740
10741 host->can_queue = hba->nutrs - UFSHCD_NUM_RESERVED;
10742 host->cmd_per_lun = hba->nutrs - UFSHCD_NUM_RESERVED;
10743 host->max_id = UFSHCD_MAX_ID;
10744 host->max_lun = UFS_MAX_LUNS;
10745 host->max_channel = UFSHCD_MAX_CHANNEL;
10746 host->unique_id = host->host_no;
10747 host->max_cmd_len = UFS_CDB_SIZE;
10748 host->queuecommand_may_block = !!(hba->caps & UFSHCD_CAP_CLK_GATING);
10749
10750 /* Use default RPM delay if host not set */
10751 if (host->rpm_autosuspend_delay == 0)
10752 host->rpm_autosuspend_delay = RPM_AUTOSUSPEND_DELAY_MS;
10753
10754 hba->max_pwr_info.is_valid = false;
10755
10756 /* Initialize work queues */
10757 hba->eh_wq = alloc_ordered_workqueue("ufs_eh_wq_%d", WQ_MEM_RECLAIM,
10758 hba->host->host_no);
10759 if (!hba->eh_wq) {
10760 dev_err(hba->dev, "%s: failed to create eh workqueue\n",
10761 __func__);
10762 err = -ENOMEM;
10763 goto out_disable;
10764 }
10765 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
10766 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
10767
10768 sema_init(&hba->host_sem, 1);
10769
10770 /* Initialize UIC command mutex */
10771 mutex_init(&hba->uic_cmd_mutex);
10772
10773 /* Initialize mutex for device management commands */
10774 mutex_init(&hba->dev_cmd.lock);
10775
10776 /* Initialize mutex for exception event control */
10777 mutex_init(&hba->ee_ctrl_mutex);
10778
10779 mutex_init(&hba->wb_mutex);
10780
10781 init_rwsem(&hba->clk_scaling_lock);
10782
10783 ufshcd_init_clk_gating(hba);
10784
10785 ufshcd_init_clk_scaling(hba);
10786
10787 /*
10788 * In order to avoid any spurious interrupt immediately after
10789 * registering UFS controller interrupt handler, clear any pending UFS
10790 * interrupt status and disable all the UFS interrupts.
10791 */
10792 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
10793 REG_INTERRUPT_STATUS);
10794 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
10795 /*
10796 * Make sure that UFS interrupts are disabled and any pending interrupt
10797 * status is cleared before registering UFS interrupt handler.
10798 */
10799 ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
10800
10801 /* IRQ registration */
10802 err = devm_request_threaded_irq(dev, irq, ufshcd_intr, ufshcd_threaded_intr,
10803 IRQF_ONESHOT | IRQF_SHARED, UFSHCD, hba);
10804 if (err) {
10805 dev_err(hba->dev, "request irq failed\n");
10806 goto out_disable;
10807 } else {
10808 hba->is_irq_enabled = true;
10809 }
10810
10811 /* Reset the attached device */
10812 ufshcd_device_reset(hba);
10813
10814 ufshcd_init_crypto(hba);
10815
10816 /* Host controller enable */
10817 err = ufshcd_hba_enable(hba);
10818 if (err) {
10819 dev_err(hba->dev, "Host controller enable failed\n");
10820 ufshcd_print_evt_hist(hba);
10821 ufshcd_print_host_state(hba);
10822 goto out_disable;
10823 }
10824
10825 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work);
10826 INIT_DELAYED_WORK(&hba->ufs_rtc_update_work, ufshcd_rtc_work);
10827
10828 /* Set the default auto-hiberate idle timer value to 150 ms */
10829 if (ufshcd_is_auto_hibern8_supported(hba) && !hba->ahit) {
10830 hba->ahit = FIELD_PREP(UFSHCI_AHIBERN8_TIMER_MASK, 150) |
10831 FIELD_PREP(UFSHCI_AHIBERN8_SCALE_MASK, 3);
10832 }
10833
10834 /* Hold auto suspend until async scan completes */
10835 pm_runtime_get_sync(dev);
10836
10837 /*
10838 * We are assuming that device wasn't put in sleep/power-down
10839 * state exclusively during the boot stage before kernel.
10840 * This assumption helps avoid doing link startup twice during
10841 * ufshcd_probe_hba().
10842 */
10843 ufshcd_set_ufs_dev_active(hba);
10844
10845 /* Initialize hba, detect and initialize UFS device */
10846 ktime_t probe_start = ktime_get();
10847
10848 hba->ufshcd_state = UFSHCD_STATE_RESET;
10849
10850 err = ufshcd_link_startup(hba);
10851 if (err)
10852 goto out_disable;
10853
10854 if (hba->quirks & UFSHCD_QUIRK_SKIP_PH_CONFIGURATION)
10855 goto initialized;
10856
10857 /* Debug counters initialization */
10858 ufshcd_clear_dbg_ufs_stats(hba);
10859
10860 /* UniPro link is active now */
10861 ufshcd_set_link_active(hba);
10862
10863 /* Verify device initialization by sending NOP OUT UPIU */
10864 err = ufshcd_verify_dev_init(hba);
10865 if (err)
10866 goto out_disable;
10867
10868 /* Initiate UFS initialization, and waiting until completion */
10869 err = ufshcd_complete_dev_init(hba);
10870 if (err)
10871 goto out_disable;
10872
10873 err = ufshcd_device_params_init(hba);
10874 if (err)
10875 goto out_disable;
10876
10877 err = ufshcd_post_device_init(hba);
10878
10879 initialized:
10880 ufshcd_process_probe_result(hba, probe_start, err);
10881 if (err)
10882 goto out_disable;
10883
10884 err = ufshcd_add_scsi_host(hba);
10885 if (err)
10886 goto out_disable;
10887
10888 async_schedule(ufshcd_async_scan, hba);
10889 ufs_sysfs_add_nodes(hba->dev);
10890
10891 device_enable_async_suspend(dev);
10892 ufshcd_pm_qos_init(hba);
10893 return 0;
10894
10895 out_disable:
10896 hba->is_irq_enabled = false;
10897 ufshcd_hba_exit(hba);
10898 out_error:
10899 return err;
10900 }
10901 EXPORT_SYMBOL_GPL(ufshcd_init);
10902
ufshcd_resume_complete(struct device * dev)10903 void ufshcd_resume_complete(struct device *dev)
10904 {
10905 struct ufs_hba *hba = dev_get_drvdata(dev);
10906
10907 if (hba->complete_put) {
10908 ufshcd_rpm_put(hba);
10909 hba->complete_put = false;
10910 }
10911 }
10912 EXPORT_SYMBOL_GPL(ufshcd_resume_complete);
10913
ufshcd_rpm_ok_for_spm(struct ufs_hba * hba)10914 static bool ufshcd_rpm_ok_for_spm(struct ufs_hba *hba)
10915 {
10916 struct device *dev = &hba->ufs_device_wlun->sdev_gendev;
10917 enum ufs_dev_pwr_mode dev_pwr_mode;
10918 enum uic_link_state link_state;
10919 unsigned long flags;
10920 bool res;
10921
10922 spin_lock_irqsave(&dev->power.lock, flags);
10923 dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl);
10924 link_state = ufs_get_pm_lvl_to_link_pwr_state(hba->spm_lvl);
10925 res = pm_runtime_suspended(dev) &&
10926 hba->curr_dev_pwr_mode == dev_pwr_mode &&
10927 hba->uic_link_state == link_state &&
10928 !hba->dev_info.b_rpm_dev_flush_capable;
10929 spin_unlock_irqrestore(&dev->power.lock, flags);
10930
10931 return res;
10932 }
10933
__ufshcd_suspend_prepare(struct device * dev,bool rpm_ok_for_spm)10934 int __ufshcd_suspend_prepare(struct device *dev, bool rpm_ok_for_spm)
10935 {
10936 struct ufs_hba *hba = dev_get_drvdata(dev);
10937 int ret;
10938
10939 /*
10940 * SCSI assumes that runtime-pm and system-pm for scsi drivers
10941 * are same. And it doesn't wake up the device for system-suspend
10942 * if it's runtime suspended. But ufs doesn't follow that.
10943 * Refer ufshcd_resume_complete()
10944 */
10945 if (hba->ufs_device_wlun) {
10946 /* Prevent runtime suspend */
10947 ufshcd_rpm_get_noresume(hba);
10948 /*
10949 * Check if already runtime suspended in same state as system
10950 * suspend would be.
10951 */
10952 if (!rpm_ok_for_spm || !ufshcd_rpm_ok_for_spm(hba)) {
10953 /* RPM state is not ok for SPM, so runtime resume */
10954 ret = ufshcd_rpm_resume(hba);
10955 if (ret < 0 && ret != -EACCES) {
10956 ufshcd_rpm_put(hba);
10957 return ret;
10958 }
10959 }
10960 hba->complete_put = true;
10961 }
10962 return 0;
10963 }
10964 EXPORT_SYMBOL_GPL(__ufshcd_suspend_prepare);
10965
ufshcd_suspend_prepare(struct device * dev)10966 int ufshcd_suspend_prepare(struct device *dev)
10967 {
10968 return __ufshcd_suspend_prepare(dev, true);
10969 }
10970 EXPORT_SYMBOL_GPL(ufshcd_suspend_prepare);
10971
10972 #ifdef CONFIG_PM_SLEEP
ufshcd_wl_poweroff(struct device * dev)10973 static int ufshcd_wl_poweroff(struct device *dev)
10974 {
10975 struct scsi_device *sdev = to_scsi_device(dev);
10976 struct ufs_hba *hba = shost_priv(sdev->host);
10977
10978 __ufshcd_wl_suspend(hba, UFS_SHUTDOWN_PM);
10979 return 0;
10980 }
10981 #endif
10982
ufshcd_wl_probe(struct device * dev)10983 static int ufshcd_wl_probe(struct device *dev)
10984 {
10985 struct scsi_device *sdev = to_scsi_device(dev);
10986
10987 if (!is_device_wlun(sdev))
10988 return -ENODEV;
10989
10990 blk_pm_runtime_init(sdev->request_queue, dev);
10991 pm_runtime_set_autosuspend_delay(dev, 0);
10992 pm_runtime_allow(dev);
10993
10994 return 0;
10995 }
10996
ufshcd_wl_remove(struct device * dev)10997 static int ufshcd_wl_remove(struct device *dev)
10998 {
10999 pm_runtime_forbid(dev);
11000 return 0;
11001 }
11002
11003 static const struct dev_pm_ops ufshcd_wl_pm_ops = {
11004 #ifdef CONFIG_PM_SLEEP
11005 .suspend = ufshcd_wl_suspend,
11006 .resume = ufshcd_wl_resume,
11007 .freeze = ufshcd_wl_suspend,
11008 .thaw = ufshcd_wl_resume,
11009 .poweroff = ufshcd_wl_poweroff,
11010 .restore = ufshcd_wl_resume,
11011 #endif
11012 SET_RUNTIME_PM_OPS(ufshcd_wl_runtime_suspend, ufshcd_wl_runtime_resume, NULL)
11013 };
11014
ufshcd_check_header_layout(void)11015 static void ufshcd_check_header_layout(void)
11016 {
11017 /*
11018 * gcc compilers before version 10 cannot do constant-folding for
11019 * sub-byte bitfields. Hence skip the layout checks for gcc 9 and
11020 * before.
11021 */
11022 if (IS_ENABLED(CONFIG_CC_IS_GCC) && CONFIG_GCC_VERSION < 100000)
11023 return;
11024
11025 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11026 .cci = 3})[0] != 3);
11027
11028 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11029 .ehs_length = 2})[1] != 2);
11030
11031 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11032 .enable_crypto = 1})[2]
11033 != 0x80);
11034
11035 BUILD_BUG_ON((((u8 *)&(struct request_desc_header){
11036 .command_type = 5,
11037 .data_direction = 3,
11038 .interrupt = 1,
11039 })[3]) != ((5 << 4) | (3 << 1) | 1));
11040
11041 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
11042 .dunl = cpu_to_le32(0xdeadbeef)})[1] !=
11043 cpu_to_le32(0xdeadbeef));
11044
11045 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11046 .ocs = 4})[8] != 4);
11047
11048 BUILD_BUG_ON(((u8 *)&(struct request_desc_header){
11049 .cds = 5})[9] != 5);
11050
11051 BUILD_BUG_ON(((__le32 *)&(struct request_desc_header){
11052 .dunu = cpu_to_le32(0xbadcafe)})[3] !=
11053 cpu_to_le32(0xbadcafe));
11054
11055 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
11056 .iid = 0xf })[4] != 0xf0);
11057
11058 BUILD_BUG_ON(((u8 *)&(struct utp_upiu_header){
11059 .command_set_type = 0xf })[4] != 0xf);
11060 }
11061
11062 /*
11063 * ufs_dev_wlun_template - describes ufs device wlun
11064 * ufs-device wlun - used to send pm commands
11065 * All luns are consumers of ufs-device wlun.
11066 *
11067 * Currently, no sd driver is present for wluns.
11068 * Hence the no specific pm operations are performed.
11069 * With ufs design, SSU should be sent to ufs-device wlun.
11070 * Hence register a scsi driver for ufs wluns only.
11071 */
11072 static struct scsi_driver ufs_dev_wlun_template = {
11073 .gendrv = {
11074 .name = "ufs_device_wlun",
11075 .probe = ufshcd_wl_probe,
11076 .remove = ufshcd_wl_remove,
11077 .pm = &ufshcd_wl_pm_ops,
11078 .shutdown = ufshcd_wl_shutdown,
11079 },
11080 };
11081
ufshcd_core_init(void)11082 static int __init ufshcd_core_init(void)
11083 {
11084 int ret;
11085
11086 ufshcd_check_header_layout();
11087
11088 ufs_debugfs_init();
11089
11090 ret = scsi_register_driver(&ufs_dev_wlun_template.gendrv);
11091 if (ret)
11092 ufs_debugfs_exit();
11093 return ret;
11094 }
11095
ufshcd_core_exit(void)11096 static void __exit ufshcd_core_exit(void)
11097 {
11098 ufs_debugfs_exit();
11099 scsi_unregister_driver(&ufs_dev_wlun_template.gendrv);
11100 }
11101
11102 module_init(ufshcd_core_init);
11103 module_exit(ufshcd_core_exit);
11104
11105 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
11106 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
11107 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
11108 MODULE_SOFTDEP("pre: governor_simpleondemand");
11109 MODULE_LICENSE("GPL");
11110