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