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