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