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