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