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