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