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