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