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