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