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