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