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