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