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