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