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