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