scsi: ufs: add retry for query descriptors
[GitHub/moto-9609/android_kernel_motorola_exynos9610.git] / drivers / scsi / ufs / ufshcd.c
CommitLineData
7a3e97b0 1/*
e0eca63e 2 * Universal Flash Storage Host controller driver Core
7a3e97b0
SY
3 *
4 * This code is based on drivers/scsi/ufs/ufshcd.c
3b1d0580 5 * Copyright (C) 2011-2013 Samsung India Software Operations
52ac95fe 6 * Copyright (c) 2013-2016, The Linux Foundation. All rights reserved.
7a3e97b0 7 *
3b1d0580
VH
8 * Authors:
9 * Santosh Yaraganavi <santosh.sy@samsung.com>
10 * Vinayak Holikatti <h.vinayak@samsung.com>
7a3e97b0
SY
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.
3b1d0580
VH
16 * See the COPYING file in the top-level directory or visit
17 * <http://www.gnu.org/licenses/gpl-2.0.html>
7a3e97b0
SY
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 *
3b1d0580
VH
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.
5c0c28a8
SRT
35 *
36 * The Linux Foundation chooses to take subject only to the GPLv2
37 * license terms, and distributes only under these terms.
7a3e97b0
SY
38 */
39
6ccf44fe 40#include <linux/async.h>
856b3483 41#include <linux/devfreq.h>
b573d484 42#include <linux/nls.h>
54b879b7 43#include <linux/of.h>
e0eca63e 44#include "ufshcd.h"
c58ab7aa 45#include "ufs_quirks.h"
53b3d9c3 46#include "unipro.h"
7a3e97b0 47
2fbd009b
SJ
48#define UFSHCD_ENABLE_INTRS (UTP_TRANSFER_REQ_COMPL |\
49 UTP_TASK_REQ_COMPL |\
50 UFSHCD_ERROR_MASK)
6ccf44fe
SJ
51/* UIC command timeout, unit: ms */
52#define UIC_CMD_TIMEOUT 500
2fbd009b 53
5a0b0cb9
SRT
54/* NOP OUT retries waiting for NOP IN response */
55#define NOP_OUT_RETRIES 10
56/* Timeout after 30 msecs if NOP OUT hangs without response */
57#define NOP_OUT_TIMEOUT 30 /* msecs */
58
68078d5c
DR
59/* Query request retries */
60#define QUERY_REQ_RETRIES 10
61/* Query request timeout */
62#define QUERY_REQ_TIMEOUT 30 /* msec */
e5ad406c
YG
63/*
64 * Query request timeout for fDeviceInit flag
65 * fDeviceInit query response time for some devices is too large that default
66 * QUERY_REQ_TIMEOUT may not be enough for such devices.
67 */
68#define QUERY_FDEVICEINIT_REQ_TIMEOUT 600 /* msec */
68078d5c 69
e2933132
SRT
70/* Task management command timeout */
71#define TM_CMD_TIMEOUT 100 /* msecs */
72
64238fbd
YG
73/* maximum number of retries for a general UIC command */
74#define UFS_UIC_COMMAND_RETRIES 3
75
1d337ec2
SRT
76/* maximum number of link-startup retries */
77#define DME_LINKSTARTUP_RETRIES 3
78
87d0b4a6
YG
79/* Maximum retries for Hibern8 enter */
80#define UIC_HIBERN8_ENTER_RETRIES 3
81
1d337ec2
SRT
82/* maximum number of reset retries before giving up */
83#define MAX_HOST_RESET_RETRIES 5
84
68078d5c
DR
85/* Expose the flag value from utp_upiu_query.value */
86#define MASK_QUERY_UPIU_FLAG_LOC 0xFF
87
7d568652
SJ
88/* Interrupt aggregation default timeout, unit: 40us */
89#define INT_AGGR_DEF_TO 0x02
90
aa497613
SRT
91#define ufshcd_toggle_vreg(_dev, _vreg, _on) \
92 ({ \
93 int _ret; \
94 if (_on) \
95 _ret = ufshcd_enable_vreg(_dev, _vreg); \
96 else \
97 _ret = ufshcd_disable_vreg(_dev, _vreg); \
98 _ret; \
99 })
100
da461cec
SJ
101static u32 ufs_query_desc_max_size[] = {
102 QUERY_DESC_DEVICE_MAX_SIZE,
103 QUERY_DESC_CONFIGURAION_MAX_SIZE,
104 QUERY_DESC_UNIT_MAX_SIZE,
105 QUERY_DESC_RFU_MAX_SIZE,
106 QUERY_DESC_INTERCONNECT_MAX_SIZE,
107 QUERY_DESC_STRING_MAX_SIZE,
108 QUERY_DESC_RFU_MAX_SIZE,
1ce21794 109 QUERY_DESC_GEOMETRY_MAX_SIZE,
da461cec
SJ
110 QUERY_DESC_POWER_MAX_SIZE,
111 QUERY_DESC_RFU_MAX_SIZE,
112};
113
7a3e97b0
SY
114enum {
115 UFSHCD_MAX_CHANNEL = 0,
116 UFSHCD_MAX_ID = 1,
7a3e97b0
SY
117 UFSHCD_CMD_PER_LUN = 32,
118 UFSHCD_CAN_QUEUE = 32,
119};
120
121/* UFSHCD states */
122enum {
7a3e97b0
SY
123 UFSHCD_STATE_RESET,
124 UFSHCD_STATE_ERROR,
3441da7d
SRT
125 UFSHCD_STATE_OPERATIONAL,
126};
127
128/* UFSHCD error handling flags */
129enum {
130 UFSHCD_EH_IN_PROGRESS = (1 << 0),
7a3e97b0
SY
131};
132
e8e7f271
SRT
133/* UFSHCD UIC layer error flags */
134enum {
135 UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
9a47ec7c
YG
136 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR = (1 << 1), /* Data link layer error */
137 UFSHCD_UIC_DL_TCx_REPLAY_ERROR = (1 << 2), /* Data link layer error */
138 UFSHCD_UIC_NL_ERROR = (1 << 3), /* Network layer error */
139 UFSHCD_UIC_TL_ERROR = (1 << 4), /* Transport Layer error */
140 UFSHCD_UIC_DME_ERROR = (1 << 5), /* DME error */
e8e7f271
SRT
141};
142
7a3e97b0
SY
143/* Interrupt configuration options */
144enum {
145 UFSHCD_INT_DISABLE,
146 UFSHCD_INT_ENABLE,
147 UFSHCD_INT_CLEAR,
148};
149
3441da7d
SRT
150#define ufshcd_set_eh_in_progress(h) \
151 (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
152#define ufshcd_eh_in_progress(h) \
153 (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
154#define ufshcd_clear_eh_in_progress(h) \
155 (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
156
57d104c1
SJ
157#define ufshcd_set_ufs_dev_active(h) \
158 ((h)->curr_dev_pwr_mode = UFS_ACTIVE_PWR_MODE)
159#define ufshcd_set_ufs_dev_sleep(h) \
160 ((h)->curr_dev_pwr_mode = UFS_SLEEP_PWR_MODE)
161#define ufshcd_set_ufs_dev_poweroff(h) \
162 ((h)->curr_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE)
163#define ufshcd_is_ufs_dev_active(h) \
164 ((h)->curr_dev_pwr_mode == UFS_ACTIVE_PWR_MODE)
165#define ufshcd_is_ufs_dev_sleep(h) \
166 ((h)->curr_dev_pwr_mode == UFS_SLEEP_PWR_MODE)
167#define ufshcd_is_ufs_dev_poweroff(h) \
168 ((h)->curr_dev_pwr_mode == UFS_POWERDOWN_PWR_MODE)
169
170static struct ufs_pm_lvl_states ufs_pm_lvl_states[] = {
171 {UFS_ACTIVE_PWR_MODE, UIC_LINK_ACTIVE_STATE},
172 {UFS_ACTIVE_PWR_MODE, UIC_LINK_HIBERN8_STATE},
173 {UFS_SLEEP_PWR_MODE, UIC_LINK_ACTIVE_STATE},
174 {UFS_SLEEP_PWR_MODE, UIC_LINK_HIBERN8_STATE},
175 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_HIBERN8_STATE},
176 {UFS_POWERDOWN_PWR_MODE, UIC_LINK_OFF_STATE},
177};
178
179static inline enum ufs_dev_pwr_mode
180ufs_get_pm_lvl_to_dev_pwr_mode(enum ufs_pm_level lvl)
181{
182 return ufs_pm_lvl_states[lvl].dev_state;
183}
184
185static inline enum uic_link_state
186ufs_get_pm_lvl_to_link_pwr_state(enum ufs_pm_level lvl)
187{
188 return ufs_pm_lvl_states[lvl].link_state;
189}
190
3441da7d
SRT
191static void ufshcd_tmc_handler(struct ufs_hba *hba);
192static void ufshcd_async_scan(void *data, async_cookie_t cookie);
e8e7f271
SRT
193static int ufshcd_reset_and_restore(struct ufs_hba *hba);
194static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
1d337ec2
SRT
195static void ufshcd_hba_exit(struct ufs_hba *hba);
196static int ufshcd_probe_hba(struct ufs_hba *hba);
1ab27c9c
ST
197static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
198 bool skip_ref_clk);
199static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on);
60f01870 200static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused);
1ab27c9c
ST
201static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba);
202static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba);
cad2e03d 203static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba);
57d104c1
SJ
204static int ufshcd_host_reset_and_restore(struct ufs_hba *hba);
205static irqreturn_t ufshcd_intr(int irq, void *__hba);
7eb584db
DR
206static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
207 struct ufs_pa_layer_attr *desired_pwr_mode);
874237f7
YG
208static int ufshcd_change_power_mode(struct ufs_hba *hba,
209 struct ufs_pa_layer_attr *pwr_mode);
14497328
YG
210static inline bool ufshcd_valid_tag(struct ufs_hba *hba, int tag)
211{
212 return tag >= 0 && tag < hba->nutrs;
213}
57d104c1
SJ
214
215static inline int ufshcd_enable_irq(struct ufs_hba *hba)
216{
217 int ret = 0;
218
219 if (!hba->is_irq_enabled) {
220 ret = request_irq(hba->irq, ufshcd_intr, IRQF_SHARED, UFSHCD,
221 hba);
222 if (ret)
223 dev_err(hba->dev, "%s: request_irq failed, ret=%d\n",
224 __func__, ret);
225 hba->is_irq_enabled = true;
226 }
227
228 return ret;
229}
230
231static inline void ufshcd_disable_irq(struct ufs_hba *hba)
232{
233 if (hba->is_irq_enabled) {
234 free_irq(hba->irq, hba);
235 hba->is_irq_enabled = false;
236 }
237}
3441da7d 238
b573d484
YG
239/* replace non-printable or non-ASCII characters with spaces */
240static inline void ufshcd_remove_non_printable(char *val)
241{
242 if (!val)
243 return;
244
245 if (*val < 0x20 || *val > 0x7e)
246 *val = ' ';
247}
248
5a0b0cb9
SRT
249/*
250 * ufshcd_wait_for_register - wait for register value to change
251 * @hba - per-adapter interface
252 * @reg - mmio register offset
253 * @mask - mask to apply to read register value
254 * @val - wait condition
255 * @interval_us - polling interval in microsecs
256 * @timeout_ms - timeout in millisecs
596585a2 257 * @can_sleep - perform sleep or just spin
5a0b0cb9
SRT
258 *
259 * Returns -ETIMEDOUT on error, zero on success
260 */
596585a2
YG
261int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
262 u32 val, unsigned long interval_us,
263 unsigned long timeout_ms, bool can_sleep)
5a0b0cb9
SRT
264{
265 int err = 0;
266 unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
267
268 /* ignore bits that we don't intend to wait on */
269 val = val & mask;
270
271 while ((ufshcd_readl(hba, reg) & mask) != val) {
596585a2
YG
272 if (can_sleep)
273 usleep_range(interval_us, interval_us + 50);
274 else
275 udelay(interval_us);
5a0b0cb9
SRT
276 if (time_after(jiffies, timeout)) {
277 if ((ufshcd_readl(hba, reg) & mask) != val)
278 err = -ETIMEDOUT;
279 break;
280 }
281 }
282
283 return err;
284}
285
2fbd009b
SJ
286/**
287 * ufshcd_get_intr_mask - Get the interrupt bit mask
288 * @hba - Pointer to adapter instance
289 *
290 * Returns interrupt bit mask per version
291 */
292static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
293{
294 if (hba->ufs_version == UFSHCI_VERSION_10)
295 return INTERRUPT_MASK_ALL_VER_10;
296 else
297 return INTERRUPT_MASK_ALL_VER_11;
298}
299
7a3e97b0
SY
300/**
301 * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
302 * @hba - Pointer to adapter instance
303 *
304 * Returns UFSHCI version supported by the controller
305 */
306static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
307{
0263bcd0
YG
308 if (hba->quirks & UFSHCD_QUIRK_BROKEN_UFS_HCI_VERSION)
309 return ufshcd_vops_get_ufs_hci_version(hba);
9949e702 310
b873a275 311 return ufshcd_readl(hba, REG_UFS_VERSION);
7a3e97b0
SY
312}
313
314/**
315 * ufshcd_is_device_present - Check if any device connected to
316 * the host controller
5c0c28a8 317 * @hba: pointer to adapter instance
7a3e97b0 318 *
73ec513a 319 * Returns 1 if device present, 0 if no device detected
7a3e97b0 320 */
5c0c28a8 321static inline int ufshcd_is_device_present(struct ufs_hba *hba)
7a3e97b0 322{
5c0c28a8
SRT
323 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) &
324 DEVICE_PRESENT) ? 1 : 0;
7a3e97b0
SY
325}
326
327/**
328 * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
329 * @lrb: pointer to local command reference block
330 *
331 * This function is used to get the OCS field from UTRD
332 * Returns the OCS field in the UTRD
333 */
334static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
335{
e8c8e82a 336 return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
7a3e97b0
SY
337}
338
339/**
340 * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
341 * @task_req_descp: pointer to utp_task_req_desc structure
342 *
343 * This function is used to get the OCS field from UTMRD
344 * Returns the OCS field in the UTMRD
345 */
346static inline int
347ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
348{
e8c8e82a 349 return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
7a3e97b0
SY
350}
351
352/**
353 * ufshcd_get_tm_free_slot - get a free slot for task management request
354 * @hba: per adapter instance
e2933132 355 * @free_slot: pointer to variable with available slot value
7a3e97b0 356 *
e2933132
SRT
357 * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
358 * Returns 0 if free slot is not available, else return 1 with tag value
359 * in @free_slot.
7a3e97b0 360 */
e2933132 361static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
7a3e97b0 362{
e2933132
SRT
363 int tag;
364 bool ret = false;
365
366 if (!free_slot)
367 goto out;
368
369 do {
370 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
371 if (tag >= hba->nutmrs)
372 goto out;
373 } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
374
375 *free_slot = tag;
376 ret = true;
377out:
378 return ret;
379}
380
381static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
382{
383 clear_bit_unlock(slot, &hba->tm_slots_in_use);
7a3e97b0
SY
384}
385
386/**
387 * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
388 * @hba: per adapter instance
389 * @pos: position of the bit to be cleared
390 */
391static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
392{
b873a275 393 ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
7a3e97b0
SY
394}
395
a48353f6
YG
396/**
397 * ufshcd_outstanding_req_clear - Clear a bit in outstanding request field
398 * @hba: per adapter instance
399 * @tag: position of the bit to be cleared
400 */
401static inline void ufshcd_outstanding_req_clear(struct ufs_hba *hba, int tag)
402{
403 __clear_bit(tag, &hba->outstanding_reqs);
404}
405
7a3e97b0
SY
406/**
407 * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
408 * @reg: Register value of host controller status
409 *
410 * Returns integer, 0 on Success and positive value if failed
411 */
412static inline int ufshcd_get_lists_status(u32 reg)
413{
414 /*
415 * The mask 0xFF is for the following HCS register bits
416 * Bit Description
417 * 0 Device Present
418 * 1 UTRLRDY
419 * 2 UTMRLRDY
420 * 3 UCRDY
897efe62 421 * 4-7 reserved
7a3e97b0 422 */
897efe62 423 return ((reg & 0xFF) >> 1) ^ 0x07;
7a3e97b0
SY
424}
425
426/**
427 * ufshcd_get_uic_cmd_result - Get the UIC command result
428 * @hba: Pointer to adapter instance
429 *
430 * This function gets the result of UIC command completion
431 * Returns 0 on success, non zero value on error
432 */
433static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
434{
b873a275 435 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
7a3e97b0
SY
436 MASK_UIC_COMMAND_RESULT;
437}
438
12b4fdb4
SJ
439/**
440 * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
441 * @hba: Pointer to adapter instance
442 *
443 * This function gets UIC command argument3
444 * Returns 0 on success, non zero value on error
445 */
446static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
447{
448 return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
449}
450
7a3e97b0 451/**
5a0b0cb9 452 * ufshcd_get_req_rsp - returns the TR response transaction type
7a3e97b0 453 * @ucd_rsp_ptr: pointer to response UPIU
7a3e97b0
SY
454 */
455static inline int
5a0b0cb9 456ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
7a3e97b0 457{
5a0b0cb9 458 return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
7a3e97b0
SY
459}
460
461/**
462 * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
463 * @ucd_rsp_ptr: pointer to response UPIU
464 *
465 * This function gets the response status and scsi_status from response UPIU
466 * Returns the response result code.
467 */
468static inline int
469ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
470{
471 return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
472}
473
1c2623c5
SJ
474/*
475 * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
476 * from response UPIU
477 * @ucd_rsp_ptr: pointer to response UPIU
478 *
479 * Return the data segment length.
480 */
481static inline unsigned int
482ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
483{
484 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
485 MASK_RSP_UPIU_DATA_SEG_LEN;
486}
487
66ec6d59
SRT
488/**
489 * ufshcd_is_exception_event - Check if the device raised an exception event
490 * @ucd_rsp_ptr: pointer to response UPIU
491 *
492 * The function checks if the device raised an exception event indicated in
493 * the Device Information field of response UPIU.
494 *
495 * Returns true if exception is raised, false otherwise.
496 */
497static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
498{
499 return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
500 MASK_RSP_EXCEPTION_EVENT ? true : false;
501}
502
7a3e97b0 503/**
7d568652 504 * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
7a3e97b0 505 * @hba: per adapter instance
7a3e97b0
SY
506 */
507static inline void
7d568652 508ufshcd_reset_intr_aggr(struct ufs_hba *hba)
7a3e97b0 509{
7d568652
SJ
510 ufshcd_writel(hba, INT_AGGR_ENABLE |
511 INT_AGGR_COUNTER_AND_TIMER_RESET,
512 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
513}
514
515/**
516 * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
517 * @hba: per adapter instance
518 * @cnt: Interrupt aggregation counter threshold
519 * @tmout: Interrupt aggregation timeout value
520 */
521static inline void
522ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
523{
524 ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
525 INT_AGGR_COUNTER_THLD_VAL(cnt) |
526 INT_AGGR_TIMEOUT_VAL(tmout),
527 REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
7a3e97b0
SY
528}
529
b852190e
YG
530/**
531 * ufshcd_disable_intr_aggr - Disables interrupt aggregation.
532 * @hba: per adapter instance
533 */
534static inline void ufshcd_disable_intr_aggr(struct ufs_hba *hba)
535{
536 ufshcd_writel(hba, 0, REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
537}
538
7a3e97b0
SY
539/**
540 * ufshcd_enable_run_stop_reg - Enable run-stop registers,
541 * When run-stop registers are set to 1, it indicates the
542 * host controller that it can process the requests
543 * @hba: per adapter instance
544 */
545static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
546{
b873a275
SJ
547 ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
548 REG_UTP_TASK_REQ_LIST_RUN_STOP);
549 ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
550 REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
7a3e97b0
SY
551}
552
7a3e97b0
SY
553/**
554 * ufshcd_hba_start - Start controller initialization sequence
555 * @hba: per adapter instance
556 */
557static inline void ufshcd_hba_start(struct ufs_hba *hba)
558{
b873a275 559 ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
7a3e97b0
SY
560}
561
562/**
563 * ufshcd_is_hba_active - Get controller state
564 * @hba: per adapter instance
565 *
566 * Returns zero if controller is active, 1 otherwise
567 */
568static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
569{
b873a275 570 return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
7a3e97b0
SY
571}
572
1ab27c9c
ST
573static void ufshcd_ungate_work(struct work_struct *work)
574{
575 int ret;
576 unsigned long flags;
577 struct ufs_hba *hba = container_of(work, struct ufs_hba,
578 clk_gating.ungate_work);
579
580 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
581
582 spin_lock_irqsave(hba->host->host_lock, flags);
583 if (hba->clk_gating.state == CLKS_ON) {
584 spin_unlock_irqrestore(hba->host->host_lock, flags);
585 goto unblock_reqs;
586 }
587
588 spin_unlock_irqrestore(hba->host->host_lock, flags);
589 ufshcd_setup_clocks(hba, true);
590
591 /* Exit from hibern8 */
592 if (ufshcd_can_hibern8_during_gating(hba)) {
593 /* Prevent gating in this path */
594 hba->clk_gating.is_suspended = true;
595 if (ufshcd_is_link_hibern8(hba)) {
596 ret = ufshcd_uic_hibern8_exit(hba);
597 if (ret)
598 dev_err(hba->dev, "%s: hibern8 exit failed %d\n",
599 __func__, ret);
600 else
601 ufshcd_set_link_active(hba);
602 }
603 hba->clk_gating.is_suspended = false;
604 }
605unblock_reqs:
856b3483
ST
606 if (ufshcd_is_clkscaling_enabled(hba))
607 devfreq_resume_device(hba->devfreq);
1ab27c9c
ST
608 scsi_unblock_requests(hba->host);
609}
610
611/**
612 * ufshcd_hold - Enable clocks that were gated earlier due to ufshcd_release.
613 * Also, exit from hibern8 mode and set the link as active.
614 * @hba: per adapter instance
615 * @async: This indicates whether caller should ungate clocks asynchronously.
616 */
617int ufshcd_hold(struct ufs_hba *hba, bool async)
618{
619 int rc = 0;
620 unsigned long flags;
621
622 if (!ufshcd_is_clkgating_allowed(hba))
623 goto out;
1ab27c9c
ST
624 spin_lock_irqsave(hba->host->host_lock, flags);
625 hba->clk_gating.active_reqs++;
626
53c12d0e
YG
627 if (ufshcd_eh_in_progress(hba)) {
628 spin_unlock_irqrestore(hba->host->host_lock, flags);
629 return 0;
630 }
631
856b3483 632start:
1ab27c9c
ST
633 switch (hba->clk_gating.state) {
634 case CLKS_ON:
635 break;
636 case REQ_CLKS_OFF:
637 if (cancel_delayed_work(&hba->clk_gating.gate_work)) {
638 hba->clk_gating.state = CLKS_ON;
639 break;
640 }
641 /*
642 * If we here, it means gating work is either done or
643 * currently running. Hence, fall through to cancel gating
644 * work and to enable clocks.
645 */
646 case CLKS_OFF:
647 scsi_block_requests(hba->host);
648 hba->clk_gating.state = REQ_CLKS_ON;
649 schedule_work(&hba->clk_gating.ungate_work);
650 /*
651 * fall through to check if we should wait for this
652 * work to be done or not.
653 */
654 case REQ_CLKS_ON:
655 if (async) {
656 rc = -EAGAIN;
657 hba->clk_gating.active_reqs--;
658 break;
659 }
660
661 spin_unlock_irqrestore(hba->host->host_lock, flags);
662 flush_work(&hba->clk_gating.ungate_work);
663 /* Make sure state is CLKS_ON before returning */
856b3483 664 spin_lock_irqsave(hba->host->host_lock, flags);
1ab27c9c
ST
665 goto start;
666 default:
667 dev_err(hba->dev, "%s: clk gating is in invalid state %d\n",
668 __func__, hba->clk_gating.state);
669 break;
670 }
671 spin_unlock_irqrestore(hba->host->host_lock, flags);
672out:
673 return rc;
674}
6e3fd44d 675EXPORT_SYMBOL_GPL(ufshcd_hold);
1ab27c9c
ST
676
677static void ufshcd_gate_work(struct work_struct *work)
678{
679 struct ufs_hba *hba = container_of(work, struct ufs_hba,
680 clk_gating.gate_work.work);
681 unsigned long flags;
682
683 spin_lock_irqsave(hba->host->host_lock, flags);
684 if (hba->clk_gating.is_suspended) {
685 hba->clk_gating.state = CLKS_ON;
686 goto rel_lock;
687 }
688
689 if (hba->clk_gating.active_reqs
690 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
691 || hba->lrb_in_use || hba->outstanding_tasks
692 || hba->active_uic_cmd || hba->uic_async_done)
693 goto rel_lock;
694
695 spin_unlock_irqrestore(hba->host->host_lock, flags);
696
697 /* put the link into hibern8 mode before turning off clocks */
698 if (ufshcd_can_hibern8_during_gating(hba)) {
699 if (ufshcd_uic_hibern8_enter(hba)) {
700 hba->clk_gating.state = CLKS_ON;
701 goto out;
702 }
703 ufshcd_set_link_hibern8(hba);
704 }
705
856b3483
ST
706 if (ufshcd_is_clkscaling_enabled(hba)) {
707 devfreq_suspend_device(hba->devfreq);
708 hba->clk_scaling.window_start_t = 0;
709 }
710
1ab27c9c
ST
711 if (!ufshcd_is_link_active(hba))
712 ufshcd_setup_clocks(hba, false);
713 else
714 /* If link is active, device ref_clk can't be switched off */
715 __ufshcd_setup_clocks(hba, false, true);
716
717 /*
718 * In case you are here to cancel this work the gating state
719 * would be marked as REQ_CLKS_ON. In this case keep the state
720 * as REQ_CLKS_ON which would anyway imply that clocks are off
721 * and a request to turn them on is pending. By doing this way,
722 * we keep the state machine in tact and this would ultimately
723 * prevent from doing cancel work multiple times when there are
724 * new requests arriving before the current cancel work is done.
725 */
726 spin_lock_irqsave(hba->host->host_lock, flags);
727 if (hba->clk_gating.state == REQ_CLKS_OFF)
728 hba->clk_gating.state = CLKS_OFF;
729
730rel_lock:
731 spin_unlock_irqrestore(hba->host->host_lock, flags);
732out:
733 return;
734}
735
736/* host lock must be held before calling this variant */
737static void __ufshcd_release(struct ufs_hba *hba)
738{
739 if (!ufshcd_is_clkgating_allowed(hba))
740 return;
741
742 hba->clk_gating.active_reqs--;
743
744 if (hba->clk_gating.active_reqs || hba->clk_gating.is_suspended
745 || hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL
746 || hba->lrb_in_use || hba->outstanding_tasks
53c12d0e
YG
747 || hba->active_uic_cmd || hba->uic_async_done
748 || ufshcd_eh_in_progress(hba))
1ab27c9c
ST
749 return;
750
751 hba->clk_gating.state = REQ_CLKS_OFF;
752 schedule_delayed_work(&hba->clk_gating.gate_work,
753 msecs_to_jiffies(hba->clk_gating.delay_ms));
754}
755
756void ufshcd_release(struct ufs_hba *hba)
757{
758 unsigned long flags;
759
760 spin_lock_irqsave(hba->host->host_lock, flags);
761 __ufshcd_release(hba);
762 spin_unlock_irqrestore(hba->host->host_lock, flags);
763}
6e3fd44d 764EXPORT_SYMBOL_GPL(ufshcd_release);
1ab27c9c
ST
765
766static ssize_t ufshcd_clkgate_delay_show(struct device *dev,
767 struct device_attribute *attr, char *buf)
768{
769 struct ufs_hba *hba = dev_get_drvdata(dev);
770
771 return snprintf(buf, PAGE_SIZE, "%lu\n", hba->clk_gating.delay_ms);
772}
773
774static ssize_t ufshcd_clkgate_delay_store(struct device *dev,
775 struct device_attribute *attr, const char *buf, size_t count)
776{
777 struct ufs_hba *hba = dev_get_drvdata(dev);
778 unsigned long flags, value;
779
780 if (kstrtoul(buf, 0, &value))
781 return -EINVAL;
782
783 spin_lock_irqsave(hba->host->host_lock, flags);
784 hba->clk_gating.delay_ms = value;
785 spin_unlock_irqrestore(hba->host->host_lock, flags);
786 return count;
787}
788
789static void ufshcd_init_clk_gating(struct ufs_hba *hba)
790{
791 if (!ufshcd_is_clkgating_allowed(hba))
792 return;
793
794 hba->clk_gating.delay_ms = 150;
795 INIT_DELAYED_WORK(&hba->clk_gating.gate_work, ufshcd_gate_work);
796 INIT_WORK(&hba->clk_gating.ungate_work, ufshcd_ungate_work);
797
798 hba->clk_gating.delay_attr.show = ufshcd_clkgate_delay_show;
799 hba->clk_gating.delay_attr.store = ufshcd_clkgate_delay_store;
800 sysfs_attr_init(&hba->clk_gating.delay_attr.attr);
801 hba->clk_gating.delay_attr.attr.name = "clkgate_delay_ms";
802 hba->clk_gating.delay_attr.attr.mode = S_IRUGO | S_IWUSR;
803 if (device_create_file(hba->dev, &hba->clk_gating.delay_attr))
804 dev_err(hba->dev, "Failed to create sysfs for clkgate_delay\n");
805}
806
807static void ufshcd_exit_clk_gating(struct ufs_hba *hba)
808{
809 if (!ufshcd_is_clkgating_allowed(hba))
810 return;
811 device_remove_file(hba->dev, &hba->clk_gating.delay_attr);
97cd6805
AM
812 cancel_work_sync(&hba->clk_gating.ungate_work);
813 cancel_delayed_work_sync(&hba->clk_gating.gate_work);
1ab27c9c
ST
814}
815
856b3483
ST
816/* Must be called with host lock acquired */
817static void ufshcd_clk_scaling_start_busy(struct ufs_hba *hba)
818{
819 if (!ufshcd_is_clkscaling_enabled(hba))
820 return;
821
822 if (!hba->clk_scaling.is_busy_started) {
823 hba->clk_scaling.busy_start_t = ktime_get();
824 hba->clk_scaling.is_busy_started = true;
825 }
826}
827
828static void ufshcd_clk_scaling_update_busy(struct ufs_hba *hba)
829{
830 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
831
832 if (!ufshcd_is_clkscaling_enabled(hba))
833 return;
834
835 if (!hba->outstanding_reqs && scaling->is_busy_started) {
836 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
837 scaling->busy_start_t));
838 scaling->busy_start_t = ktime_set(0, 0);
839 scaling->is_busy_started = false;
840 }
841}
7a3e97b0
SY
842/**
843 * ufshcd_send_command - Send SCSI or device management commands
844 * @hba: per adapter instance
845 * @task_tag: Task tag of the command
846 */
847static inline
848void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
849{
856b3483 850 ufshcd_clk_scaling_start_busy(hba);
7a3e97b0 851 __set_bit(task_tag, &hba->outstanding_reqs);
b873a275 852 ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
7a3e97b0
SY
853}
854
855/**
856 * ufshcd_copy_sense_data - Copy sense data in case of check condition
857 * @lrb - pointer to local reference block
858 */
859static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
860{
861 int len;
1c2623c5
SJ
862 if (lrbp->sense_buffer &&
863 ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
5a0b0cb9 864 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
7a3e97b0 865 memcpy(lrbp->sense_buffer,
5a0b0cb9 866 lrbp->ucd_rsp_ptr->sr.sense_data,
7a3e97b0
SY
867 min_t(int, len, SCSI_SENSE_BUFFERSIZE));
868 }
869}
870
68078d5c
DR
871/**
872 * ufshcd_copy_query_response() - Copy the Query Response and the data
873 * descriptor
874 * @hba: per adapter instance
875 * @lrb - pointer to local reference block
876 */
877static
c6d4a831 878int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
68078d5c
DR
879{
880 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
881
68078d5c 882 memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
68078d5c 883
68078d5c
DR
884 /* Get the descriptor */
885 if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
d44a5f98 886 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
68078d5c 887 GENERAL_UPIU_REQUEST_SIZE;
c6d4a831
DR
888 u16 resp_len;
889 u16 buf_len;
68078d5c
DR
890
891 /* data segment length */
c6d4a831 892 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
68078d5c 893 MASK_QUERY_DATA_SEG_LEN;
ea2aab24
SRT
894 buf_len = be16_to_cpu(
895 hba->dev_cmd.query.request.upiu_req.length);
c6d4a831
DR
896 if (likely(buf_len >= resp_len)) {
897 memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
898 } else {
899 dev_warn(hba->dev,
900 "%s: Response size is bigger than buffer",
901 __func__);
902 return -EINVAL;
903 }
68078d5c 904 }
c6d4a831
DR
905
906 return 0;
68078d5c
DR
907}
908
7a3e97b0
SY
909/**
910 * ufshcd_hba_capabilities - Read controller capabilities
911 * @hba: per adapter instance
912 */
913static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
914{
b873a275 915 hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
7a3e97b0
SY
916
917 /* nutrs and nutmrs are 0 based values */
918 hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
919 hba->nutmrs =
920 ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
921}
922
923/**
6ccf44fe
SJ
924 * ufshcd_ready_for_uic_cmd - Check if controller is ready
925 * to accept UIC commands
7a3e97b0 926 * @hba: per adapter instance
6ccf44fe
SJ
927 * Return true on success, else false
928 */
929static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
930{
931 if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
932 return true;
933 else
934 return false;
935}
936
53b3d9c3
SJ
937/**
938 * ufshcd_get_upmcrs - Get the power mode change request status
939 * @hba: Pointer to adapter instance
940 *
941 * This function gets the UPMCRS field of HCS register
942 * Returns value of UPMCRS field
943 */
944static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
945{
946 return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
947}
948
6ccf44fe
SJ
949/**
950 * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
951 * @hba: per adapter instance
952 * @uic_cmd: UIC command
953 *
954 * Mutex must be held.
7a3e97b0
SY
955 */
956static inline void
6ccf44fe 957ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
7a3e97b0 958{
6ccf44fe
SJ
959 WARN_ON(hba->active_uic_cmd);
960
961 hba->active_uic_cmd = uic_cmd;
962
7a3e97b0 963 /* Write Args */
6ccf44fe
SJ
964 ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
965 ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
966 ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
7a3e97b0
SY
967
968 /* Write UIC Cmd */
6ccf44fe 969 ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
b873a275 970 REG_UIC_COMMAND);
7a3e97b0
SY
971}
972
6ccf44fe
SJ
973/**
974 * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
975 * @hba: per adapter instance
976 * @uic_command: UIC command
977 *
978 * Must be called with mutex held.
979 * Returns 0 only if success.
980 */
981static int
982ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
983{
984 int ret;
985 unsigned long flags;
986
987 if (wait_for_completion_timeout(&uic_cmd->done,
988 msecs_to_jiffies(UIC_CMD_TIMEOUT)))
989 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
990 else
991 ret = -ETIMEDOUT;
992
993 spin_lock_irqsave(hba->host->host_lock, flags);
994 hba->active_uic_cmd = NULL;
995 spin_unlock_irqrestore(hba->host->host_lock, flags);
996
997 return ret;
998}
999
1000/**
1001 * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1002 * @hba: per adapter instance
1003 * @uic_cmd: UIC command
d75f7fe4 1004 * @completion: initialize the completion only if this is set to true
6ccf44fe
SJ
1005 *
1006 * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
57d104c1 1007 * with mutex held and host_lock locked.
6ccf44fe
SJ
1008 * Returns 0 only if success.
1009 */
1010static int
d75f7fe4
YG
1011__ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd,
1012 bool completion)
6ccf44fe 1013{
6ccf44fe
SJ
1014 if (!ufshcd_ready_for_uic_cmd(hba)) {
1015 dev_err(hba->dev,
1016 "Controller not ready to accept UIC commands\n");
1017 return -EIO;
1018 }
1019
d75f7fe4
YG
1020 if (completion)
1021 init_completion(&uic_cmd->done);
6ccf44fe 1022
6ccf44fe 1023 ufshcd_dispatch_uic_cmd(hba, uic_cmd);
6ccf44fe 1024
57d104c1 1025 return 0;
6ccf44fe
SJ
1026}
1027
1028/**
1029 * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
1030 * @hba: per adapter instance
1031 * @uic_cmd: UIC command
1032 *
1033 * Returns 0 only if success.
1034 */
1035static int
1036ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
1037{
1038 int ret;
57d104c1 1039 unsigned long flags;
6ccf44fe 1040
1ab27c9c 1041 ufshcd_hold(hba, false);
6ccf44fe 1042 mutex_lock(&hba->uic_cmd_mutex);
cad2e03d
YG
1043 ufshcd_add_delay_before_dme_cmd(hba);
1044
57d104c1 1045 spin_lock_irqsave(hba->host->host_lock, flags);
d75f7fe4 1046 ret = __ufshcd_send_uic_cmd(hba, uic_cmd, true);
57d104c1
SJ
1047 spin_unlock_irqrestore(hba->host->host_lock, flags);
1048 if (!ret)
1049 ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
1050
6ccf44fe
SJ
1051 mutex_unlock(&hba->uic_cmd_mutex);
1052
1ab27c9c 1053 ufshcd_release(hba);
6ccf44fe
SJ
1054 return ret;
1055}
1056
7a3e97b0
SY
1057/**
1058 * ufshcd_map_sg - Map scatter-gather list to prdt
1059 * @lrbp - pointer to local reference block
1060 *
1061 * Returns 0 in case of success, non-zero value in case of failure
1062 */
1063static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
1064{
1065 struct ufshcd_sg_entry *prd_table;
1066 struct scatterlist *sg;
1067 struct scsi_cmnd *cmd;
1068 int sg_segments;
1069 int i;
1070
1071 cmd = lrbp->cmd;
1072 sg_segments = scsi_dma_map(cmd);
1073 if (sg_segments < 0)
1074 return sg_segments;
1075
1076 if (sg_segments) {
1077 lrbp->utr_descriptor_ptr->prd_table_length =
1078 cpu_to_le16((u16) (sg_segments));
1079
1080 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
1081
1082 scsi_for_each_sg(cmd, sg, sg_segments, i) {
1083 prd_table[i].size =
1084 cpu_to_le32(((u32) sg_dma_len(sg))-1);
1085 prd_table[i].base_addr =
1086 cpu_to_le32(lower_32_bits(sg->dma_address));
1087 prd_table[i].upper_addr =
1088 cpu_to_le32(upper_32_bits(sg->dma_address));
52ac95fe 1089 prd_table[i].reserved = 0;
7a3e97b0
SY
1090 }
1091 } else {
1092 lrbp->utr_descriptor_ptr->prd_table_length = 0;
1093 }
1094
1095 return 0;
1096}
1097
1098/**
2fbd009b 1099 * ufshcd_enable_intr - enable interrupts
7a3e97b0 1100 * @hba: per adapter instance
2fbd009b 1101 * @intrs: interrupt bits
7a3e97b0 1102 */
2fbd009b 1103static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
7a3e97b0 1104{
2fbd009b
SJ
1105 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1106
1107 if (hba->ufs_version == UFSHCI_VERSION_10) {
1108 u32 rw;
1109 rw = set & INTERRUPT_MASK_RW_VER_10;
1110 set = rw | ((set ^ intrs) & intrs);
1111 } else {
1112 set |= intrs;
1113 }
1114
1115 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
1116}
1117
1118/**
1119 * ufshcd_disable_intr - disable interrupts
1120 * @hba: per adapter instance
1121 * @intrs: interrupt bits
1122 */
1123static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
1124{
1125 u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
1126
1127 if (hba->ufs_version == UFSHCI_VERSION_10) {
1128 u32 rw;
1129 rw = (set & INTERRUPT_MASK_RW_VER_10) &
1130 ~(intrs & INTERRUPT_MASK_RW_VER_10);
1131 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
1132
1133 } else {
1134 set &= ~intrs;
7a3e97b0 1135 }
2fbd009b
SJ
1136
1137 ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
7a3e97b0
SY
1138}
1139
5a0b0cb9
SRT
1140/**
1141 * ufshcd_prepare_req_desc_hdr() - Fills the requests header
1142 * descriptor according to request
1143 * @lrbp: pointer to local reference block
1144 * @upiu_flags: flags required in the header
1145 * @cmd_dir: requests data direction
1146 */
1147static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
1148 u32 *upiu_flags, enum dma_data_direction cmd_dir)
1149{
1150 struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
1151 u32 data_direction;
1152 u32 dword_0;
1153
1154 if (cmd_dir == DMA_FROM_DEVICE) {
1155 data_direction = UTP_DEVICE_TO_HOST;
1156 *upiu_flags = UPIU_CMD_FLAGS_READ;
1157 } else if (cmd_dir == DMA_TO_DEVICE) {
1158 data_direction = UTP_HOST_TO_DEVICE;
1159 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
1160 } else {
1161 data_direction = UTP_NO_DATA_TRANSFER;
1162 *upiu_flags = UPIU_CMD_FLAGS_NONE;
1163 }
1164
1165 dword_0 = data_direction | (lrbp->command_type
1166 << UPIU_COMMAND_TYPE_OFFSET);
1167 if (lrbp->intr_cmd)
1168 dword_0 |= UTP_REQ_DESC_INT_CMD;
1169
1170 /* Transfer request descriptor header fields */
1171 req_desc->header.dword_0 = cpu_to_le32(dword_0);
52ac95fe
YG
1172 /* dword_1 is reserved, hence it is set to 0 */
1173 req_desc->header.dword_1 = 0;
5a0b0cb9
SRT
1174 /*
1175 * assigning invalid value for command status. Controller
1176 * updates OCS on command completion, with the command
1177 * status
1178 */
1179 req_desc->header.dword_2 =
1180 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
52ac95fe
YG
1181 /* dword_3 is reserved, hence it is set to 0 */
1182 req_desc->header.dword_3 = 0;
51047266
YG
1183
1184 req_desc->prd_table_length = 0;
5a0b0cb9
SRT
1185}
1186
1187/**
1188 * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
1189 * for scsi commands
1190 * @lrbp - local reference block pointer
1191 * @upiu_flags - flags
1192 */
1193static
1194void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
1195{
1196 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
52ac95fe 1197 unsigned short cdb_len;
5a0b0cb9
SRT
1198
1199 /* command descriptor fields */
1200 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1201 UPIU_TRANSACTION_COMMAND, upiu_flags,
1202 lrbp->lun, lrbp->task_tag);
1203 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1204 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
1205
1206 /* Total EHS length and Data segment length will be zero */
1207 ucd_req_ptr->header.dword_2 = 0;
1208
1209 ucd_req_ptr->sc.exp_data_transfer_len =
1210 cpu_to_be32(lrbp->cmd->sdb.length);
1211
52ac95fe
YG
1212 cdb_len = min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE);
1213 memset(ucd_req_ptr->sc.cdb, 0, MAX_CDB_SIZE);
1214 memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd, cdb_len);
1215
1216 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5a0b0cb9
SRT
1217}
1218
68078d5c
DR
1219/**
1220 * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
1221 * for query requsts
1222 * @hba: UFS hba
1223 * @lrbp: local reference block pointer
1224 * @upiu_flags: flags
1225 */
1226static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
1227 struct ufshcd_lrb *lrbp, u32 upiu_flags)
1228{
1229 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1230 struct ufs_query *query = &hba->dev_cmd.query;
e8c8e82a 1231 u16 len = be16_to_cpu(query->request.upiu_req.length);
68078d5c
DR
1232 u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
1233
1234 /* Query request header */
1235 ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
1236 UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
1237 lrbp->lun, lrbp->task_tag);
1238 ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
1239 0, query->request.query_func, 0, 0);
1240
1241 /* Data segment length */
1242 ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
1243 0, 0, len >> 8, (u8)len);
1244
1245 /* Copy the Query Request buffer as is */
1246 memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
1247 QUERY_OSF_SIZE);
68078d5c
DR
1248
1249 /* Copy the Descriptor */
c6d4a831
DR
1250 if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
1251 memcpy(descp, query->descriptor, len);
1252
51047266 1253 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
68078d5c
DR
1254}
1255
5a0b0cb9
SRT
1256static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
1257{
1258 struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
1259
1260 memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
1261
1262 /* command descriptor fields */
1263 ucd_req_ptr->header.dword_0 =
1264 UPIU_HEADER_DWORD(
1265 UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
51047266
YG
1266 /* clear rest of the fields of basic header */
1267 ucd_req_ptr->header.dword_1 = 0;
1268 ucd_req_ptr->header.dword_2 = 0;
1269
1270 memset(lrbp->ucd_rsp_ptr, 0, sizeof(struct utp_upiu_rsp));
5a0b0cb9
SRT
1271}
1272
7a3e97b0
SY
1273/**
1274 * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
5a0b0cb9 1275 * @hba - per adapter instance
7a3e97b0
SY
1276 * @lrb - pointer to local reference block
1277 */
5a0b0cb9 1278static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
7a3e97b0 1279{
7a3e97b0 1280 u32 upiu_flags;
5a0b0cb9 1281 int ret = 0;
7a3e97b0
SY
1282
1283 switch (lrbp->command_type) {
1284 case UTP_CMD_TYPE_SCSI:
5a0b0cb9
SRT
1285 if (likely(lrbp->cmd)) {
1286 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
1287 lrbp->cmd->sc_data_direction);
1288 ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
7a3e97b0 1289 } else {
5a0b0cb9 1290 ret = -EINVAL;
7a3e97b0 1291 }
7a3e97b0
SY
1292 break;
1293 case UTP_CMD_TYPE_DEV_MANAGE:
5a0b0cb9 1294 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
68078d5c
DR
1295 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
1296 ufshcd_prepare_utp_query_req_upiu(
1297 hba, lrbp, upiu_flags);
1298 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
5a0b0cb9
SRT
1299 ufshcd_prepare_utp_nop_upiu(lrbp);
1300 else
1301 ret = -EINVAL;
7a3e97b0
SY
1302 break;
1303 case UTP_CMD_TYPE_UFS:
1304 /* For UFS native command implementation */
5a0b0cb9
SRT
1305 ret = -ENOTSUPP;
1306 dev_err(hba->dev, "%s: UFS native command are not supported\n",
1307 __func__);
1308 break;
1309 default:
1310 ret = -ENOTSUPP;
1311 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
1312 __func__, lrbp->command_type);
7a3e97b0
SY
1313 break;
1314 } /* end of switch */
5a0b0cb9
SRT
1315
1316 return ret;
7a3e97b0
SY
1317}
1318
0ce147d4
SJ
1319/*
1320 * ufshcd_scsi_to_upiu_lun - maps scsi LUN to UPIU LUN
1321 * @scsi_lun: scsi LUN id
1322 *
1323 * Returns UPIU LUN id
1324 */
1325static inline u8 ufshcd_scsi_to_upiu_lun(unsigned int scsi_lun)
1326{
1327 if (scsi_is_wlun(scsi_lun))
1328 return (scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID)
1329 | UFS_UPIU_WLUN_ID;
1330 else
1331 return scsi_lun & UFS_UPIU_MAX_UNIT_NUM_ID;
1332}
1333
2a8fa600
SJ
1334/**
1335 * ufshcd_upiu_wlun_to_scsi_wlun - maps UPIU W-LUN id to SCSI W-LUN ID
1336 * @scsi_lun: UPIU W-LUN id
1337 *
1338 * Returns SCSI W-LUN id
1339 */
1340static inline u16 ufshcd_upiu_wlun_to_scsi_wlun(u8 upiu_wlun_id)
1341{
1342 return (upiu_wlun_id & ~UFS_UPIU_WLUN_ID) | SCSI_W_LUN_BASE;
1343}
1344
7a3e97b0
SY
1345/**
1346 * ufshcd_queuecommand - main entry point for SCSI requests
1347 * @cmd: command from SCSI Midlayer
1348 * @done: call back function
1349 *
1350 * Returns 0 for success, non-zero in case of failure
1351 */
1352static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
1353{
1354 struct ufshcd_lrb *lrbp;
1355 struct ufs_hba *hba;
1356 unsigned long flags;
1357 int tag;
1358 int err = 0;
1359
1360 hba = shost_priv(host);
1361
1362 tag = cmd->request->tag;
14497328
YG
1363 if (!ufshcd_valid_tag(hba, tag)) {
1364 dev_err(hba->dev,
1365 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
1366 __func__, tag, cmd, cmd->request);
1367 BUG();
1368 }
7a3e97b0 1369
3441da7d
SRT
1370 spin_lock_irqsave(hba->host->host_lock, flags);
1371 switch (hba->ufshcd_state) {
1372 case UFSHCD_STATE_OPERATIONAL:
1373 break;
1374 case UFSHCD_STATE_RESET:
7a3e97b0 1375 err = SCSI_MLQUEUE_HOST_BUSY;
3441da7d
SRT
1376 goto out_unlock;
1377 case UFSHCD_STATE_ERROR:
1378 set_host_byte(cmd, DID_ERROR);
1379 cmd->scsi_done(cmd);
1380 goto out_unlock;
1381 default:
1382 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
1383 __func__, hba->ufshcd_state);
1384 set_host_byte(cmd, DID_BAD_TARGET);
1385 cmd->scsi_done(cmd);
1386 goto out_unlock;
7a3e97b0 1387 }
53c12d0e
YG
1388
1389 /* if error handling is in progress, don't issue commands */
1390 if (ufshcd_eh_in_progress(hba)) {
1391 set_host_byte(cmd, DID_ERROR);
1392 cmd->scsi_done(cmd);
1393 goto out_unlock;
1394 }
3441da7d 1395 spin_unlock_irqrestore(hba->host->host_lock, flags);
7a3e97b0 1396
5a0b0cb9
SRT
1397 /* acquire the tag to make sure device cmds don't use it */
1398 if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
1399 /*
1400 * Dev manage command in progress, requeue the command.
1401 * Requeuing the command helps in cases where the request *may*
1402 * find different tag instead of waiting for dev manage command
1403 * completion.
1404 */
1405 err = SCSI_MLQUEUE_HOST_BUSY;
1406 goto out;
1407 }
1408
1ab27c9c
ST
1409 err = ufshcd_hold(hba, true);
1410 if (err) {
1411 err = SCSI_MLQUEUE_HOST_BUSY;
1412 clear_bit_unlock(tag, &hba->lrb_in_use);
1413 goto out;
1414 }
1415 WARN_ON(hba->clk_gating.state != CLKS_ON);
1416
7a3e97b0
SY
1417 lrbp = &hba->lrb[tag];
1418
5a0b0cb9 1419 WARN_ON(lrbp->cmd);
7a3e97b0
SY
1420 lrbp->cmd = cmd;
1421 lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
1422 lrbp->sense_buffer = cmd->sense_buffer;
1423 lrbp->task_tag = tag;
0ce147d4 1424 lrbp->lun = ufshcd_scsi_to_upiu_lun(cmd->device->lun);
b852190e 1425 lrbp->intr_cmd = !ufshcd_is_intr_aggr_allowed(hba) ? true : false;
7a3e97b0
SY
1426 lrbp->command_type = UTP_CMD_TYPE_SCSI;
1427
1428 /* form UPIU before issuing the command */
5a0b0cb9 1429 ufshcd_compose_upiu(hba, lrbp);
7a3e97b0 1430 err = ufshcd_map_sg(lrbp);
5a0b0cb9
SRT
1431 if (err) {
1432 lrbp->cmd = NULL;
1433 clear_bit_unlock(tag, &hba->lrb_in_use);
7a3e97b0 1434 goto out;
5a0b0cb9 1435 }
7a3e97b0
SY
1436
1437 /* issue command to the controller */
1438 spin_lock_irqsave(hba->host->host_lock, flags);
1439 ufshcd_send_command(hba, tag);
3441da7d 1440out_unlock:
7a3e97b0
SY
1441 spin_unlock_irqrestore(hba->host->host_lock, flags);
1442out:
1443 return err;
1444}
1445
5a0b0cb9
SRT
1446static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
1447 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
1448{
1449 lrbp->cmd = NULL;
1450 lrbp->sense_bufflen = 0;
1451 lrbp->sense_buffer = NULL;
1452 lrbp->task_tag = tag;
1453 lrbp->lun = 0; /* device management cmd is not specific to any LUN */
1454 lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
1455 lrbp->intr_cmd = true; /* No interrupt aggregation */
1456 hba->dev_cmd.type = cmd_type;
1457
1458 return ufshcd_compose_upiu(hba, lrbp);
1459}
1460
1461static int
1462ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
1463{
1464 int err = 0;
1465 unsigned long flags;
1466 u32 mask = 1 << tag;
1467
1468 /* clear outstanding transaction before retry */
1469 spin_lock_irqsave(hba->host->host_lock, flags);
1470 ufshcd_utrl_clear(hba, tag);
1471 spin_unlock_irqrestore(hba->host->host_lock, flags);
1472
1473 /*
1474 * wait for for h/w to clear corresponding bit in door-bell.
1475 * max. wait is 1 sec.
1476 */
1477 err = ufshcd_wait_for_register(hba,
1478 REG_UTP_TRANSFER_REQ_DOOR_BELL,
596585a2 1479 mask, ~mask, 1000, 1000, true);
5a0b0cb9
SRT
1480
1481 return err;
1482}
1483
c6d4a831
DR
1484static int
1485ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1486{
1487 struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
1488
1489 /* Get the UPIU response */
1490 query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
1491 UPIU_RSP_CODE_OFFSET;
1492 return query_res->response;
1493}
1494
5a0b0cb9
SRT
1495/**
1496 * ufshcd_dev_cmd_completion() - handles device management command responses
1497 * @hba: per adapter instance
1498 * @lrbp: pointer to local reference block
1499 */
1500static int
1501ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1502{
1503 int resp;
1504 int err = 0;
1505
1506 resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1507
1508 switch (resp) {
1509 case UPIU_TRANSACTION_NOP_IN:
1510 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1511 err = -EINVAL;
1512 dev_err(hba->dev, "%s: unexpected response %x\n",
1513 __func__, resp);
1514 }
1515 break;
68078d5c 1516 case UPIU_TRANSACTION_QUERY_RSP:
c6d4a831
DR
1517 err = ufshcd_check_query_response(hba, lrbp);
1518 if (!err)
1519 err = ufshcd_copy_query_response(hba, lrbp);
68078d5c 1520 break;
5a0b0cb9
SRT
1521 case UPIU_TRANSACTION_REJECT_UPIU:
1522 /* TODO: handle Reject UPIU Response */
1523 err = -EPERM;
1524 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1525 __func__);
1526 break;
1527 default:
1528 err = -EINVAL;
1529 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1530 __func__, resp);
1531 break;
1532 }
1533
1534 return err;
1535}
1536
1537static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1538 struct ufshcd_lrb *lrbp, int max_timeout)
1539{
1540 int err = 0;
1541 unsigned long time_left;
1542 unsigned long flags;
1543
1544 time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1545 msecs_to_jiffies(max_timeout));
1546
1547 spin_lock_irqsave(hba->host->host_lock, flags);
1548 hba->dev_cmd.complete = NULL;
1549 if (likely(time_left)) {
1550 err = ufshcd_get_tr_ocs(lrbp);
1551 if (!err)
1552 err = ufshcd_dev_cmd_completion(hba, lrbp);
1553 }
1554 spin_unlock_irqrestore(hba->host->host_lock, flags);
1555
1556 if (!time_left) {
1557 err = -ETIMEDOUT;
a48353f6
YG
1558 dev_dbg(hba->dev, "%s: dev_cmd request timedout, tag %d\n",
1559 __func__, lrbp->task_tag);
5a0b0cb9 1560 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
a48353f6 1561 /* successfully cleared the command, retry if needed */
5a0b0cb9 1562 err = -EAGAIN;
a48353f6
YG
1563 /*
1564 * in case of an error, after clearing the doorbell,
1565 * we also need to clear the outstanding_request
1566 * field in hba
1567 */
1568 ufshcd_outstanding_req_clear(hba, lrbp->task_tag);
5a0b0cb9
SRT
1569 }
1570
1571 return err;
1572}
1573
1574/**
1575 * ufshcd_get_dev_cmd_tag - Get device management command tag
1576 * @hba: per-adapter instance
1577 * @tag: pointer to variable with available slot value
1578 *
1579 * Get a free slot and lock it until device management command
1580 * completes.
1581 *
1582 * Returns false if free slot is unavailable for locking, else
1583 * return true with tag value in @tag.
1584 */
1585static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1586{
1587 int tag;
1588 bool ret = false;
1589 unsigned long tmp;
1590
1591 if (!tag_out)
1592 goto out;
1593
1594 do {
1595 tmp = ~hba->lrb_in_use;
1596 tag = find_last_bit(&tmp, hba->nutrs);
1597 if (tag >= hba->nutrs)
1598 goto out;
1599 } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1600
1601 *tag_out = tag;
1602 ret = true;
1603out:
1604 return ret;
1605}
1606
1607static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1608{
1609 clear_bit_unlock(tag, &hba->lrb_in_use);
1610}
1611
1612/**
1613 * ufshcd_exec_dev_cmd - API for sending device management requests
1614 * @hba - UFS hba
1615 * @cmd_type - specifies the type (NOP, Query...)
1616 * @timeout - time in seconds
1617 *
68078d5c
DR
1618 * NOTE: Since there is only one available tag for device management commands,
1619 * it is expected you hold the hba->dev_cmd.lock mutex.
5a0b0cb9
SRT
1620 */
1621static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1622 enum dev_cmd_type cmd_type, int timeout)
1623{
1624 struct ufshcd_lrb *lrbp;
1625 int err;
1626 int tag;
1627 struct completion wait;
1628 unsigned long flags;
1629
1630 /*
1631 * Get free slot, sleep if slots are unavailable.
1632 * Even though we use wait_event() which sleeps indefinitely,
1633 * the maximum wait time is bounded by SCSI request timeout.
1634 */
1635 wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1636
1637 init_completion(&wait);
1638 lrbp = &hba->lrb[tag];
1639 WARN_ON(lrbp->cmd);
1640 err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1641 if (unlikely(err))
1642 goto out_put_tag;
1643
1644 hba->dev_cmd.complete = &wait;
1645
e3dfdc53
YG
1646 /* Make sure descriptors are ready before ringing the doorbell */
1647 wmb();
5a0b0cb9
SRT
1648 spin_lock_irqsave(hba->host->host_lock, flags);
1649 ufshcd_send_command(hba, tag);
1650 spin_unlock_irqrestore(hba->host->host_lock, flags);
1651
1652 err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1653
1654out_put_tag:
1655 ufshcd_put_dev_cmd_tag(hba, tag);
1656 wake_up(&hba->dev_cmd.tag_wq);
1657 return err;
1658}
1659
d44a5f98
DR
1660/**
1661 * ufshcd_init_query() - init the query response and request parameters
1662 * @hba: per-adapter instance
1663 * @request: address of the request pointer to be initialized
1664 * @response: address of the response pointer to be initialized
1665 * @opcode: operation to perform
1666 * @idn: flag idn to access
1667 * @index: LU number to access
1668 * @selector: query/flag/descriptor further identification
1669 */
1670static inline void ufshcd_init_query(struct ufs_hba *hba,
1671 struct ufs_query_req **request, struct ufs_query_res **response,
1672 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1673{
1674 *request = &hba->dev_cmd.query.request;
1675 *response = &hba->dev_cmd.query.response;
1676 memset(*request, 0, sizeof(struct ufs_query_req));
1677 memset(*response, 0, sizeof(struct ufs_query_res));
1678 (*request)->upiu_req.opcode = opcode;
1679 (*request)->upiu_req.idn = idn;
1680 (*request)->upiu_req.index = index;
1681 (*request)->upiu_req.selector = selector;
1682}
1683
dc3c8d3a
YG
1684static int ufshcd_query_flag_retry(struct ufs_hba *hba,
1685 enum query_opcode opcode, enum flag_idn idn, bool *flag_res)
1686{
1687 int ret;
1688 int retries;
1689
1690 for (retries = 0; retries < QUERY_REQ_RETRIES; retries++) {
1691 ret = ufshcd_query_flag(hba, opcode, idn, flag_res);
1692 if (ret)
1693 dev_dbg(hba->dev,
1694 "%s: failed with error %d, retries %d\n",
1695 __func__, ret, retries);
1696 else
1697 break;
1698 }
1699
1700 if (ret)
1701 dev_err(hba->dev,
1702 "%s: query attribute, opcode %d, idn %d, failed with error %d after %d retires\n",
1703 __func__, opcode, idn, ret, retries);
1704 return ret;
1705}
1706
68078d5c
DR
1707/**
1708 * ufshcd_query_flag() - API function for sending flag query requests
1709 * hba: per-adapter instance
1710 * query_opcode: flag query to perform
1711 * idn: flag idn to access
1712 * flag_res: the flag value after the query request completes
1713 *
1714 * Returns 0 for success, non-zero in case of failure
1715 */
dc3c8d3a 1716int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
68078d5c
DR
1717 enum flag_idn idn, bool *flag_res)
1718{
d44a5f98
DR
1719 struct ufs_query_req *request = NULL;
1720 struct ufs_query_res *response = NULL;
1721 int err, index = 0, selector = 0;
e5ad406c 1722 int timeout = QUERY_REQ_TIMEOUT;
68078d5c
DR
1723
1724 BUG_ON(!hba);
1725
1ab27c9c 1726 ufshcd_hold(hba, false);
68078d5c 1727 mutex_lock(&hba->dev_cmd.lock);
d44a5f98
DR
1728 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1729 selector);
68078d5c
DR
1730
1731 switch (opcode) {
1732 case UPIU_QUERY_OPCODE_SET_FLAG:
1733 case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1734 case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1735 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1736 break;
1737 case UPIU_QUERY_OPCODE_READ_FLAG:
1738 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1739 if (!flag_res) {
1740 /* No dummy reads */
1741 dev_err(hba->dev, "%s: Invalid argument for read request\n",
1742 __func__);
1743 err = -EINVAL;
1744 goto out_unlock;
1745 }
1746 break;
1747 default:
1748 dev_err(hba->dev,
1749 "%s: Expected query flag opcode but got = %d\n",
1750 __func__, opcode);
1751 err = -EINVAL;
1752 goto out_unlock;
1753 }
68078d5c 1754
e5ad406c
YG
1755 if (idn == QUERY_FLAG_IDN_FDEVICEINIT)
1756 timeout = QUERY_FDEVICEINIT_REQ_TIMEOUT;
1757
1758 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, timeout);
68078d5c
DR
1759
1760 if (err) {
1761 dev_err(hba->dev,
1762 "%s: Sending flag query for idn %d failed, err = %d\n",
1763 __func__, idn, err);
1764 goto out_unlock;
1765 }
1766
1767 if (flag_res)
e8c8e82a 1768 *flag_res = (be32_to_cpu(response->upiu_res.value) &
68078d5c
DR
1769 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1770
1771out_unlock:
1772 mutex_unlock(&hba->dev_cmd.lock);
1ab27c9c 1773 ufshcd_release(hba);
68078d5c
DR
1774 return err;
1775}
1776
66ec6d59
SRT
1777/**
1778 * ufshcd_query_attr - API function for sending attribute requests
1779 * hba: per-adapter instance
1780 * opcode: attribute opcode
1781 * idn: attribute idn to access
1782 * index: index field
1783 * selector: selector field
1784 * attr_val: the attribute value after the query request completes
1785 *
1786 * Returns 0 for success, non-zero in case of failure
1787*/
bdbe5d2f 1788static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
66ec6d59
SRT
1789 enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1790{
d44a5f98
DR
1791 struct ufs_query_req *request = NULL;
1792 struct ufs_query_res *response = NULL;
66ec6d59
SRT
1793 int err;
1794
1795 BUG_ON(!hba);
1796
1ab27c9c 1797 ufshcd_hold(hba, false);
66ec6d59
SRT
1798 if (!attr_val) {
1799 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1800 __func__, opcode);
1801 err = -EINVAL;
1802 goto out;
1803 }
1804
1805 mutex_lock(&hba->dev_cmd.lock);
d44a5f98
DR
1806 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1807 selector);
66ec6d59
SRT
1808
1809 switch (opcode) {
1810 case UPIU_QUERY_OPCODE_WRITE_ATTR:
1811 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
e8c8e82a 1812 request->upiu_req.value = cpu_to_be32(*attr_val);
66ec6d59
SRT
1813 break;
1814 case UPIU_QUERY_OPCODE_READ_ATTR:
1815 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1816 break;
1817 default:
1818 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1819 __func__, opcode);
1820 err = -EINVAL;
1821 goto out_unlock;
1822 }
1823
d44a5f98 1824 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
66ec6d59
SRT
1825
1826 if (err) {
1827 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1828 __func__, opcode, idn, err);
1829 goto out_unlock;
1830 }
1831
e8c8e82a 1832 *attr_val = be32_to_cpu(response->upiu_res.value);
66ec6d59
SRT
1833
1834out_unlock:
1835 mutex_unlock(&hba->dev_cmd.lock);
1836out:
1ab27c9c 1837 ufshcd_release(hba);
66ec6d59
SRT
1838 return err;
1839}
1840
5e86ae44
YG
1841/**
1842 * ufshcd_query_attr_retry() - API function for sending query
1843 * attribute with retries
1844 * @hba: per-adapter instance
1845 * @opcode: attribute opcode
1846 * @idn: attribute idn to access
1847 * @index: index field
1848 * @selector: selector field
1849 * @attr_val: the attribute value after the query request
1850 * completes
1851 *
1852 * Returns 0 for success, non-zero in case of failure
1853*/
1854static int ufshcd_query_attr_retry(struct ufs_hba *hba,
1855 enum query_opcode opcode, enum attr_idn idn, u8 index, u8 selector,
1856 u32 *attr_val)
1857{
1858 int ret = 0;
1859 u32 retries;
1860
1861 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1862 ret = ufshcd_query_attr(hba, opcode, idn, index,
1863 selector, attr_val);
1864 if (ret)
1865 dev_dbg(hba->dev, "%s: failed with error %d, retries %d\n",
1866 __func__, ret, retries);
1867 else
1868 break;
1869 }
1870
1871 if (ret)
1872 dev_err(hba->dev,
1873 "%s: query attribute, idn %d, failed with error %d after %d retires\n",
1874 __func__, idn, ret, QUERY_REQ_RETRIES);
1875 return ret;
1876}
1877
a70e91b8 1878static int __ufshcd_query_descriptor(struct ufs_hba *hba,
d44a5f98
DR
1879 enum query_opcode opcode, enum desc_idn idn, u8 index,
1880 u8 selector, u8 *desc_buf, int *buf_len)
1881{
1882 struct ufs_query_req *request = NULL;
1883 struct ufs_query_res *response = NULL;
1884 int err;
1885
1886 BUG_ON(!hba);
1887
1ab27c9c 1888 ufshcd_hold(hba, false);
d44a5f98
DR
1889 if (!desc_buf) {
1890 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1891 __func__, opcode);
1892 err = -EINVAL;
1893 goto out;
1894 }
1895
1896 if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1897 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1898 __func__, *buf_len);
1899 err = -EINVAL;
1900 goto out;
1901 }
1902
1903 mutex_lock(&hba->dev_cmd.lock);
1904 ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1905 selector);
1906 hba->dev_cmd.query.descriptor = desc_buf;
ea2aab24 1907 request->upiu_req.length = cpu_to_be16(*buf_len);
d44a5f98
DR
1908
1909 switch (opcode) {
1910 case UPIU_QUERY_OPCODE_WRITE_DESC:
1911 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1912 break;
1913 case UPIU_QUERY_OPCODE_READ_DESC:
1914 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1915 break;
1916 default:
1917 dev_err(hba->dev,
1918 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1919 __func__, opcode);
1920 err = -EINVAL;
1921 goto out_unlock;
1922 }
1923
1924 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1925
1926 if (err) {
1927 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1928 __func__, opcode, idn, err);
1929 goto out_unlock;
1930 }
1931
1932 hba->dev_cmd.query.descriptor = NULL;
ea2aab24 1933 *buf_len = be16_to_cpu(response->upiu_res.length);
d44a5f98
DR
1934
1935out_unlock:
1936 mutex_unlock(&hba->dev_cmd.lock);
1937out:
1ab27c9c 1938 ufshcd_release(hba);
d44a5f98
DR
1939 return err;
1940}
1941
a70e91b8
YG
1942/**
1943 * ufshcd_query_descriptor_retry - API function for sending descriptor
1944 * requests
1945 * hba: per-adapter instance
1946 * opcode: attribute opcode
1947 * idn: attribute idn to access
1948 * index: index field
1949 * selector: selector field
1950 * desc_buf: the buffer that contains the descriptor
1951 * buf_len: length parameter passed to the device
1952 *
1953 * Returns 0 for success, non-zero in case of failure.
1954 * The buf_len parameter will contain, on return, the length parameter
1955 * received on the response.
1956 */
1957int ufshcd_query_descriptor_retry(struct ufs_hba *hba,
1958 enum query_opcode opcode, enum desc_idn idn, u8 index,
1959 u8 selector, u8 *desc_buf, int *buf_len)
1960{
1961 int err;
1962 int retries;
1963
1964 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1965 err = __ufshcd_query_descriptor(hba, opcode, idn, index,
1966 selector, desc_buf, buf_len);
1967 if (!err || err == -EINVAL)
1968 break;
1969 }
1970
1971 return err;
1972}
1973EXPORT_SYMBOL(ufshcd_query_descriptor_retry);
1974
da461cec
SJ
1975/**
1976 * ufshcd_read_desc_param - read the specified descriptor parameter
1977 * @hba: Pointer to adapter instance
1978 * @desc_id: descriptor idn value
1979 * @desc_index: descriptor index
1980 * @param_offset: offset of the parameter to read
1981 * @param_read_buf: pointer to buffer where parameter would be read
1982 * @param_size: sizeof(param_read_buf)
1983 *
1984 * Return 0 in case of success, non-zero otherwise
1985 */
1986static int ufshcd_read_desc_param(struct ufs_hba *hba,
1987 enum desc_idn desc_id,
1988 int desc_index,
1989 u32 param_offset,
1990 u8 *param_read_buf,
1991 u32 param_size)
1992{
1993 int ret;
1994 u8 *desc_buf;
1995 u32 buff_len;
1996 bool is_kmalloc = true;
1997
1998 /* safety checks */
1999 if (desc_id >= QUERY_DESC_IDN_MAX)
2000 return -EINVAL;
2001
2002 buff_len = ufs_query_desc_max_size[desc_id];
2003 if ((param_offset + param_size) > buff_len)
2004 return -EINVAL;
2005
2006 if (!param_offset && (param_size == buff_len)) {
2007 /* memory space already available to hold full descriptor */
2008 desc_buf = param_read_buf;
2009 is_kmalloc = false;
2010 } else {
2011 /* allocate memory to hold full descriptor */
2012 desc_buf = kmalloc(buff_len, GFP_KERNEL);
2013 if (!desc_buf)
2014 return -ENOMEM;
2015 }
2016
a70e91b8
YG
2017 ret = ufshcd_query_descriptor_retry(hba, UPIU_QUERY_OPCODE_READ_DESC,
2018 desc_id, desc_index, 0, desc_buf,
2019 &buff_len);
da461cec
SJ
2020
2021 if (ret || (buff_len < ufs_query_desc_max_size[desc_id]) ||
2022 (desc_buf[QUERY_DESC_LENGTH_OFFSET] !=
2023 ufs_query_desc_max_size[desc_id])
2024 || (desc_buf[QUERY_DESC_DESC_TYPE_OFFSET] != desc_id)) {
2025 dev_err(hba->dev, "%s: Failed reading descriptor. desc_id %d param_offset %d buff_len %d ret %d",
2026 __func__, desc_id, param_offset, buff_len, ret);
2027 if (!ret)
2028 ret = -EINVAL;
2029
2030 goto out;
2031 }
2032
2033 if (is_kmalloc)
2034 memcpy(param_read_buf, &desc_buf[param_offset], param_size);
2035out:
2036 if (is_kmalloc)
2037 kfree(desc_buf);
2038 return ret;
2039}
2040
2041static inline int ufshcd_read_desc(struct ufs_hba *hba,
2042 enum desc_idn desc_id,
2043 int desc_index,
2044 u8 *buf,
2045 u32 size)
2046{
2047 return ufshcd_read_desc_param(hba, desc_id, desc_index, 0, buf, size);
2048}
2049
2050static inline int ufshcd_read_power_desc(struct ufs_hba *hba,
2051 u8 *buf,
2052 u32 size)
2053{
2054 return ufshcd_read_desc(hba, QUERY_DESC_IDN_POWER, 0, buf, size);
2055}
2056
b573d484
YG
2057int ufshcd_read_device_desc(struct ufs_hba *hba, u8 *buf, u32 size)
2058{
2059 return ufshcd_read_desc(hba, QUERY_DESC_IDN_DEVICE, 0, buf, size);
2060}
2061EXPORT_SYMBOL(ufshcd_read_device_desc);
2062
2063/**
2064 * ufshcd_read_string_desc - read string descriptor
2065 * @hba: pointer to adapter instance
2066 * @desc_index: descriptor index
2067 * @buf: pointer to buffer where descriptor would be read
2068 * @size: size of buf
2069 * @ascii: if true convert from unicode to ascii characters
2070 *
2071 * Return 0 in case of success, non-zero otherwise
2072 */
2073int ufshcd_read_string_desc(struct ufs_hba *hba, int desc_index, u8 *buf,
2074 u32 size, bool ascii)
2075{
2076 int err = 0;
2077
2078 err = ufshcd_read_desc(hba,
2079 QUERY_DESC_IDN_STRING, desc_index, buf, size);
2080
2081 if (err) {
2082 dev_err(hba->dev, "%s: reading String Desc failed after %d retries. err = %d\n",
2083 __func__, QUERY_REQ_RETRIES, err);
2084 goto out;
2085 }
2086
2087 if (ascii) {
2088 int desc_len;
2089 int ascii_len;
2090 int i;
2091 char *buff_ascii;
2092
2093 desc_len = buf[0];
2094 /* remove header and divide by 2 to move from UTF16 to UTF8 */
2095 ascii_len = (desc_len - QUERY_DESC_HDR_SIZE) / 2 + 1;
2096 if (size < ascii_len + QUERY_DESC_HDR_SIZE) {
2097 dev_err(hba->dev, "%s: buffer allocated size is too small\n",
2098 __func__);
2099 err = -ENOMEM;
2100 goto out;
2101 }
2102
2103 buff_ascii = kmalloc(ascii_len, GFP_KERNEL);
2104 if (!buff_ascii) {
2105 err = -ENOMEM;
2106 goto out_free_buff;
2107 }
2108
2109 /*
2110 * the descriptor contains string in UTF16 format
2111 * we need to convert to utf-8 so it can be displayed
2112 */
2113 utf16s_to_utf8s((wchar_t *)&buf[QUERY_DESC_HDR_SIZE],
2114 desc_len - QUERY_DESC_HDR_SIZE,
2115 UTF16_BIG_ENDIAN, buff_ascii, ascii_len);
2116
2117 /* replace non-printable or non-ASCII characters with spaces */
2118 for (i = 0; i < ascii_len; i++)
2119 ufshcd_remove_non_printable(&buff_ascii[i]);
2120
2121 memset(buf + QUERY_DESC_HDR_SIZE, 0,
2122 size - QUERY_DESC_HDR_SIZE);
2123 memcpy(buf + QUERY_DESC_HDR_SIZE, buff_ascii, ascii_len);
2124 buf[QUERY_DESC_LENGTH_OFFSET] = ascii_len + QUERY_DESC_HDR_SIZE;
2125out_free_buff:
2126 kfree(buff_ascii);
2127 }
2128out:
2129 return err;
2130}
2131EXPORT_SYMBOL(ufshcd_read_string_desc);
2132
da461cec
SJ
2133/**
2134 * ufshcd_read_unit_desc_param - read the specified unit descriptor parameter
2135 * @hba: Pointer to adapter instance
2136 * @lun: lun id
2137 * @param_offset: offset of the parameter to read
2138 * @param_read_buf: pointer to buffer where parameter would be read
2139 * @param_size: sizeof(param_read_buf)
2140 *
2141 * Return 0 in case of success, non-zero otherwise
2142 */
2143static inline int ufshcd_read_unit_desc_param(struct ufs_hba *hba,
2144 int lun,
2145 enum unit_desc_param param_offset,
2146 u8 *param_read_buf,
2147 u32 param_size)
2148{
2149 /*
2150 * Unit descriptors are only available for general purpose LUs (LUN id
2151 * from 0 to 7) and RPMB Well known LU.
2152 */
0ce147d4 2153 if (lun != UFS_UPIU_RPMB_WLUN && (lun >= UFS_UPIU_MAX_GENERAL_LUN))
da461cec
SJ
2154 return -EOPNOTSUPP;
2155
2156 return ufshcd_read_desc_param(hba, QUERY_DESC_IDN_UNIT, lun,
2157 param_offset, param_read_buf, param_size);
2158}
2159
7a3e97b0
SY
2160/**
2161 * ufshcd_memory_alloc - allocate memory for host memory space data structures
2162 * @hba: per adapter instance
2163 *
2164 * 1. Allocate DMA memory for Command Descriptor array
2165 * Each command descriptor consist of Command UPIU, Response UPIU and PRDT
2166 * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
2167 * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
2168 * (UTMRDL)
2169 * 4. Allocate memory for local reference block(lrb).
2170 *
2171 * Returns 0 for success, non-zero in case of failure
2172 */
2173static int ufshcd_memory_alloc(struct ufs_hba *hba)
2174{
2175 size_t utmrdl_size, utrdl_size, ucdl_size;
2176
2177 /* Allocate memory for UTP command descriptors */
2178 ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
2953f850
SJ
2179 hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
2180 ucdl_size,
2181 &hba->ucdl_dma_addr,
2182 GFP_KERNEL);
7a3e97b0
SY
2183
2184 /*
2185 * UFSHCI requires UTP command descriptor to be 128 byte aligned.
2186 * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
2187 * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
2188 * be aligned to 128 bytes as well
2189 */
2190 if (!hba->ucdl_base_addr ||
2191 WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
3b1d0580 2192 dev_err(hba->dev,
7a3e97b0
SY
2193 "Command Descriptor Memory allocation failed\n");
2194 goto out;
2195 }
2196
2197 /*
2198 * Allocate memory for UTP Transfer descriptors
2199 * UFSHCI requires 1024 byte alignment of UTRD
2200 */
2201 utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
2953f850
SJ
2202 hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
2203 utrdl_size,
2204 &hba->utrdl_dma_addr,
2205 GFP_KERNEL);
7a3e97b0
SY
2206 if (!hba->utrdl_base_addr ||
2207 WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
3b1d0580 2208 dev_err(hba->dev,
7a3e97b0
SY
2209 "Transfer Descriptor Memory allocation failed\n");
2210 goto out;
2211 }
2212
2213 /*
2214 * Allocate memory for UTP Task Management descriptors
2215 * UFSHCI requires 1024 byte alignment of UTMRD
2216 */
2217 utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
2953f850
SJ
2218 hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
2219 utmrdl_size,
2220 &hba->utmrdl_dma_addr,
2221 GFP_KERNEL);
7a3e97b0
SY
2222 if (!hba->utmrdl_base_addr ||
2223 WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
3b1d0580 2224 dev_err(hba->dev,
7a3e97b0
SY
2225 "Task Management Descriptor Memory allocation failed\n");
2226 goto out;
2227 }
2228
2229 /* Allocate memory for local reference block */
2953f850
SJ
2230 hba->lrb = devm_kzalloc(hba->dev,
2231 hba->nutrs * sizeof(struct ufshcd_lrb),
2232 GFP_KERNEL);
7a3e97b0 2233 if (!hba->lrb) {
3b1d0580 2234 dev_err(hba->dev, "LRB Memory allocation failed\n");
7a3e97b0
SY
2235 goto out;
2236 }
2237 return 0;
2238out:
7a3e97b0
SY
2239 return -ENOMEM;
2240}
2241
2242/**
2243 * ufshcd_host_memory_configure - configure local reference block with
2244 * memory offsets
2245 * @hba: per adapter instance
2246 *
2247 * Configure Host memory space
2248 * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
2249 * address.
2250 * 2. Update each UTRD with Response UPIU offset, Response UPIU length
2251 * and PRDT offset.
2252 * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
2253 * into local reference block.
2254 */
2255static void ufshcd_host_memory_configure(struct ufs_hba *hba)
2256{
2257 struct utp_transfer_cmd_desc *cmd_descp;
2258 struct utp_transfer_req_desc *utrdlp;
2259 dma_addr_t cmd_desc_dma_addr;
2260 dma_addr_t cmd_desc_element_addr;
2261 u16 response_offset;
2262 u16 prdt_offset;
2263 int cmd_desc_size;
2264 int i;
2265
2266 utrdlp = hba->utrdl_base_addr;
2267 cmd_descp = hba->ucdl_base_addr;
2268
2269 response_offset =
2270 offsetof(struct utp_transfer_cmd_desc, response_upiu);
2271 prdt_offset =
2272 offsetof(struct utp_transfer_cmd_desc, prd_table);
2273
2274 cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
2275 cmd_desc_dma_addr = hba->ucdl_dma_addr;
2276
2277 for (i = 0; i < hba->nutrs; i++) {
2278 /* Configure UTRD with command descriptor base address */
2279 cmd_desc_element_addr =
2280 (cmd_desc_dma_addr + (cmd_desc_size * i));
2281 utrdlp[i].command_desc_base_addr_lo =
2282 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
2283 utrdlp[i].command_desc_base_addr_hi =
2284 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
2285
2286 /* Response upiu and prdt offset should be in double words */
2287 utrdlp[i].response_upiu_offset =
2288 cpu_to_le16((response_offset >> 2));
2289 utrdlp[i].prd_table_offset =
2290 cpu_to_le16((prdt_offset >> 2));
2291 utrdlp[i].response_upiu_length =
3ca316c5 2292 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
7a3e97b0
SY
2293
2294 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
5a0b0cb9
SRT
2295 hba->lrb[i].ucd_req_ptr =
2296 (struct utp_upiu_req *)(cmd_descp + i);
7a3e97b0
SY
2297 hba->lrb[i].ucd_rsp_ptr =
2298 (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
2299 hba->lrb[i].ucd_prdt_ptr =
2300 (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
2301 }
2302}
2303
2304/**
2305 * ufshcd_dme_link_startup - Notify Unipro to perform link startup
2306 * @hba: per adapter instance
2307 *
2308 * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
2309 * in order to initialize the Unipro link startup procedure.
2310 * Once the Unipro links are up, the device connected to the controller
2311 * is detected.
2312 *
2313 * Returns 0 on success, non-zero value on failure
2314 */
2315static int ufshcd_dme_link_startup(struct ufs_hba *hba)
2316{
6ccf44fe
SJ
2317 struct uic_command uic_cmd = {0};
2318 int ret;
7a3e97b0 2319
6ccf44fe 2320 uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
7a3e97b0 2321
6ccf44fe
SJ
2322 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2323 if (ret)
2324 dev_err(hba->dev,
2325 "dme-link-startup: error code %d\n", ret);
2326 return ret;
7a3e97b0
SY
2327}
2328
cad2e03d
YG
2329static inline void ufshcd_add_delay_before_dme_cmd(struct ufs_hba *hba)
2330{
2331 #define MIN_DELAY_BEFORE_DME_CMDS_US 1000
2332 unsigned long min_sleep_time_us;
2333
2334 if (!(hba->quirks & UFSHCD_QUIRK_DELAY_BEFORE_DME_CMDS))
2335 return;
2336
2337 /*
2338 * last_dme_cmd_tstamp will be 0 only for 1st call to
2339 * this function
2340 */
2341 if (unlikely(!ktime_to_us(hba->last_dme_cmd_tstamp))) {
2342 min_sleep_time_us = MIN_DELAY_BEFORE_DME_CMDS_US;
2343 } else {
2344 unsigned long delta =
2345 (unsigned long) ktime_to_us(
2346 ktime_sub(ktime_get(),
2347 hba->last_dme_cmd_tstamp));
2348
2349 if (delta < MIN_DELAY_BEFORE_DME_CMDS_US)
2350 min_sleep_time_us =
2351 MIN_DELAY_BEFORE_DME_CMDS_US - delta;
2352 else
2353 return; /* no more delay required */
2354 }
2355
2356 /* allow sleep for extra 50us if needed */
2357 usleep_range(min_sleep_time_us, min_sleep_time_us + 50);
2358}
2359
12b4fdb4
SJ
2360/**
2361 * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
2362 * @hba: per adapter instance
2363 * @attr_sel: uic command argument1
2364 * @attr_set: attribute set type as uic command argument2
2365 * @mib_val: setting value as uic command argument3
2366 * @peer: indicate whether peer or local
2367 *
2368 * Returns 0 on success, non-zero value on failure
2369 */
2370int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
2371 u8 attr_set, u32 mib_val, u8 peer)
2372{
2373 struct uic_command uic_cmd = {0};
2374 static const char *const action[] = {
2375 "dme-set",
2376 "dme-peer-set"
2377 };
2378 const char *set = action[!!peer];
2379 int ret;
64238fbd 2380 int retries = UFS_UIC_COMMAND_RETRIES;
12b4fdb4
SJ
2381
2382 uic_cmd.command = peer ?
2383 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
2384 uic_cmd.argument1 = attr_sel;
2385 uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
2386 uic_cmd.argument3 = mib_val;
2387
64238fbd
YG
2388 do {
2389 /* for peer attributes we retry upon failure */
2390 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2391 if (ret)
2392 dev_dbg(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
2393 set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
2394 } while (ret && peer && --retries);
2395
2396 if (!retries)
2397 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x failed %d retries\n",
2398 set, UIC_GET_ATTR_ID(attr_sel), mib_val,
2399 retries);
12b4fdb4
SJ
2400
2401 return ret;
2402}
2403EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
2404
2405/**
2406 * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
2407 * @hba: per adapter instance
2408 * @attr_sel: uic command argument1
2409 * @mib_val: the value of the attribute as returned by the UIC command
2410 * @peer: indicate whether peer or local
2411 *
2412 * Returns 0 on success, non-zero value on failure
2413 */
2414int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
2415 u32 *mib_val, u8 peer)
2416{
2417 struct uic_command uic_cmd = {0};
2418 static const char *const action[] = {
2419 "dme-get",
2420 "dme-peer-get"
2421 };
2422 const char *get = action[!!peer];
2423 int ret;
64238fbd 2424 int retries = UFS_UIC_COMMAND_RETRIES;
874237f7
YG
2425 struct ufs_pa_layer_attr orig_pwr_info;
2426 struct ufs_pa_layer_attr temp_pwr_info;
2427 bool pwr_mode_change = false;
2428
2429 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)) {
2430 orig_pwr_info = hba->pwr_info;
2431 temp_pwr_info = orig_pwr_info;
2432
2433 if (orig_pwr_info.pwr_tx == FAST_MODE ||
2434 orig_pwr_info.pwr_rx == FAST_MODE) {
2435 temp_pwr_info.pwr_tx = FASTAUTO_MODE;
2436 temp_pwr_info.pwr_rx = FASTAUTO_MODE;
2437 pwr_mode_change = true;
2438 } else if (orig_pwr_info.pwr_tx == SLOW_MODE ||
2439 orig_pwr_info.pwr_rx == SLOW_MODE) {
2440 temp_pwr_info.pwr_tx = SLOWAUTO_MODE;
2441 temp_pwr_info.pwr_rx = SLOWAUTO_MODE;
2442 pwr_mode_change = true;
2443 }
2444 if (pwr_mode_change) {
2445 ret = ufshcd_change_power_mode(hba, &temp_pwr_info);
2446 if (ret)
2447 goto out;
2448 }
2449 }
12b4fdb4
SJ
2450
2451 uic_cmd.command = peer ?
2452 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
2453 uic_cmd.argument1 = attr_sel;
2454
64238fbd
YG
2455 do {
2456 /* for peer attributes we retry upon failure */
2457 ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
2458 if (ret)
2459 dev_dbg(hba->dev, "%s: attr-id 0x%x error code %d\n",
2460 get, UIC_GET_ATTR_ID(attr_sel), ret);
2461 } while (ret && peer && --retries);
2462
2463 if (!retries)
2464 dev_err(hba->dev, "%s: attr-id 0x%x failed %d retries\n",
2465 get, UIC_GET_ATTR_ID(attr_sel), retries);
12b4fdb4 2466
64238fbd 2467 if (mib_val && !ret)
12b4fdb4 2468 *mib_val = uic_cmd.argument3;
874237f7
YG
2469
2470 if (peer && (hba->quirks & UFSHCD_QUIRK_DME_PEER_ACCESS_AUTO_MODE)
2471 && pwr_mode_change)
2472 ufshcd_change_power_mode(hba, &orig_pwr_info);
12b4fdb4
SJ
2473out:
2474 return ret;
2475}
2476EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
2477
53b3d9c3 2478/**
57d104c1
SJ
2479 * ufshcd_uic_pwr_ctrl - executes UIC commands (which affects the link power
2480 * state) and waits for it to take effect.
2481 *
53b3d9c3 2482 * @hba: per adapter instance
57d104c1
SJ
2483 * @cmd: UIC command to execute
2484 *
2485 * DME operations like DME_SET(PA_PWRMODE), DME_HIBERNATE_ENTER &
2486 * DME_HIBERNATE_EXIT commands take some time to take its effect on both host
2487 * and device UniPro link and hence it's final completion would be indicated by
2488 * dedicated status bits in Interrupt Status register (UPMS, UHES, UHXS) in
2489 * addition to normal UIC command completion Status (UCCS). This function only
2490 * returns after the relevant status bits indicate the completion.
53b3d9c3
SJ
2491 *
2492 * Returns 0 on success, non-zero value on failure
2493 */
57d104c1 2494static int ufshcd_uic_pwr_ctrl(struct ufs_hba *hba, struct uic_command *cmd)
53b3d9c3 2495{
57d104c1 2496 struct completion uic_async_done;
53b3d9c3
SJ
2497 unsigned long flags;
2498 u8 status;
2499 int ret;
d75f7fe4 2500 bool reenable_intr = false;
53b3d9c3 2501
53b3d9c3 2502 mutex_lock(&hba->uic_cmd_mutex);
57d104c1 2503 init_completion(&uic_async_done);
cad2e03d 2504 ufshcd_add_delay_before_dme_cmd(hba);
53b3d9c3
SJ
2505
2506 spin_lock_irqsave(hba->host->host_lock, flags);
57d104c1 2507 hba->uic_async_done = &uic_async_done;
d75f7fe4
YG
2508 if (ufshcd_readl(hba, REG_INTERRUPT_ENABLE) & UIC_COMMAND_COMPL) {
2509 ufshcd_disable_intr(hba, UIC_COMMAND_COMPL);
2510 /*
2511 * Make sure UIC command completion interrupt is disabled before
2512 * issuing UIC command.
2513 */
2514 wmb();
2515 reenable_intr = true;
57d104c1 2516 }
d75f7fe4
YG
2517 ret = __ufshcd_send_uic_cmd(hba, cmd, false);
2518 spin_unlock_irqrestore(hba->host->host_lock, flags);
57d104c1
SJ
2519 if (ret) {
2520 dev_err(hba->dev,
2521 "pwr ctrl cmd 0x%x with mode 0x%x uic error %d\n",
2522 cmd->command, cmd->argument3, ret);
53b3d9c3
SJ
2523 goto out;
2524 }
2525
57d104c1 2526 if (!wait_for_completion_timeout(hba->uic_async_done,
53b3d9c3
SJ
2527 msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
2528 dev_err(hba->dev,
57d104c1
SJ
2529 "pwr ctrl cmd 0x%x with mode 0x%x completion timeout\n",
2530 cmd->command, cmd->argument3);
53b3d9c3
SJ
2531 ret = -ETIMEDOUT;
2532 goto out;
2533 }
2534
2535 status = ufshcd_get_upmcrs(hba);
2536 if (status != PWR_LOCAL) {
2537 dev_err(hba->dev,
57d104c1
SJ
2538 "pwr ctrl cmd 0x%0x failed, host umpcrs:0x%x\n",
2539 cmd->command, status);
53b3d9c3
SJ
2540 ret = (status != PWR_OK) ? status : -1;
2541 }
2542out:
2543 spin_lock_irqsave(hba->host->host_lock, flags);
d75f7fe4 2544 hba->active_uic_cmd = NULL;
57d104c1 2545 hba->uic_async_done = NULL;
d75f7fe4
YG
2546 if (reenable_intr)
2547 ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
53b3d9c3
SJ
2548 spin_unlock_irqrestore(hba->host->host_lock, flags);
2549 mutex_unlock(&hba->uic_cmd_mutex);
1ab27c9c 2550
53b3d9c3
SJ
2551 return ret;
2552}
2553
57d104c1
SJ
2554/**
2555 * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
2556 * using DME_SET primitives.
2557 * @hba: per adapter instance
2558 * @mode: powr mode value
2559 *
2560 * Returns 0 on success, non-zero value on failure
2561 */
2562static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
2563{
2564 struct uic_command uic_cmd = {0};
1ab27c9c 2565 int ret;
57d104c1 2566
c3a2f9ee
YG
2567 if (hba->quirks & UFSHCD_QUIRK_BROKEN_PA_RXHSUNTERMCAP) {
2568 ret = ufshcd_dme_set(hba,
2569 UIC_ARG_MIB_SEL(PA_RXHSUNTERMCAP, 0), 1);
2570 if (ret) {
2571 dev_err(hba->dev, "%s: failed to enable PA_RXHSUNTERMCAP ret %d\n",
2572 __func__, ret);
2573 goto out;
2574 }
2575 }
2576
57d104c1
SJ
2577 uic_cmd.command = UIC_CMD_DME_SET;
2578 uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
2579 uic_cmd.argument3 = mode;
1ab27c9c
ST
2580 ufshcd_hold(hba, false);
2581 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2582 ufshcd_release(hba);
57d104c1 2583
c3a2f9ee 2584out:
1ab27c9c 2585 return ret;
57d104c1
SJ
2586}
2587
53c12d0e
YG
2588static int ufshcd_link_recovery(struct ufs_hba *hba)
2589{
2590 int ret;
2591 unsigned long flags;
2592
2593 spin_lock_irqsave(hba->host->host_lock, flags);
2594 hba->ufshcd_state = UFSHCD_STATE_RESET;
2595 ufshcd_set_eh_in_progress(hba);
2596 spin_unlock_irqrestore(hba->host->host_lock, flags);
2597
2598 ret = ufshcd_host_reset_and_restore(hba);
2599
2600 spin_lock_irqsave(hba->host->host_lock, flags);
2601 if (ret)
2602 hba->ufshcd_state = UFSHCD_STATE_ERROR;
2603 ufshcd_clear_eh_in_progress(hba);
2604 spin_unlock_irqrestore(hba->host->host_lock, flags);
2605
2606 if (ret)
2607 dev_err(hba->dev, "%s: link recovery failed, err %d",
2608 __func__, ret);
2609
2610 return ret;
2611}
2612
87d0b4a6 2613static int __ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
57d104c1 2614{
87d0b4a6 2615 int ret;
57d104c1
SJ
2616 struct uic_command uic_cmd = {0};
2617
2618 uic_cmd.command = UIC_CMD_DME_HIBER_ENTER;
87d0b4a6
YG
2619 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2620
53c12d0e 2621 if (ret) {
87d0b4a6
YG
2622 dev_err(hba->dev, "%s: hibern8 enter failed. ret = %d\n",
2623 __func__, ret);
2624
53c12d0e
YG
2625 /*
2626 * If link recovery fails then return error so that caller
2627 * don't retry the hibern8 enter again.
2628 */
2629 if (ufshcd_link_recovery(hba))
2630 ret = -ENOLINK;
2631 }
2632
87d0b4a6
YG
2633 return ret;
2634}
2635
2636static int ufshcd_uic_hibern8_enter(struct ufs_hba *hba)
2637{
2638 int ret = 0, retries;
57d104c1 2639
87d0b4a6
YG
2640 for (retries = UIC_HIBERN8_ENTER_RETRIES; retries > 0; retries--) {
2641 ret = __ufshcd_uic_hibern8_enter(hba);
2642 if (!ret || ret == -ENOLINK)
2643 goto out;
2644 }
2645out:
2646 return ret;
57d104c1
SJ
2647}
2648
2649static int ufshcd_uic_hibern8_exit(struct ufs_hba *hba)
2650{
2651 struct uic_command uic_cmd = {0};
2652 int ret;
2653
2654 uic_cmd.command = UIC_CMD_DME_HIBER_EXIT;
2655 ret = ufshcd_uic_pwr_ctrl(hba, &uic_cmd);
2656 if (ret) {
53c12d0e
YG
2657 dev_err(hba->dev, "%s: hibern8 exit failed. ret = %d\n",
2658 __func__, ret);
2659 ret = ufshcd_link_recovery(hba);
57d104c1
SJ
2660 }
2661
2662 return ret;
2663}
2664
5064636c
YG
2665 /**
2666 * ufshcd_init_pwr_info - setting the POR (power on reset)
2667 * values in hba power info
2668 * @hba: per-adapter instance
2669 */
2670static void ufshcd_init_pwr_info(struct ufs_hba *hba)
2671{
2672 hba->pwr_info.gear_rx = UFS_PWM_G1;
2673 hba->pwr_info.gear_tx = UFS_PWM_G1;
2674 hba->pwr_info.lane_rx = 1;
2675 hba->pwr_info.lane_tx = 1;
2676 hba->pwr_info.pwr_rx = SLOWAUTO_MODE;
2677 hba->pwr_info.pwr_tx = SLOWAUTO_MODE;
2678 hba->pwr_info.hs_rate = 0;
2679}
2680
d3e89bac 2681/**
7eb584db
DR
2682 * ufshcd_get_max_pwr_mode - reads the max power mode negotiated with device
2683 * @hba: per-adapter instance
d3e89bac 2684 */
7eb584db 2685static int ufshcd_get_max_pwr_mode(struct ufs_hba *hba)
d3e89bac 2686{
7eb584db
DR
2687 struct ufs_pa_layer_attr *pwr_info = &hba->max_pwr_info.info;
2688
2689 if (hba->max_pwr_info.is_valid)
2690 return 0;
2691
2692 pwr_info->pwr_tx = FASTAUTO_MODE;
2693 pwr_info->pwr_rx = FASTAUTO_MODE;
2694 pwr_info->hs_rate = PA_HS_MODE_B;
d3e89bac
SJ
2695
2696 /* Get the connected lane count */
7eb584db
DR
2697 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES),
2698 &pwr_info->lane_rx);
2699 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
2700 &pwr_info->lane_tx);
2701
2702 if (!pwr_info->lane_rx || !pwr_info->lane_tx) {
2703 dev_err(hba->dev, "%s: invalid connected lanes value. rx=%d, tx=%d\n",
2704 __func__,
2705 pwr_info->lane_rx,
2706 pwr_info->lane_tx);
2707 return -EINVAL;
2708 }
d3e89bac
SJ
2709
2710 /*
2711 * First, get the maximum gears of HS speed.
2712 * If a zero value, it means there is no HSGEAR capability.
2713 * Then, get the maximum gears of PWM speed.
2714 */
7eb584db
DR
2715 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &pwr_info->gear_rx);
2716 if (!pwr_info->gear_rx) {
2717 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
2718 &pwr_info->gear_rx);
2719 if (!pwr_info->gear_rx) {
2720 dev_err(hba->dev, "%s: invalid max pwm rx gear read = %d\n",
2721 __func__, pwr_info->gear_rx);
2722 return -EINVAL;
2723 }
2724 pwr_info->pwr_rx = SLOWAUTO_MODE;
d3e89bac
SJ
2725 }
2726
7eb584db
DR
2727 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR),
2728 &pwr_info->gear_tx);
2729 if (!pwr_info->gear_tx) {
d3e89bac 2730 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
7eb584db
DR
2731 &pwr_info->gear_tx);
2732 if (!pwr_info->gear_tx) {
2733 dev_err(hba->dev, "%s: invalid max pwm tx gear read = %d\n",
2734 __func__, pwr_info->gear_tx);
2735 return -EINVAL;
2736 }
2737 pwr_info->pwr_tx = SLOWAUTO_MODE;
2738 }
2739
2740 hba->max_pwr_info.is_valid = true;
2741 return 0;
2742}
2743
2744static int ufshcd_change_power_mode(struct ufs_hba *hba,
2745 struct ufs_pa_layer_attr *pwr_mode)
2746{
2747 int ret;
2748
2749 /* if already configured to the requested pwr_mode */
2750 if (pwr_mode->gear_rx == hba->pwr_info.gear_rx &&
2751 pwr_mode->gear_tx == hba->pwr_info.gear_tx &&
2752 pwr_mode->lane_rx == hba->pwr_info.lane_rx &&
2753 pwr_mode->lane_tx == hba->pwr_info.lane_tx &&
2754 pwr_mode->pwr_rx == hba->pwr_info.pwr_rx &&
2755 pwr_mode->pwr_tx == hba->pwr_info.pwr_tx &&
2756 pwr_mode->hs_rate == hba->pwr_info.hs_rate) {
2757 dev_dbg(hba->dev, "%s: power already configured\n", __func__);
2758 return 0;
d3e89bac
SJ
2759 }
2760
2761 /*
2762 * Configure attributes for power mode change with below.
2763 * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
2764 * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
2765 * - PA_HSSERIES
2766 */
7eb584db
DR
2767 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), pwr_mode->gear_rx);
2768 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES),
2769 pwr_mode->lane_rx);
2770 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2771 pwr_mode->pwr_rx == FAST_MODE)
d3e89bac 2772 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
7eb584db
DR
2773 else
2774 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), FALSE);
d3e89bac 2775
7eb584db
DR
2776 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), pwr_mode->gear_tx);
2777 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES),
2778 pwr_mode->lane_tx);
2779 if (pwr_mode->pwr_tx == FASTAUTO_MODE ||
2780 pwr_mode->pwr_tx == FAST_MODE)
d3e89bac 2781 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
7eb584db
DR
2782 else
2783 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), FALSE);
d3e89bac 2784
7eb584db
DR
2785 if (pwr_mode->pwr_rx == FASTAUTO_MODE ||
2786 pwr_mode->pwr_tx == FASTAUTO_MODE ||
2787 pwr_mode->pwr_rx == FAST_MODE ||
2788 pwr_mode->pwr_tx == FAST_MODE)
2789 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES),
2790 pwr_mode->hs_rate);
d3e89bac 2791
7eb584db
DR
2792 ret = ufshcd_uic_change_pwr_mode(hba, pwr_mode->pwr_rx << 4
2793 | pwr_mode->pwr_tx);
2794
2795 if (ret) {
d3e89bac 2796 dev_err(hba->dev,
7eb584db
DR
2797 "%s: power mode change failed %d\n", __func__, ret);
2798 } else {
0263bcd0
YG
2799 ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, NULL,
2800 pwr_mode);
7eb584db
DR
2801
2802 memcpy(&hba->pwr_info, pwr_mode,
2803 sizeof(struct ufs_pa_layer_attr));
2804 }
2805
2806 return ret;
2807}
2808
2809/**
2810 * ufshcd_config_pwr_mode - configure a new power mode
2811 * @hba: per-adapter instance
2812 * @desired_pwr_mode: desired power configuration
2813 */
2814static int ufshcd_config_pwr_mode(struct ufs_hba *hba,
2815 struct ufs_pa_layer_attr *desired_pwr_mode)
2816{
2817 struct ufs_pa_layer_attr final_params = { 0 };
2818 int ret;
2819
0263bcd0
YG
2820 ret = ufshcd_vops_pwr_change_notify(hba, PRE_CHANGE,
2821 desired_pwr_mode, &final_params);
2822
2823 if (ret)
7eb584db
DR
2824 memcpy(&final_params, desired_pwr_mode, sizeof(final_params));
2825
2826 ret = ufshcd_change_power_mode(hba, &final_params);
d3e89bac
SJ
2827
2828 return ret;
2829}
2830
68078d5c
DR
2831/**
2832 * ufshcd_complete_dev_init() - checks device readiness
2833 * hba: per-adapter instance
2834 *
2835 * Set fDeviceInit flag and poll until device toggles it.
2836 */
2837static int ufshcd_complete_dev_init(struct ufs_hba *hba)
2838{
dc3c8d3a
YG
2839 int i;
2840 int err;
68078d5c
DR
2841 bool flag_res = 1;
2842
dc3c8d3a
YG
2843 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2844 QUERY_FLAG_IDN_FDEVICEINIT, NULL);
68078d5c
DR
2845 if (err) {
2846 dev_err(hba->dev,
2847 "%s setting fDeviceInit flag failed with error %d\n",
2848 __func__, err);
2849 goto out;
2850 }
2851
dc3c8d3a
YG
2852 /* poll for max. 1000 iterations for fDeviceInit flag to clear */
2853 for (i = 0; i < 1000 && !err && flag_res; i++)
2854 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
2855 QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
2856
68078d5c
DR
2857 if (err)
2858 dev_err(hba->dev,
2859 "%s reading fDeviceInit flag failed with error %d\n",
2860 __func__, err);
2861 else if (flag_res)
2862 dev_err(hba->dev,
2863 "%s fDeviceInit was not cleared by the device\n",
2864 __func__);
2865
2866out:
2867 return err;
2868}
2869
7a3e97b0
SY
2870/**
2871 * ufshcd_make_hba_operational - Make UFS controller operational
2872 * @hba: per adapter instance
2873 *
2874 * To bring UFS host controller to operational state,
5c0c28a8
SRT
2875 * 1. Enable required interrupts
2876 * 2. Configure interrupt aggregation
897efe62 2877 * 3. Program UTRL and UTMRL base address
5c0c28a8 2878 * 4. Configure run-stop-registers
7a3e97b0
SY
2879 *
2880 * Returns 0 on success, non-zero value on failure
2881 */
2882static int ufshcd_make_hba_operational(struct ufs_hba *hba)
2883{
2884 int err = 0;
2885 u32 reg;
2886
6ccf44fe
SJ
2887 /* Enable required interrupts */
2888 ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
2889
2890 /* Configure interrupt aggregation */
b852190e
YG
2891 if (ufshcd_is_intr_aggr_allowed(hba))
2892 ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
2893 else
2894 ufshcd_disable_intr_aggr(hba);
6ccf44fe
SJ
2895
2896 /* Configure UTRL and UTMRL base address registers */
2897 ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
2898 REG_UTP_TRANSFER_REQ_LIST_BASE_L);
2899 ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
2900 REG_UTP_TRANSFER_REQ_LIST_BASE_H);
2901 ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
2902 REG_UTP_TASK_REQ_LIST_BASE_L);
2903 ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
2904 REG_UTP_TASK_REQ_LIST_BASE_H);
2905
897efe62
YG
2906 /*
2907 * Make sure base address and interrupt setup are updated before
2908 * enabling the run/stop registers below.
2909 */
2910 wmb();
2911
7a3e97b0
SY
2912 /*
2913 * UCRDY, UTMRLDY and UTRLRDY bits must be 1
7a3e97b0 2914 */
5c0c28a8 2915 reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
7a3e97b0
SY
2916 if (!(ufshcd_get_lists_status(reg))) {
2917 ufshcd_enable_run_stop_reg(hba);
2918 } else {
3b1d0580 2919 dev_err(hba->dev,
7a3e97b0
SY
2920 "Host controller not ready to process requests");
2921 err = -EIO;
2922 goto out;
2923 }
2924
7a3e97b0
SY
2925out:
2926 return err;
2927}
2928
596585a2
YG
2929/**
2930 * ufshcd_hba_stop - Send controller to reset state
2931 * @hba: per adapter instance
2932 * @can_sleep: perform sleep or just spin
2933 */
2934static inline void ufshcd_hba_stop(struct ufs_hba *hba, bool can_sleep)
2935{
2936 int err;
2937
2938 ufshcd_writel(hba, CONTROLLER_DISABLE, REG_CONTROLLER_ENABLE);
2939 err = ufshcd_wait_for_register(hba, REG_CONTROLLER_ENABLE,
2940 CONTROLLER_ENABLE, CONTROLLER_DISABLE,
2941 10, 1, can_sleep);
2942 if (err)
2943 dev_err(hba->dev, "%s: Controller disable failed\n", __func__);
2944}
2945
7a3e97b0
SY
2946/**
2947 * ufshcd_hba_enable - initialize the controller
2948 * @hba: per adapter instance
2949 *
2950 * The controller resets itself and controller firmware initialization
2951 * sequence kicks off. When controller is ready it will set
2952 * the Host Controller Enable bit to 1.
2953 *
2954 * Returns 0 on success, non-zero value on failure
2955 */
2956static int ufshcd_hba_enable(struct ufs_hba *hba)
2957{
2958 int retry;
2959
2960 /*
2961 * msleep of 1 and 5 used in this function might result in msleep(20),
2962 * but it was necessary to send the UFS FPGA to reset mode during
2963 * development and testing of this driver. msleep can be changed to
2964 * mdelay and retry count can be reduced based on the controller.
2965 */
596585a2 2966 if (!ufshcd_is_hba_active(hba))
7a3e97b0 2967 /* change controller state to "reset state" */
596585a2 2968 ufshcd_hba_stop(hba, true);
7a3e97b0 2969
57d104c1
SJ
2970 /* UniPro link is disabled at this point */
2971 ufshcd_set_link_off(hba);
2972
0263bcd0 2973 ufshcd_vops_hce_enable_notify(hba, PRE_CHANGE);
5c0c28a8 2974
7a3e97b0
SY
2975 /* start controller initialization sequence */
2976 ufshcd_hba_start(hba);
2977
2978 /*
2979 * To initialize a UFS host controller HCE bit must be set to 1.
2980 * During initialization the HCE bit value changes from 1->0->1.
2981 * When the host controller completes initialization sequence
2982 * it sets the value of HCE bit to 1. The same HCE bit is read back
2983 * to check if the controller has completed initialization sequence.
2984 * So without this delay the value HCE = 1, set in the previous
2985 * instruction might be read back.
2986 * This delay can be changed based on the controller.
2987 */
2988 msleep(1);
2989
2990 /* wait for the host controller to complete initialization */
2991 retry = 10;
2992 while (ufshcd_is_hba_active(hba)) {
2993 if (retry) {
2994 retry--;
2995 } else {
3b1d0580 2996 dev_err(hba->dev,
7a3e97b0
SY
2997 "Controller enable failed\n");
2998 return -EIO;
2999 }
3000 msleep(5);
3001 }
5c0c28a8 3002
1d337ec2 3003 /* enable UIC related interrupts */
57d104c1 3004 ufshcd_enable_intr(hba, UFSHCD_UIC_MASK);
1d337ec2 3005
0263bcd0 3006 ufshcd_vops_hce_enable_notify(hba, POST_CHANGE);
5c0c28a8 3007
7a3e97b0
SY
3008 return 0;
3009}
3010
7ca38cf3
YG
3011static int ufshcd_disable_tx_lcc(struct ufs_hba *hba, bool peer)
3012{
3013 int tx_lanes, i, err = 0;
3014
3015 if (!peer)
3016 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3017 &tx_lanes);
3018 else
3019 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES),
3020 &tx_lanes);
3021 for (i = 0; i < tx_lanes; i++) {
3022 if (!peer)
3023 err = ufshcd_dme_set(hba,
3024 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3025 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3026 0);
3027 else
3028 err = ufshcd_dme_peer_set(hba,
3029 UIC_ARG_MIB_SEL(TX_LCC_ENABLE,
3030 UIC_ARG_MPHY_TX_GEN_SEL_INDEX(i)),
3031 0);
3032 if (err) {
3033 dev_err(hba->dev, "%s: TX LCC Disable failed, peer = %d, lane = %d, err = %d",
3034 __func__, peer, i, err);
3035 break;
3036 }
3037 }
3038
3039 return err;
3040}
3041
3042static inline int ufshcd_disable_device_tx_lcc(struct ufs_hba *hba)
3043{
3044 return ufshcd_disable_tx_lcc(hba, true);
3045}
3046
7a3e97b0 3047/**
6ccf44fe 3048 * ufshcd_link_startup - Initialize unipro link startup
7a3e97b0
SY
3049 * @hba: per adapter instance
3050 *
6ccf44fe 3051 * Returns 0 for success, non-zero in case of failure
7a3e97b0 3052 */
6ccf44fe 3053static int ufshcd_link_startup(struct ufs_hba *hba)
7a3e97b0 3054{
6ccf44fe 3055 int ret;
1d337ec2 3056 int retries = DME_LINKSTARTUP_RETRIES;
7a3e97b0 3057
1d337ec2 3058 do {
0263bcd0 3059 ufshcd_vops_link_startup_notify(hba, PRE_CHANGE);
6ccf44fe 3060
1d337ec2 3061 ret = ufshcd_dme_link_startup(hba);
5c0c28a8 3062
1d337ec2
SRT
3063 /* check if device is detected by inter-connect layer */
3064 if (!ret && !ufshcd_is_device_present(hba)) {
3065 dev_err(hba->dev, "%s: Device not present\n", __func__);
3066 ret = -ENXIO;
3067 goto out;
3068 }
6ccf44fe 3069
1d337ec2
SRT
3070 /*
3071 * DME link lost indication is only received when link is up,
3072 * but we can't be sure if the link is up until link startup
3073 * succeeds. So reset the local Uni-Pro and try again.
3074 */
3075 if (ret && ufshcd_hba_enable(hba))
3076 goto out;
3077 } while (ret && retries--);
3078
3079 if (ret)
3080 /* failed to get the link up... retire */
5c0c28a8 3081 goto out;
5c0c28a8 3082
7ca38cf3
YG
3083 if (hba->quirks & UFSHCD_QUIRK_BROKEN_LCC) {
3084 ret = ufshcd_disable_device_tx_lcc(hba);
3085 if (ret)
3086 goto out;
3087 }
3088
5c0c28a8 3089 /* Include any host controller configuration via UIC commands */
0263bcd0
YG
3090 ret = ufshcd_vops_link_startup_notify(hba, POST_CHANGE);
3091 if (ret)
3092 goto out;
7a3e97b0 3093
5c0c28a8 3094 ret = ufshcd_make_hba_operational(hba);
6ccf44fe
SJ
3095out:
3096 if (ret)
3097 dev_err(hba->dev, "link startup failed %d\n", ret);
3098 return ret;
7a3e97b0
SY
3099}
3100
5a0b0cb9
SRT
3101/**
3102 * ufshcd_verify_dev_init() - Verify device initialization
3103 * @hba: per-adapter instance
3104 *
3105 * Send NOP OUT UPIU and wait for NOP IN response to check whether the
3106 * device Transport Protocol (UTP) layer is ready after a reset.
3107 * If the UTP layer at the device side is not initialized, it may
3108 * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
3109 * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
3110 */
3111static int ufshcd_verify_dev_init(struct ufs_hba *hba)
3112{
3113 int err = 0;
3114 int retries;
3115
1ab27c9c 3116 ufshcd_hold(hba, false);
5a0b0cb9
SRT
3117 mutex_lock(&hba->dev_cmd.lock);
3118 for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
3119 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
3120 NOP_OUT_TIMEOUT);
3121
3122 if (!err || err == -ETIMEDOUT)
3123 break;
3124
3125 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
3126 }
3127 mutex_unlock(&hba->dev_cmd.lock);
1ab27c9c 3128 ufshcd_release(hba);
5a0b0cb9
SRT
3129
3130 if (err)
3131 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
3132 return err;
3133}
3134
0ce147d4
SJ
3135/**
3136 * ufshcd_set_queue_depth - set lun queue depth
3137 * @sdev: pointer to SCSI device
3138 *
3139 * Read bLUQueueDepth value and activate scsi tagged command
3140 * queueing. For WLUN, queue depth is set to 1. For best-effort
3141 * cases (bLUQueueDepth = 0) the queue depth is set to a maximum
3142 * value that host can queue.
3143 */
3144static void ufshcd_set_queue_depth(struct scsi_device *sdev)
3145{
3146 int ret = 0;
3147 u8 lun_qdepth;
3148 struct ufs_hba *hba;
3149
3150 hba = shost_priv(sdev->host);
3151
3152 lun_qdepth = hba->nutrs;
3153 ret = ufshcd_read_unit_desc_param(hba,
3154 ufshcd_scsi_to_upiu_lun(sdev->lun),
3155 UNIT_DESC_PARAM_LU_Q_DEPTH,
3156 &lun_qdepth,
3157 sizeof(lun_qdepth));
3158
3159 /* Some WLUN doesn't support unit descriptor */
3160 if (ret == -EOPNOTSUPP)
3161 lun_qdepth = 1;
3162 else if (!lun_qdepth)
3163 /* eventually, we can figure out the real queue depth */
3164 lun_qdepth = hba->nutrs;
3165 else
3166 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
3167
3168 dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
3169 __func__, lun_qdepth);
db5ed4df 3170 scsi_change_queue_depth(sdev, lun_qdepth);
0ce147d4
SJ
3171}
3172
57d104c1
SJ
3173/*
3174 * ufshcd_get_lu_wp - returns the "b_lu_write_protect" from UNIT DESCRIPTOR
3175 * @hba: per-adapter instance
3176 * @lun: UFS device lun id
3177 * @b_lu_write_protect: pointer to buffer to hold the LU's write protect info
3178 *
3179 * Returns 0 in case of success and b_lu_write_protect status would be returned
3180 * @b_lu_write_protect parameter.
3181 * Returns -ENOTSUPP if reading b_lu_write_protect is not supported.
3182 * Returns -EINVAL in case of invalid parameters passed to this function.
3183 */
3184static int ufshcd_get_lu_wp(struct ufs_hba *hba,
3185 u8 lun,
3186 u8 *b_lu_write_protect)
3187{
3188 int ret;
3189
3190 if (!b_lu_write_protect)
3191 ret = -EINVAL;
3192 /*
3193 * According to UFS device spec, RPMB LU can't be write
3194 * protected so skip reading bLUWriteProtect parameter for
3195 * it. For other W-LUs, UNIT DESCRIPTOR is not available.
3196 */
3197 else if (lun >= UFS_UPIU_MAX_GENERAL_LUN)
3198 ret = -ENOTSUPP;
3199 else
3200 ret = ufshcd_read_unit_desc_param(hba,
3201 lun,
3202 UNIT_DESC_PARAM_LU_WR_PROTECT,
3203 b_lu_write_protect,
3204 sizeof(*b_lu_write_protect));
3205 return ret;
3206}
3207
3208/**
3209 * ufshcd_get_lu_power_on_wp_status - get LU's power on write protect
3210 * status
3211 * @hba: per-adapter instance
3212 * @sdev: pointer to SCSI device
3213 *
3214 */
3215static inline void ufshcd_get_lu_power_on_wp_status(struct ufs_hba *hba,
3216 struct scsi_device *sdev)
3217{
3218 if (hba->dev_info.f_power_on_wp_en &&
3219 !hba->dev_info.is_lu_power_on_wp) {
3220 u8 b_lu_write_protect;
3221
3222 if (!ufshcd_get_lu_wp(hba, ufshcd_scsi_to_upiu_lun(sdev->lun),
3223 &b_lu_write_protect) &&
3224 (b_lu_write_protect == UFS_LU_POWER_ON_WP))
3225 hba->dev_info.is_lu_power_on_wp = true;
3226 }
3227}
3228
7a3e97b0
SY
3229/**
3230 * ufshcd_slave_alloc - handle initial SCSI device configurations
3231 * @sdev: pointer to SCSI device
3232 *
3233 * Returns success
3234 */
3235static int ufshcd_slave_alloc(struct scsi_device *sdev)
3236{
3237 struct ufs_hba *hba;
3238
3239 hba = shost_priv(sdev->host);
7a3e97b0
SY
3240
3241 /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
3242 sdev->use_10_for_ms = 1;
7a3e97b0 3243
e8e7f271
SRT
3244 /* allow SCSI layer to restart the device in case of errors */
3245 sdev->allow_restart = 1;
4264fd61 3246
b2a6c522
SRT
3247 /* REPORT SUPPORTED OPERATION CODES is not supported */
3248 sdev->no_report_opcodes = 1;
3249
e8e7f271 3250
0ce147d4 3251 ufshcd_set_queue_depth(sdev);
4264fd61 3252
57d104c1
SJ
3253 ufshcd_get_lu_power_on_wp_status(hba, sdev);
3254
7a3e97b0
SY
3255 return 0;
3256}
3257
4264fd61
SRT
3258/**
3259 * ufshcd_change_queue_depth - change queue depth
3260 * @sdev: pointer to SCSI device
3261 * @depth: required depth to set
4264fd61 3262 *
db5ed4df 3263 * Change queue depth and make sure the max. limits are not crossed.
4264fd61 3264 */
db5ed4df 3265static int ufshcd_change_queue_depth(struct scsi_device *sdev, int depth)
4264fd61
SRT
3266{
3267 struct ufs_hba *hba = shost_priv(sdev->host);
3268
3269 if (depth > hba->nutrs)
3270 depth = hba->nutrs;
db5ed4df 3271 return scsi_change_queue_depth(sdev, depth);
4264fd61
SRT
3272}
3273
eeda4749
AM
3274/**
3275 * ufshcd_slave_configure - adjust SCSI device configurations
3276 * @sdev: pointer to SCSI device
3277 */
3278static int ufshcd_slave_configure(struct scsi_device *sdev)
3279{
3280 struct request_queue *q = sdev->request_queue;
3281
3282 blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
3283 blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
3284
3285 return 0;
3286}
3287
7a3e97b0
SY
3288/**
3289 * ufshcd_slave_destroy - remove SCSI device configurations
3290 * @sdev: pointer to SCSI device
3291 */
3292static void ufshcd_slave_destroy(struct scsi_device *sdev)
3293{
3294 struct ufs_hba *hba;
3295
3296 hba = shost_priv(sdev->host);
0ce147d4 3297 /* Drop the reference as it won't be needed anymore */
7c48bfd0
AM
3298 if (ufshcd_scsi_to_upiu_lun(sdev->lun) == UFS_UPIU_UFS_DEVICE_WLUN) {
3299 unsigned long flags;
3300
3301 spin_lock_irqsave(hba->host->host_lock, flags);
0ce147d4 3302 hba->sdev_ufs_device = NULL;
7c48bfd0
AM
3303 spin_unlock_irqrestore(hba->host->host_lock, flags);
3304 }
7a3e97b0
SY
3305}
3306
3307/**
3308 * ufshcd_task_req_compl - handle task management request completion
3309 * @hba: per adapter instance
3310 * @index: index of the completed request
e2933132 3311 * @resp: task management service response
7a3e97b0 3312 *
e2933132 3313 * Returns non-zero value on error, zero on success
7a3e97b0 3314 */
e2933132 3315static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
7a3e97b0
SY
3316{
3317 struct utp_task_req_desc *task_req_descp;
3318 struct utp_upiu_task_rsp *task_rsp_upiup;
3319 unsigned long flags;
3320 int ocs_value;
3321 int task_result;
3322
3323 spin_lock_irqsave(hba->host->host_lock, flags);
3324
3325 /* Clear completed tasks from outstanding_tasks */
3326 __clear_bit(index, &hba->outstanding_tasks);
3327
3328 task_req_descp = hba->utmrdl_base_addr;
3329 ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
3330
3331 if (ocs_value == OCS_SUCCESS) {
3332 task_rsp_upiup = (struct utp_upiu_task_rsp *)
3333 task_req_descp[index].task_rsp_upiu;
3334 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
3335 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
e2933132
SRT
3336 if (resp)
3337 *resp = (u8)task_result;
7a3e97b0 3338 } else {
e2933132
SRT
3339 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
3340 __func__, ocs_value);
7a3e97b0
SY
3341 }
3342 spin_unlock_irqrestore(hba->host->host_lock, flags);
e2933132
SRT
3343
3344 return ocs_value;
7a3e97b0
SY
3345}
3346
7a3e97b0
SY
3347/**
3348 * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
3349 * @lrb: pointer to local reference block of completed command
3350 * @scsi_status: SCSI command status
3351 *
3352 * Returns value base on SCSI command status
3353 */
3354static inline int
3355ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
3356{
3357 int result = 0;
3358
3359 switch (scsi_status) {
7a3e97b0 3360 case SAM_STAT_CHECK_CONDITION:
1c2623c5
SJ
3361 ufshcd_copy_sense_data(lrbp);
3362 case SAM_STAT_GOOD:
7a3e97b0
SY
3363 result |= DID_OK << 16 |
3364 COMMAND_COMPLETE << 8 |
1c2623c5 3365 scsi_status;
7a3e97b0
SY
3366 break;
3367 case SAM_STAT_TASK_SET_FULL:
1c2623c5 3368 case SAM_STAT_BUSY:
7a3e97b0 3369 case SAM_STAT_TASK_ABORTED:
1c2623c5
SJ
3370 ufshcd_copy_sense_data(lrbp);
3371 result |= scsi_status;
7a3e97b0
SY
3372 break;
3373 default:
3374 result |= DID_ERROR << 16;
3375 break;
3376 } /* end of switch */
3377
3378 return result;
3379}
3380
3381/**
3382 * ufshcd_transfer_rsp_status - Get overall status of the response
3383 * @hba: per adapter instance
3384 * @lrb: pointer to local reference block of completed command
3385 *
3386 * Returns result of the command to notify SCSI midlayer
3387 */
3388static inline int
3389ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
3390{
3391 int result = 0;
3392 int scsi_status;
3393 int ocs;
3394
3395 /* overall command status of utrd */
3396 ocs = ufshcd_get_tr_ocs(lrbp);
3397
3398 switch (ocs) {
3399 case OCS_SUCCESS:
5a0b0cb9 3400 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
7a3e97b0 3401
5a0b0cb9
SRT
3402 switch (result) {
3403 case UPIU_TRANSACTION_RESPONSE:
3404 /*
3405 * get the response UPIU result to extract
3406 * the SCSI command status
3407 */
3408 result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
3409
3410 /*
3411 * get the result based on SCSI status response
3412 * to notify the SCSI midlayer of the command status
3413 */
3414 scsi_status = result & MASK_SCSI_STATUS;
3415 result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
66ec6d59 3416
f05ac2e5
YG
3417 /*
3418 * Currently we are only supporting BKOPs exception
3419 * events hence we can ignore BKOPs exception event
3420 * during power management callbacks. BKOPs exception
3421 * event is not expected to be raised in runtime suspend
3422 * callback as it allows the urgent bkops.
3423 * During system suspend, we are anyway forcefully
3424 * disabling the bkops and if urgent bkops is needed
3425 * it will be enabled on system resume. Long term
3426 * solution could be to abort the system suspend if
3427 * UFS device needs urgent BKOPs.
3428 */
3429 if (!hba->pm_op_in_progress &&
3430 ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
66ec6d59 3431 schedule_work(&hba->eeh_work);
5a0b0cb9
SRT
3432 break;
3433 case UPIU_TRANSACTION_REJECT_UPIU:
3434 /* TODO: handle Reject UPIU Response */
3435 result = DID_ERROR << 16;
3b1d0580 3436 dev_err(hba->dev,
5a0b0cb9
SRT
3437 "Reject UPIU not fully implemented\n");
3438 break;
3439 default:
3440 result = DID_ERROR << 16;
3441 dev_err(hba->dev,
3442 "Unexpected request response code = %x\n",
3443 result);
7a3e97b0
SY
3444 break;
3445 }
7a3e97b0
SY
3446 break;
3447 case OCS_ABORTED:
3448 result |= DID_ABORT << 16;
3449 break;
e8e7f271
SRT
3450 case OCS_INVALID_COMMAND_STATUS:
3451 result |= DID_REQUEUE << 16;
3452 break;
7a3e97b0
SY
3453 case OCS_INVALID_CMD_TABLE_ATTR:
3454 case OCS_INVALID_PRDT_ATTR:
3455 case OCS_MISMATCH_DATA_BUF_SIZE:
3456 case OCS_MISMATCH_RESP_UPIU_SIZE:
3457 case OCS_PEER_COMM_FAILURE:
3458 case OCS_FATAL_ERROR:
3459 default:
3460 result |= DID_ERROR << 16;
3b1d0580 3461 dev_err(hba->dev,
7a3e97b0
SY
3462 "OCS error from controller = %x\n", ocs);
3463 break;
3464 } /* end of switch */
3465
3466 return result;
3467}
3468
6ccf44fe
SJ
3469/**
3470 * ufshcd_uic_cmd_compl - handle completion of uic command
3471 * @hba: per adapter instance
53b3d9c3 3472 * @intr_status: interrupt status generated by the controller
6ccf44fe 3473 */
53b3d9c3 3474static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
6ccf44fe 3475{
53b3d9c3 3476 if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
6ccf44fe
SJ
3477 hba->active_uic_cmd->argument2 |=
3478 ufshcd_get_uic_cmd_result(hba);
12b4fdb4
SJ
3479 hba->active_uic_cmd->argument3 =
3480 ufshcd_get_dme_attr_val(hba);
6ccf44fe
SJ
3481 complete(&hba->active_uic_cmd->done);
3482 }
53b3d9c3 3483
57d104c1
SJ
3484 if ((intr_status & UFSHCD_UIC_PWR_MASK) && hba->uic_async_done)
3485 complete(hba->uic_async_done);
6ccf44fe
SJ
3486}
3487
7a3e97b0 3488/**
9a47ec7c 3489 * __ufshcd_transfer_req_compl - handle SCSI and query command completion
7a3e97b0 3490 * @hba: per adapter instance
9a47ec7c 3491 * @completed_reqs: requests to complete
7a3e97b0 3492 */
9a47ec7c
YG
3493static void __ufshcd_transfer_req_compl(struct ufs_hba *hba,
3494 unsigned long completed_reqs)
7a3e97b0 3495{
5a0b0cb9
SRT
3496 struct ufshcd_lrb *lrbp;
3497 struct scsi_cmnd *cmd;
7a3e97b0
SY
3498 int result;
3499 int index;
e9d501b1 3500
e9d501b1
DR
3501 for_each_set_bit(index, &completed_reqs, hba->nutrs) {
3502 lrbp = &hba->lrb[index];
3503 cmd = lrbp->cmd;
3504 if (cmd) {
3505 result = ufshcd_transfer_rsp_status(hba, lrbp);
3506 scsi_dma_unmap(cmd);
3507 cmd->result = result;
3508 /* Mark completed command as NULL in LRB */
3509 lrbp->cmd = NULL;
3510 clear_bit_unlock(index, &hba->lrb_in_use);
3511 /* Do not touch lrbp after scsi done */
3512 cmd->scsi_done(cmd);
1ab27c9c 3513 __ufshcd_release(hba);
e9d501b1
DR
3514 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
3515 if (hba->dev_cmd.complete)
3516 complete(hba->dev_cmd.complete);
3517 }
3518 }
7a3e97b0
SY
3519
3520 /* clear corresponding bits of completed commands */
3521 hba->outstanding_reqs ^= completed_reqs;
3522
856b3483
ST
3523 ufshcd_clk_scaling_update_busy(hba);
3524
5a0b0cb9
SRT
3525 /* we might have free'd some tags above */
3526 wake_up(&hba->dev_cmd.tag_wq);
7a3e97b0
SY
3527}
3528
9a47ec7c
YG
3529/**
3530 * ufshcd_transfer_req_compl - handle SCSI and query command completion
3531 * @hba: per adapter instance
3532 */
3533static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
3534{
3535 unsigned long completed_reqs;
3536 u32 tr_doorbell;
3537
3538 /* Resetting interrupt aggregation counters first and reading the
3539 * DOOR_BELL afterward allows us to handle all the completed requests.
3540 * In order to prevent other interrupts starvation the DB is read once
3541 * after reset. The down side of this solution is the possibility of
3542 * false interrupt if device completes another request after resetting
3543 * aggregation and before reading the DB.
3544 */
3545 if (ufshcd_is_intr_aggr_allowed(hba))
3546 ufshcd_reset_intr_aggr(hba);
3547
3548 tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
3549 completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
3550
3551 __ufshcd_transfer_req_compl(hba, completed_reqs);
3552}
3553
66ec6d59
SRT
3554/**
3555 * ufshcd_disable_ee - disable exception event
3556 * @hba: per-adapter instance
3557 * @mask: exception event to disable
3558 *
3559 * Disables exception event in the device so that the EVENT_ALERT
3560 * bit is not set.
3561 *
3562 * Returns zero on success, non-zero error value on failure.
3563 */
3564static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
3565{
3566 int err = 0;
3567 u32 val;
3568
3569 if (!(hba->ee_ctrl_mask & mask))
3570 goto out;
3571
3572 val = hba->ee_ctrl_mask & ~mask;
3573 val &= 0xFFFF; /* 2 bytes */
5e86ae44 3574 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
66ec6d59
SRT
3575 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3576 if (!err)
3577 hba->ee_ctrl_mask &= ~mask;
3578out:
3579 return err;
3580}
3581
3582/**
3583 * ufshcd_enable_ee - enable exception event
3584 * @hba: per-adapter instance
3585 * @mask: exception event to enable
3586 *
3587 * Enable corresponding exception event in the device to allow
3588 * device to alert host in critical scenarios.
3589 *
3590 * Returns zero on success, non-zero error value on failure.
3591 */
3592static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
3593{
3594 int err = 0;
3595 u32 val;
3596
3597 if (hba->ee_ctrl_mask & mask)
3598 goto out;
3599
3600 val = hba->ee_ctrl_mask | mask;
3601 val &= 0xFFFF; /* 2 bytes */
5e86ae44 3602 err = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
66ec6d59
SRT
3603 QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
3604 if (!err)
3605 hba->ee_ctrl_mask |= mask;
3606out:
3607 return err;
3608}
3609
3610/**
3611 * ufshcd_enable_auto_bkops - Allow device managed BKOPS
3612 * @hba: per-adapter instance
3613 *
3614 * Allow device to manage background operations on its own. Enabling
3615 * this might lead to inconsistent latencies during normal data transfers
3616 * as the device is allowed to manage its own way of handling background
3617 * operations.
3618 *
3619 * Returns zero on success, non-zero on failure.
3620 */
3621static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
3622{
3623 int err = 0;
3624
3625 if (hba->auto_bkops_enabled)
3626 goto out;
3627
dc3c8d3a 3628 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_SET_FLAG,
66ec6d59
SRT
3629 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3630 if (err) {
3631 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
3632 __func__, err);
3633 goto out;
3634 }
3635
3636 hba->auto_bkops_enabled = true;
3637
3638 /* No need of URGENT_BKOPS exception from the device */
3639 err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3640 if (err)
3641 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
3642 __func__, err);
3643out:
3644 return err;
3645}
3646
3647/**
3648 * ufshcd_disable_auto_bkops - block device in doing background operations
3649 * @hba: per-adapter instance
3650 *
3651 * Disabling background operations improves command response latency but
3652 * has drawback of device moving into critical state where the device is
3653 * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
3654 * host is idle so that BKOPS are managed effectively without any negative
3655 * impacts.
3656 *
3657 * Returns zero on success, non-zero on failure.
3658 */
3659static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
3660{
3661 int err = 0;
3662
3663 if (!hba->auto_bkops_enabled)
3664 goto out;
3665
3666 /*
3667 * If host assisted BKOPs is to be enabled, make sure
3668 * urgent bkops exception is allowed.
3669 */
3670 err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
3671 if (err) {
3672 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
3673 __func__, err);
3674 goto out;
3675 }
3676
dc3c8d3a 3677 err = ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
66ec6d59
SRT
3678 QUERY_FLAG_IDN_BKOPS_EN, NULL);
3679 if (err) {
3680 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
3681 __func__, err);
3682 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
3683 goto out;
3684 }
3685
3686 hba->auto_bkops_enabled = false;
3687out:
3688 return err;
3689}
3690
3691/**
3692 * ufshcd_force_reset_auto_bkops - force enable of auto bkops
3693 * @hba: per adapter instance
3694 *
3695 * After a device reset the device may toggle the BKOPS_EN flag
3696 * to default value. The s/w tracking variables should be updated
3697 * as well. Do this by forcing enable of auto bkops.
3698 */
3699static void ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
3700{
3701 hba->auto_bkops_enabled = false;
3702 hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
3703 ufshcd_enable_auto_bkops(hba);
3704}
3705
3706static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
3707{
5e86ae44 3708 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
66ec6d59
SRT
3709 QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
3710}
3711
3712/**
57d104c1 3713 * ufshcd_bkops_ctrl - control the auto bkops based on current bkops status
66ec6d59 3714 * @hba: per-adapter instance
57d104c1 3715 * @status: bkops_status value
66ec6d59 3716 *
57d104c1
SJ
3717 * Read the bkops_status from the UFS device and Enable fBackgroundOpsEn
3718 * flag in the device to permit background operations if the device
3719 * bkops_status is greater than or equal to "status" argument passed to
3720 * this function, disable otherwise.
3721 *
3722 * Returns 0 for success, non-zero in case of failure.
3723 *
3724 * NOTE: Caller of this function can check the "hba->auto_bkops_enabled" flag
3725 * to know whether auto bkops is enabled or disabled after this function
3726 * returns control to it.
66ec6d59 3727 */
57d104c1
SJ
3728static int ufshcd_bkops_ctrl(struct ufs_hba *hba,
3729 enum bkops_status status)
66ec6d59
SRT
3730{
3731 int err;
57d104c1 3732 u32 curr_status = 0;
66ec6d59 3733
57d104c1 3734 err = ufshcd_get_bkops_status(hba, &curr_status);
66ec6d59
SRT
3735 if (err) {
3736 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
3737 __func__, err);
3738 goto out;
57d104c1
SJ
3739 } else if (curr_status > BKOPS_STATUS_MAX) {
3740 dev_err(hba->dev, "%s: invalid BKOPS status %d\n",
3741 __func__, curr_status);
3742 err = -EINVAL;
3743 goto out;
66ec6d59
SRT
3744 }
3745
57d104c1 3746 if (curr_status >= status)
66ec6d59 3747 err = ufshcd_enable_auto_bkops(hba);
57d104c1
SJ
3748 else
3749 err = ufshcd_disable_auto_bkops(hba);
66ec6d59
SRT
3750out:
3751 return err;
3752}
3753
57d104c1
SJ
3754/**
3755 * ufshcd_urgent_bkops - handle urgent bkops exception event
3756 * @hba: per-adapter instance
3757 *
3758 * Enable fBackgroundOpsEn flag in the device to permit background
3759 * operations.
3760 *
3761 * If BKOPs is enabled, this function returns 0, 1 if the bkops in not enabled
3762 * and negative error value for any other failure.
3763 */
3764static int ufshcd_urgent_bkops(struct ufs_hba *hba)
3765{
3766 return ufshcd_bkops_ctrl(hba, BKOPS_STATUS_PERF_IMPACT);
3767}
3768
66ec6d59
SRT
3769static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
3770{
5e86ae44 3771 return ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_READ_ATTR,
66ec6d59
SRT
3772 QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
3773}
3774
3775/**
3776 * ufshcd_exception_event_handler - handle exceptions raised by device
3777 * @work: pointer to work data
3778 *
3779 * Read bExceptionEventStatus attribute from the device and handle the
3780 * exception event accordingly.
3781 */
3782static void ufshcd_exception_event_handler(struct work_struct *work)
3783{
3784 struct ufs_hba *hba;
3785 int err;
3786 u32 status = 0;
3787 hba = container_of(work, struct ufs_hba, eeh_work);
3788
62694735 3789 pm_runtime_get_sync(hba->dev);
66ec6d59
SRT
3790 err = ufshcd_get_ee_status(hba, &status);
3791 if (err) {
3792 dev_err(hba->dev, "%s: failed to get exception status %d\n",
3793 __func__, err);
3794 goto out;
3795 }
3796
3797 status &= hba->ee_ctrl_mask;
3798 if (status & MASK_EE_URGENT_BKOPS) {
3799 err = ufshcd_urgent_bkops(hba);
57d104c1 3800 if (err < 0)
66ec6d59
SRT
3801 dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
3802 __func__, err);
3803 }
3804out:
62694735 3805 pm_runtime_put_sync(hba->dev);
66ec6d59
SRT
3806 return;
3807}
3808
9a47ec7c
YG
3809/* Complete requests that have door-bell cleared */
3810static void ufshcd_complete_requests(struct ufs_hba *hba)
3811{
3812 ufshcd_transfer_req_compl(hba);
3813 ufshcd_tmc_handler(hba);
3814}
3815
583fa62d
YG
3816/**
3817 * ufshcd_quirk_dl_nac_errors - This function checks if error handling is
3818 * to recover from the DL NAC errors or not.
3819 * @hba: per-adapter instance
3820 *
3821 * Returns true if error handling is required, false otherwise
3822 */
3823static bool ufshcd_quirk_dl_nac_errors(struct ufs_hba *hba)
3824{
3825 unsigned long flags;
3826 bool err_handling = true;
3827
3828 spin_lock_irqsave(hba->host->host_lock, flags);
3829 /*
3830 * UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS only workaround the
3831 * device fatal error and/or DL NAC & REPLAY timeout errors.
3832 */
3833 if (hba->saved_err & (CONTROLLER_FATAL_ERROR | SYSTEM_BUS_FATAL_ERROR))
3834 goto out;
3835
3836 if ((hba->saved_err & DEVICE_FATAL_ERROR) ||
3837 ((hba->saved_err & UIC_ERROR) &&
3838 (hba->saved_uic_err & UFSHCD_UIC_DL_TCx_REPLAY_ERROR)))
3839 goto out;
3840
3841 if ((hba->saved_err & UIC_ERROR) &&
3842 (hba->saved_uic_err & UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)) {
3843 int err;
3844 /*
3845 * wait for 50ms to see if we can get any other errors or not.
3846 */
3847 spin_unlock_irqrestore(hba->host->host_lock, flags);
3848 msleep(50);
3849 spin_lock_irqsave(hba->host->host_lock, flags);
3850
3851 /*
3852 * now check if we have got any other severe errors other than
3853 * DL NAC error?
3854 */
3855 if ((hba->saved_err & INT_FATAL_ERRORS) ||
3856 ((hba->saved_err & UIC_ERROR) &&
3857 (hba->saved_uic_err & ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)))
3858 goto out;
3859
3860 /*
3861 * As DL NAC is the only error received so far, send out NOP
3862 * command to confirm if link is still active or not.
3863 * - If we don't get any response then do error recovery.
3864 * - If we get response then clear the DL NAC error bit.
3865 */
3866
3867 spin_unlock_irqrestore(hba->host->host_lock, flags);
3868 err = ufshcd_verify_dev_init(hba);
3869 spin_lock_irqsave(hba->host->host_lock, flags);
3870
3871 if (err)
3872 goto out;
3873
3874 /* Link seems to be alive hence ignore the DL NAC errors */
3875 if (hba->saved_uic_err == UFSHCD_UIC_DL_NAC_RECEIVED_ERROR)
3876 hba->saved_err &= ~UIC_ERROR;
3877 /* clear NAC error */
3878 hba->saved_uic_err &= ~UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
3879 if (!hba->saved_uic_err) {
3880 err_handling = false;
3881 goto out;
3882 }
3883 }
3884out:
3885 spin_unlock_irqrestore(hba->host->host_lock, flags);
3886 return err_handling;
3887}
3888
7a3e97b0 3889/**
e8e7f271
SRT
3890 * ufshcd_err_handler - handle UFS errors that require s/w attention
3891 * @work: pointer to work structure
7a3e97b0 3892 */
e8e7f271 3893static void ufshcd_err_handler(struct work_struct *work)
7a3e97b0
SY
3894{
3895 struct ufs_hba *hba;
e8e7f271
SRT
3896 unsigned long flags;
3897 u32 err_xfer = 0;
3898 u32 err_tm = 0;
3899 int err = 0;
3900 int tag;
9a47ec7c 3901 bool needs_reset = false;
e8e7f271
SRT
3902
3903 hba = container_of(work, struct ufs_hba, eh_work);
7a3e97b0 3904
62694735 3905 pm_runtime_get_sync(hba->dev);
1ab27c9c 3906 ufshcd_hold(hba, false);
e8e7f271
SRT
3907
3908 spin_lock_irqsave(hba->host->host_lock, flags);
9a47ec7c 3909 if (hba->ufshcd_state == UFSHCD_STATE_RESET)
e8e7f271 3910 goto out;
e8e7f271
SRT
3911
3912 hba->ufshcd_state = UFSHCD_STATE_RESET;
3913 ufshcd_set_eh_in_progress(hba);
3914
3915 /* Complete requests that have door-bell cleared by h/w */
9a47ec7c 3916 ufshcd_complete_requests(hba);
583fa62d
YG
3917
3918 if (hba->dev_quirks & UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
3919 bool ret;
3920
3921 spin_unlock_irqrestore(hba->host->host_lock, flags);
3922 /* release the lock as ufshcd_quirk_dl_nac_errors() may sleep */
3923 ret = ufshcd_quirk_dl_nac_errors(hba);
3924 spin_lock_irqsave(hba->host->host_lock, flags);
3925 if (!ret)
3926 goto skip_err_handling;
3927 }
9a47ec7c
YG
3928 if ((hba->saved_err & INT_FATAL_ERRORS) ||
3929 ((hba->saved_err & UIC_ERROR) &&
3930 (hba->saved_uic_err & (UFSHCD_UIC_DL_PA_INIT_ERROR |
3931 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR |
3932 UFSHCD_UIC_DL_TCx_REPLAY_ERROR))))
3933 needs_reset = true;
e8e7f271 3934
9a47ec7c
YG
3935 /*
3936 * if host reset is required then skip clearing the pending
3937 * transfers forcefully because they will automatically get
3938 * cleared after link startup.
3939 */
3940 if (needs_reset)
3941 goto skip_pending_xfer_clear;
3942
3943 /* release lock as clear command might sleep */
3944 spin_unlock_irqrestore(hba->host->host_lock, flags);
e8e7f271 3945 /* Clear pending transfer requests */
9a47ec7c
YG
3946 for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs) {
3947 if (ufshcd_clear_cmd(hba, tag)) {
3948 err_xfer = true;
3949 goto lock_skip_pending_xfer_clear;
3950 }
3951 }
e8e7f271
SRT
3952
3953 /* Clear pending task management requests */
9a47ec7c
YG
3954 for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs) {
3955 if (ufshcd_clear_tm_cmd(hba, tag)) {
3956 err_tm = true;
3957 goto lock_skip_pending_xfer_clear;
3958 }
3959 }
e8e7f271 3960
9a47ec7c 3961lock_skip_pending_xfer_clear:
e8e7f271 3962 spin_lock_irqsave(hba->host->host_lock, flags);
e8e7f271 3963
9a47ec7c
YG
3964 /* Complete the requests that are cleared by s/w */
3965 ufshcd_complete_requests(hba);
3966
3967 if (err_xfer || err_tm)
3968 needs_reset = true;
3969
3970skip_pending_xfer_clear:
e8e7f271 3971 /* Fatal errors need reset */
9a47ec7c
YG
3972 if (needs_reset) {
3973 unsigned long max_doorbells = (1UL << hba->nutrs) - 1;
3974
3975 /*
3976 * ufshcd_reset_and_restore() does the link reinitialization
3977 * which will need atleast one empty doorbell slot to send the
3978 * device management commands (NOP and query commands).
3979 * If there is no slot empty at this moment then free up last
3980 * slot forcefully.
3981 */
3982 if (hba->outstanding_reqs == max_doorbells)
3983 __ufshcd_transfer_req_compl(hba,
3984 (1UL << (hba->nutrs - 1)));
3985
3986 spin_unlock_irqrestore(hba->host->host_lock, flags);
e8e7f271 3987 err = ufshcd_reset_and_restore(hba);
9a47ec7c 3988 spin_lock_irqsave(hba->host->host_lock, flags);
e8e7f271
SRT
3989 if (err) {
3990 dev_err(hba->dev, "%s: reset and restore failed\n",
3991 __func__);
3992 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3993 }
3994 /*
3995 * Inform scsi mid-layer that we did reset and allow to handle
3996 * Unit Attention properly.
3997 */
3998 scsi_report_bus_reset(hba->host, 0);
3999 hba->saved_err = 0;
4000 hba->saved_uic_err = 0;
4001 }
9a47ec7c 4002
583fa62d 4003skip_err_handling:
9a47ec7c
YG
4004 if (!needs_reset) {
4005 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4006 if (hba->saved_err || hba->saved_uic_err)
4007 dev_err_ratelimited(hba->dev, "%s: exit: saved_err 0x%x saved_uic_err 0x%x",
4008 __func__, hba->saved_err, hba->saved_uic_err);
4009 }
4010
e8e7f271
SRT
4011 ufshcd_clear_eh_in_progress(hba);
4012
4013out:
9a47ec7c 4014 spin_unlock_irqrestore(hba->host->host_lock, flags);
e8e7f271 4015 scsi_unblock_requests(hba->host);
1ab27c9c 4016 ufshcd_release(hba);
62694735 4017 pm_runtime_put_sync(hba->dev);
7a3e97b0
SY
4018}
4019
4020/**
e8e7f271
SRT
4021 * ufshcd_update_uic_error - check and set fatal UIC error flags.
4022 * @hba: per-adapter instance
7a3e97b0 4023 */
e8e7f271 4024static void ufshcd_update_uic_error(struct ufs_hba *hba)
7a3e97b0
SY
4025{
4026 u32 reg;
4027
e8e7f271
SRT
4028 /* PA_INIT_ERROR is fatal and needs UIC reset */
4029 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
4030 if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
4031 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
583fa62d
YG
4032 else if (hba->dev_quirks &
4033 UFS_DEVICE_QUIRK_RECOVERY_FROM_DL_NAC_ERRORS) {
4034 if (reg & UIC_DATA_LINK_LAYER_ERROR_NAC_RECEIVED)
4035 hba->uic_error |=
4036 UFSHCD_UIC_DL_NAC_RECEIVED_ERROR;
4037 else if (reg & UIC_DATA_LINK_LAYER_ERROR_TCx_REPLAY_TIMEOUT)
4038 hba->uic_error |= UFSHCD_UIC_DL_TCx_REPLAY_ERROR;
4039 }
e8e7f271
SRT
4040
4041 /* UIC NL/TL/DME errors needs software retry */
4042 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
4043 if (reg)
4044 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
4045
4046 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
4047 if (reg)
4048 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
4049
4050 reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
4051 if (reg)
4052 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
4053
4054 dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
4055 __func__, hba->uic_error);
4056}
4057
4058/**
4059 * ufshcd_check_errors - Check for errors that need s/w attention
4060 * @hba: per-adapter instance
4061 */
4062static void ufshcd_check_errors(struct ufs_hba *hba)
4063{
4064 bool queue_eh_work = false;
4065
7a3e97b0 4066 if (hba->errors & INT_FATAL_ERRORS)
e8e7f271 4067 queue_eh_work = true;
7a3e97b0
SY
4068
4069 if (hba->errors & UIC_ERROR) {
e8e7f271
SRT
4070 hba->uic_error = 0;
4071 ufshcd_update_uic_error(hba);
4072 if (hba->uic_error)
4073 queue_eh_work = true;
7a3e97b0 4074 }
e8e7f271
SRT
4075
4076 if (queue_eh_work) {
9a47ec7c
YG
4077 /*
4078 * update the transfer error masks to sticky bits, let's do this
4079 * irrespective of current ufshcd_state.
4080 */
4081 hba->saved_err |= hba->errors;
4082 hba->saved_uic_err |= hba->uic_error;
4083
e8e7f271
SRT
4084 /* handle fatal errors only when link is functional */
4085 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
4086 /* block commands from scsi mid-layer */
4087 scsi_block_requests(hba->host);
4088
e8e7f271
SRT
4089 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4090 schedule_work(&hba->eh_work);
4091 }
3441da7d 4092 }
e8e7f271
SRT
4093 /*
4094 * if (!queue_eh_work) -
4095 * Other errors are either non-fatal where host recovers
4096 * itself without s/w intervention or errors that will be
4097 * handled by the SCSI core layer.
4098 */
7a3e97b0
SY
4099}
4100
4101/**
4102 * ufshcd_tmc_handler - handle task management function completion
4103 * @hba: per adapter instance
4104 */
4105static void ufshcd_tmc_handler(struct ufs_hba *hba)
4106{
4107 u32 tm_doorbell;
4108
b873a275 4109 tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
7a3e97b0 4110 hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
e2933132 4111 wake_up(&hba->tm_wq);
7a3e97b0
SY
4112}
4113
4114/**
4115 * ufshcd_sl_intr - Interrupt service routine
4116 * @hba: per adapter instance
4117 * @intr_status: contains interrupts generated by the controller
4118 */
4119static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
4120{
4121 hba->errors = UFSHCD_ERROR_MASK & intr_status;
4122 if (hba->errors)
e8e7f271 4123 ufshcd_check_errors(hba);
7a3e97b0 4124
53b3d9c3
SJ
4125 if (intr_status & UFSHCD_UIC_MASK)
4126 ufshcd_uic_cmd_compl(hba, intr_status);
7a3e97b0
SY
4127
4128 if (intr_status & UTP_TASK_REQ_COMPL)
4129 ufshcd_tmc_handler(hba);
4130
4131 if (intr_status & UTP_TRANSFER_REQ_COMPL)
4132 ufshcd_transfer_req_compl(hba);
4133}
4134
4135/**
4136 * ufshcd_intr - Main interrupt service routine
4137 * @irq: irq number
4138 * @__hba: pointer to adapter instance
4139 *
4140 * Returns IRQ_HANDLED - If interrupt is valid
4141 * IRQ_NONE - If invalid interrupt
4142 */
4143static irqreturn_t ufshcd_intr(int irq, void *__hba)
4144{
d75f7fe4 4145 u32 intr_status, enabled_intr_status;
7a3e97b0
SY
4146 irqreturn_t retval = IRQ_NONE;
4147 struct ufs_hba *hba = __hba;
4148
4149 spin_lock(hba->host->host_lock);
b873a275 4150 intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
d75f7fe4
YG
4151 enabled_intr_status =
4152 intr_status & ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
7a3e97b0 4153
d75f7fe4 4154 if (intr_status)
261ea452 4155 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
d75f7fe4
YG
4156
4157 if (enabled_intr_status) {
4158 ufshcd_sl_intr(hba, enabled_intr_status);
7a3e97b0
SY
4159 retval = IRQ_HANDLED;
4160 }
4161 spin_unlock(hba->host->host_lock);
4162 return retval;
4163}
4164
e2933132
SRT
4165static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
4166{
4167 int err = 0;
4168 u32 mask = 1 << tag;
4169 unsigned long flags;
4170
4171 if (!test_bit(tag, &hba->outstanding_tasks))
4172 goto out;
4173
4174 spin_lock_irqsave(hba->host->host_lock, flags);
4175 ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
4176 spin_unlock_irqrestore(hba->host->host_lock, flags);
4177
4178 /* poll for max. 1 sec to clear door bell register by h/w */
4179 err = ufshcd_wait_for_register(hba,
4180 REG_UTP_TASK_REQ_DOOR_BELL,
596585a2 4181 mask, 0, 1000, 1000, true);
e2933132
SRT
4182out:
4183 return err;
4184}
4185
7a3e97b0
SY
4186/**
4187 * ufshcd_issue_tm_cmd - issues task management commands to controller
4188 * @hba: per adapter instance
e2933132
SRT
4189 * @lun_id: LUN ID to which TM command is sent
4190 * @task_id: task ID to which the TM command is applicable
4191 * @tm_function: task management function opcode
4192 * @tm_response: task management service response return value
7a3e97b0 4193 *
e2933132 4194 * Returns non-zero value on error, zero on success.
7a3e97b0 4195 */
e2933132
SRT
4196static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
4197 u8 tm_function, u8 *tm_response)
7a3e97b0
SY
4198{
4199 struct utp_task_req_desc *task_req_descp;
4200 struct utp_upiu_task_req *task_req_upiup;
4201 struct Scsi_Host *host;
4202 unsigned long flags;
e2933132 4203 int free_slot;
7a3e97b0 4204 int err;
e2933132 4205 int task_tag;
7a3e97b0
SY
4206
4207 host = hba->host;
4208
e2933132
SRT
4209 /*
4210 * Get free slot, sleep if slots are unavailable.
4211 * Even though we use wait_event() which sleeps indefinitely,
4212 * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
4213 */
4214 wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
1ab27c9c 4215 ufshcd_hold(hba, false);
7a3e97b0 4216
e2933132 4217 spin_lock_irqsave(host->host_lock, flags);
7a3e97b0
SY
4218 task_req_descp = hba->utmrdl_base_addr;
4219 task_req_descp += free_slot;
4220
4221 /* Configure task request descriptor */
4222 task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
4223 task_req_descp->header.dword_2 =
4224 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
4225
4226 /* Configure task request UPIU */
4227 task_req_upiup =
4228 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
e2933132 4229 task_tag = hba->nutrs + free_slot;
7a3e97b0 4230 task_req_upiup->header.dword_0 =
5a0b0cb9 4231 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
e2933132 4232 lun_id, task_tag);
7a3e97b0 4233 task_req_upiup->header.dword_1 =
5a0b0cb9 4234 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
0ce147d4
SJ
4235 /*
4236 * The host shall provide the same value for LUN field in the basic
4237 * header and for Input Parameter.
4238 */
e2933132
SRT
4239 task_req_upiup->input_param1 = cpu_to_be32(lun_id);
4240 task_req_upiup->input_param2 = cpu_to_be32(task_id);
7a3e97b0
SY
4241
4242 /* send command to the controller */
4243 __set_bit(free_slot, &hba->outstanding_tasks);
897efe62
YG
4244
4245 /* Make sure descriptors are ready before ringing the task doorbell */
4246 wmb();
4247
b873a275 4248 ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
7a3e97b0
SY
4249
4250 spin_unlock_irqrestore(host->host_lock, flags);
4251
4252 /* wait until the task management command is completed */
e2933132
SRT
4253 err = wait_event_timeout(hba->tm_wq,
4254 test_bit(free_slot, &hba->tm_condition),
4255 msecs_to_jiffies(TM_CMD_TIMEOUT));
7a3e97b0 4256 if (!err) {
e2933132
SRT
4257 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
4258 __func__, tm_function);
4259 if (ufshcd_clear_tm_cmd(hba, free_slot))
4260 dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
4261 __func__, free_slot);
4262 err = -ETIMEDOUT;
4263 } else {
4264 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
7a3e97b0 4265 }
e2933132 4266
7a3e97b0 4267 clear_bit(free_slot, &hba->tm_condition);
e2933132
SRT
4268 ufshcd_put_tm_slot(hba, free_slot);
4269 wake_up(&hba->tm_tag_wq);
4270
1ab27c9c 4271 ufshcd_release(hba);
7a3e97b0
SY
4272 return err;
4273}
4274
4275/**
3441da7d
SRT
4276 * ufshcd_eh_device_reset_handler - device reset handler registered to
4277 * scsi layer.
7a3e97b0
SY
4278 * @cmd: SCSI command pointer
4279 *
4280 * Returns SUCCESS/FAILED
4281 */
3441da7d 4282static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
7a3e97b0
SY
4283{
4284 struct Scsi_Host *host;
4285 struct ufs_hba *hba;
4286 unsigned int tag;
4287 u32 pos;
4288 int err;
e2933132
SRT
4289 u8 resp = 0xF;
4290 struct ufshcd_lrb *lrbp;
3441da7d 4291 unsigned long flags;
7a3e97b0
SY
4292
4293 host = cmd->device->host;
4294 hba = shost_priv(host);
4295 tag = cmd->request->tag;
4296
e2933132
SRT
4297 lrbp = &hba->lrb[tag];
4298 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
4299 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
3441da7d
SRT
4300 if (!err)
4301 err = resp;
7a3e97b0 4302 goto out;
e2933132 4303 }
7a3e97b0 4304
3441da7d
SRT
4305 /* clear the commands that were pending for corresponding LUN */
4306 for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
4307 if (hba->lrb[pos].lun == lrbp->lun) {
4308 err = ufshcd_clear_cmd(hba, pos);
4309 if (err)
4310 break;
7a3e97b0 4311 }
3441da7d
SRT
4312 }
4313 spin_lock_irqsave(host->host_lock, flags);
4314 ufshcd_transfer_req_compl(hba);
4315 spin_unlock_irqrestore(host->host_lock, flags);
7a3e97b0 4316out:
3441da7d
SRT
4317 if (!err) {
4318 err = SUCCESS;
4319 } else {
4320 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4321 err = FAILED;
4322 }
7a3e97b0
SY
4323 return err;
4324}
4325
7a3e97b0
SY
4326/**
4327 * ufshcd_abort - abort a specific command
4328 * @cmd: SCSI command pointer
4329 *
f20810d8
SRT
4330 * Abort the pending command in device by sending UFS_ABORT_TASK task management
4331 * command, and in host controller by clearing the door-bell register. There can
4332 * be race between controller sending the command to the device while abort is
4333 * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
4334 * really issued and then try to abort it.
4335 *
7a3e97b0
SY
4336 * Returns SUCCESS/FAILED
4337 */
4338static int ufshcd_abort(struct scsi_cmnd *cmd)
4339{
4340 struct Scsi_Host *host;
4341 struct ufs_hba *hba;
4342 unsigned long flags;
4343 unsigned int tag;
f20810d8
SRT
4344 int err = 0;
4345 int poll_cnt;
e2933132
SRT
4346 u8 resp = 0xF;
4347 struct ufshcd_lrb *lrbp;
e9d501b1 4348 u32 reg;
7a3e97b0
SY
4349
4350 host = cmd->device->host;
4351 hba = shost_priv(host);
4352 tag = cmd->request->tag;
14497328
YG
4353 if (!ufshcd_valid_tag(hba, tag)) {
4354 dev_err(hba->dev,
4355 "%s: invalid command tag %d: cmd=0x%p, cmd->request=0x%p",
4356 __func__, tag, cmd, cmd->request);
4357 BUG();
4358 }
7a3e97b0 4359
1ab27c9c 4360 ufshcd_hold(hba, false);
14497328 4361 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
f20810d8 4362 /* If command is already aborted/completed, return SUCCESS */
14497328
YG
4363 if (!(test_bit(tag, &hba->outstanding_reqs))) {
4364 dev_err(hba->dev,
4365 "%s: cmd at tag %d already completed, outstanding=0x%lx, doorbell=0x%x\n",
4366 __func__, tag, hba->outstanding_reqs, reg);
f20810d8 4367 goto out;
14497328 4368 }
7a3e97b0 4369
e9d501b1
DR
4370 if (!(reg & (1 << tag))) {
4371 dev_err(hba->dev,
4372 "%s: cmd was completed, but without a notifying intr, tag = %d",
4373 __func__, tag);
4374 }
4375
f20810d8
SRT
4376 lrbp = &hba->lrb[tag];
4377 for (poll_cnt = 100; poll_cnt; poll_cnt--) {
4378 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4379 UFS_QUERY_TASK, &resp);
4380 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
4381 /* cmd pending in the device */
4382 break;
4383 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
f20810d8
SRT
4384 /*
4385 * cmd not pending in the device, check if it is
4386 * in transition.
4387 */
4388 reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
4389 if (reg & (1 << tag)) {
4390 /* sleep for max. 200us to stabilize */
4391 usleep_range(100, 200);
4392 continue;
4393 }
4394 /* command completed already */
4395 goto out;
4396 } else {
4397 if (!err)
4398 err = resp; /* service response error */
4399 goto out;
4400 }
4401 }
4402
4403 if (!poll_cnt) {
4404 err = -EBUSY;
7a3e97b0
SY
4405 goto out;
4406 }
7a3e97b0 4407
e2933132
SRT
4408 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
4409 UFS_ABORT_TASK, &resp);
4410 if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
f20810d8
SRT
4411 if (!err)
4412 err = resp; /* service response error */
7a3e97b0 4413 goto out;
e2933132 4414 }
7a3e97b0 4415
f20810d8
SRT
4416 err = ufshcd_clear_cmd(hba, tag);
4417 if (err)
4418 goto out;
4419
7a3e97b0
SY
4420 scsi_dma_unmap(cmd);
4421
4422 spin_lock_irqsave(host->host_lock, flags);
a48353f6 4423 ufshcd_outstanding_req_clear(hba, tag);
7a3e97b0
SY
4424 hba->lrb[tag].cmd = NULL;
4425 spin_unlock_irqrestore(host->host_lock, flags);
5a0b0cb9
SRT
4426
4427 clear_bit_unlock(tag, &hba->lrb_in_use);
4428 wake_up(&hba->dev_cmd.tag_wq);
1ab27c9c 4429
7a3e97b0 4430out:
f20810d8
SRT
4431 if (!err) {
4432 err = SUCCESS;
4433 } else {
4434 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
4435 err = FAILED;
4436 }
4437
1ab27c9c
ST
4438 /*
4439 * This ufshcd_release() corresponds to the original scsi cmd that got
4440 * aborted here (as we won't get any IRQ for it).
4441 */
4442 ufshcd_release(hba);
7a3e97b0
SY
4443 return err;
4444}
4445
3441da7d
SRT
4446/**
4447 * ufshcd_host_reset_and_restore - reset and restore host controller
4448 * @hba: per-adapter instance
4449 *
4450 * Note that host controller reset may issue DME_RESET to
4451 * local and remote (device) Uni-Pro stack and the attributes
4452 * are reset to default state.
4453 *
4454 * Returns zero on success, non-zero on failure
4455 */
4456static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
4457{
4458 int err;
3441da7d
SRT
4459 unsigned long flags;
4460
4461 /* Reset the host controller */
4462 spin_lock_irqsave(hba->host->host_lock, flags);
596585a2 4463 ufshcd_hba_stop(hba, false);
3441da7d
SRT
4464 spin_unlock_irqrestore(hba->host->host_lock, flags);
4465
4466 err = ufshcd_hba_enable(hba);
4467 if (err)
4468 goto out;
4469
4470 /* Establish the link again and restore the device */
1d337ec2
SRT
4471 err = ufshcd_probe_hba(hba);
4472
4473 if (!err && (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL))
3441da7d
SRT
4474 err = -EIO;
4475out:
4476 if (err)
4477 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
4478
4479 return err;
4480}
4481
4482/**
4483 * ufshcd_reset_and_restore - reset and re-initialize host/device
4484 * @hba: per-adapter instance
4485 *
4486 * Reset and recover device, host and re-establish link. This
4487 * is helpful to recover the communication in fatal error conditions.
4488 *
4489 * Returns zero on success, non-zero on failure
4490 */
4491static int ufshcd_reset_and_restore(struct ufs_hba *hba)
4492{
4493 int err = 0;
4494 unsigned long flags;
1d337ec2 4495 int retries = MAX_HOST_RESET_RETRIES;
3441da7d 4496
1d337ec2
SRT
4497 do {
4498 err = ufshcd_host_reset_and_restore(hba);
4499 } while (err && --retries);
3441da7d
SRT
4500
4501 /*
4502 * After reset the door-bell might be cleared, complete
4503 * outstanding requests in s/w here.
4504 */
4505 spin_lock_irqsave(hba->host->host_lock, flags);
4506 ufshcd_transfer_req_compl(hba);
4507 ufshcd_tmc_handler(hba);
4508 spin_unlock_irqrestore(hba->host->host_lock, flags);
4509
4510 return err;
4511}
4512
4513/**
4514 * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
4515 * @cmd - SCSI command pointer
4516 *
4517 * Returns SUCCESS/FAILED
4518 */
4519static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
4520{
4521 int err;
4522 unsigned long flags;
4523 struct ufs_hba *hba;
4524
4525 hba = shost_priv(cmd->device->host);
4526
1ab27c9c 4527 ufshcd_hold(hba, false);
3441da7d
SRT
4528 /*
4529 * Check if there is any race with fatal error handling.
4530 * If so, wait for it to complete. Even though fatal error
4531 * handling does reset and restore in some cases, don't assume
4532 * anything out of it. We are just avoiding race here.
4533 */
4534 do {
4535 spin_lock_irqsave(hba->host->host_lock, flags);
e8e7f271 4536 if (!(work_pending(&hba->eh_work) ||
3441da7d
SRT
4537 hba->ufshcd_state == UFSHCD_STATE_RESET))
4538 break;
4539 spin_unlock_irqrestore(hba->host->host_lock, flags);
4540 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
e8e7f271 4541 flush_work(&hba->eh_work);
3441da7d
SRT
4542 } while (1);
4543
4544 hba->ufshcd_state = UFSHCD_STATE_RESET;
4545 ufshcd_set_eh_in_progress(hba);
4546 spin_unlock_irqrestore(hba->host->host_lock, flags);
4547
4548 err = ufshcd_reset_and_restore(hba);
4549
4550 spin_lock_irqsave(hba->host->host_lock, flags);
4551 if (!err) {
4552 err = SUCCESS;
4553 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
4554 } else {
4555 err = FAILED;
4556 hba->ufshcd_state = UFSHCD_STATE_ERROR;
4557 }
4558 ufshcd_clear_eh_in_progress(hba);
4559 spin_unlock_irqrestore(hba->host->host_lock, flags);
4560
1ab27c9c 4561 ufshcd_release(hba);
3441da7d
SRT
4562 return err;
4563}
4564
3a4bf06d
YG
4565/**
4566 * ufshcd_get_max_icc_level - calculate the ICC level
4567 * @sup_curr_uA: max. current supported by the regulator
4568 * @start_scan: row at the desc table to start scan from
4569 * @buff: power descriptor buffer
4570 *
4571 * Returns calculated max ICC level for specific regulator
4572 */
4573static u32 ufshcd_get_max_icc_level(int sup_curr_uA, u32 start_scan, char *buff)
4574{
4575 int i;
4576 int curr_uA;
4577 u16 data;
4578 u16 unit;
4579
4580 for (i = start_scan; i >= 0; i--) {
4581 data = be16_to_cpu(*((u16 *)(buff + 2*i)));
4582 unit = (data & ATTR_ICC_LVL_UNIT_MASK) >>
4583 ATTR_ICC_LVL_UNIT_OFFSET;
4584 curr_uA = data & ATTR_ICC_LVL_VALUE_MASK;
4585 switch (unit) {
4586 case UFSHCD_NANO_AMP:
4587 curr_uA = curr_uA / 1000;
4588 break;
4589 case UFSHCD_MILI_AMP:
4590 curr_uA = curr_uA * 1000;
4591 break;
4592 case UFSHCD_AMP:
4593 curr_uA = curr_uA * 1000 * 1000;
4594 break;
4595 case UFSHCD_MICRO_AMP:
4596 default:
4597 break;
4598 }
4599 if (sup_curr_uA >= curr_uA)
4600 break;
4601 }
4602 if (i < 0) {
4603 i = 0;
4604 pr_err("%s: Couldn't find valid icc_level = %d", __func__, i);
4605 }
4606
4607 return (u32)i;
4608}
4609
4610/**
4611 * ufshcd_calc_icc_level - calculate the max ICC level
4612 * In case regulators are not initialized we'll return 0
4613 * @hba: per-adapter instance
4614 * @desc_buf: power descriptor buffer to extract ICC levels from.
4615 * @len: length of desc_buff
4616 *
4617 * Returns calculated ICC level
4618 */
4619static u32 ufshcd_find_max_sup_active_icc_level(struct ufs_hba *hba,
4620 u8 *desc_buf, int len)
4621{
4622 u32 icc_level = 0;
4623
4624 if (!hba->vreg_info.vcc || !hba->vreg_info.vccq ||
4625 !hba->vreg_info.vccq2) {
4626 dev_err(hba->dev,
4627 "%s: Regulator capability was not set, actvIccLevel=%d",
4628 __func__, icc_level);
4629 goto out;
4630 }
4631
4632 if (hba->vreg_info.vcc)
4633 icc_level = ufshcd_get_max_icc_level(
4634 hba->vreg_info.vcc->max_uA,
4635 POWER_DESC_MAX_ACTV_ICC_LVLS - 1,
4636 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCC_0]);
4637
4638 if (hba->vreg_info.vccq)
4639 icc_level = ufshcd_get_max_icc_level(
4640 hba->vreg_info.vccq->max_uA,
4641 icc_level,
4642 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ_0]);
4643
4644 if (hba->vreg_info.vccq2)
4645 icc_level = ufshcd_get_max_icc_level(
4646 hba->vreg_info.vccq2->max_uA,
4647 icc_level,
4648 &desc_buf[PWR_DESC_ACTIVE_LVLS_VCCQ2_0]);
4649out:
4650 return icc_level;
4651}
4652
4653static void ufshcd_init_icc_levels(struct ufs_hba *hba)
4654{
4655 int ret;
4656 int buff_len = QUERY_DESC_POWER_MAX_SIZE;
4657 u8 desc_buf[QUERY_DESC_POWER_MAX_SIZE];
4658
4659 ret = ufshcd_read_power_desc(hba, desc_buf, buff_len);
4660 if (ret) {
4661 dev_err(hba->dev,
4662 "%s: Failed reading power descriptor.len = %d ret = %d",
4663 __func__, buff_len, ret);
4664 return;
4665 }
4666
4667 hba->init_prefetch_data.icc_level =
4668 ufshcd_find_max_sup_active_icc_level(hba,
4669 desc_buf, buff_len);
4670 dev_dbg(hba->dev, "%s: setting icc_level 0x%x",
4671 __func__, hba->init_prefetch_data.icc_level);
4672
5e86ae44
YG
4673 ret = ufshcd_query_attr_retry(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
4674 QUERY_ATTR_IDN_ACTIVE_ICC_LVL, 0, 0,
4675 &hba->init_prefetch_data.icc_level);
3a4bf06d
YG
4676
4677 if (ret)
4678 dev_err(hba->dev,
4679 "%s: Failed configuring bActiveICCLevel = %d ret = %d",
4680 __func__, hba->init_prefetch_data.icc_level , ret);
4681
4682}
4683
2a8fa600
SJ
4684/**
4685 * ufshcd_scsi_add_wlus - Adds required W-LUs
4686 * @hba: per-adapter instance
4687 *
4688 * UFS device specification requires the UFS devices to support 4 well known
4689 * logical units:
4690 * "REPORT_LUNS" (address: 01h)
4691 * "UFS Device" (address: 50h)
4692 * "RPMB" (address: 44h)
4693 * "BOOT" (address: 30h)
4694 * UFS device's power management needs to be controlled by "POWER CONDITION"
4695 * field of SSU (START STOP UNIT) command. But this "power condition" field
4696 * will take effect only when its sent to "UFS device" well known logical unit
4697 * hence we require the scsi_device instance to represent this logical unit in
4698 * order for the UFS host driver to send the SSU command for power management.
4699
4700 * We also require the scsi_device instance for "RPMB" (Replay Protected Memory
4701 * Block) LU so user space process can control this LU. User space may also
4702 * want to have access to BOOT LU.
4703
4704 * This function adds scsi device instances for each of all well known LUs
4705 * (except "REPORT LUNS" LU).
4706 *
4707 * Returns zero on success (all required W-LUs are added successfully),
4708 * non-zero error value on failure (if failed to add any of the required W-LU).
4709 */
4710static int ufshcd_scsi_add_wlus(struct ufs_hba *hba)
4711{
4712 int ret = 0;
7c48bfd0
AM
4713 struct scsi_device *sdev_rpmb;
4714 struct scsi_device *sdev_boot;
2a8fa600
SJ
4715
4716 hba->sdev_ufs_device = __scsi_add_device(hba->host, 0, 0,
4717 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_UFS_DEVICE_WLUN), NULL);
4718 if (IS_ERR(hba->sdev_ufs_device)) {
4719 ret = PTR_ERR(hba->sdev_ufs_device);
4720 hba->sdev_ufs_device = NULL;
4721 goto out;
4722 }
7c48bfd0 4723 scsi_device_put(hba->sdev_ufs_device);
2a8fa600 4724
7c48bfd0 4725 sdev_boot = __scsi_add_device(hba->host, 0, 0,
2a8fa600 4726 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_BOOT_WLUN), NULL);
7c48bfd0
AM
4727 if (IS_ERR(sdev_boot)) {
4728 ret = PTR_ERR(sdev_boot);
2a8fa600
SJ
4729 goto remove_sdev_ufs_device;
4730 }
7c48bfd0 4731 scsi_device_put(sdev_boot);
2a8fa600 4732
7c48bfd0 4733 sdev_rpmb = __scsi_add_device(hba->host, 0, 0,
2a8fa600 4734 ufshcd_upiu_wlun_to_scsi_wlun(UFS_UPIU_RPMB_WLUN), NULL);
7c48bfd0
AM
4735 if (IS_ERR(sdev_rpmb)) {
4736 ret = PTR_ERR(sdev_rpmb);
2a8fa600
SJ
4737 goto remove_sdev_boot;
4738 }
7c48bfd0 4739 scsi_device_put(sdev_rpmb);
2a8fa600
SJ
4740 goto out;
4741
4742remove_sdev_boot:
7c48bfd0 4743 scsi_remove_device(sdev_boot);
2a8fa600
SJ
4744remove_sdev_ufs_device:
4745 scsi_remove_device(hba->sdev_ufs_device);
4746out:
4747 return ret;
4748}
4749
c58ab7aa
YG
4750static int ufs_get_device_info(struct ufs_hba *hba,
4751 struct ufs_device_info *card_data)
4752{
4753 int err;
4754 u8 model_index;
4755 u8 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE + 1] = {0};
4756 u8 desc_buf[QUERY_DESC_DEVICE_MAX_SIZE];
4757
4758 err = ufshcd_read_device_desc(hba, desc_buf,
4759 QUERY_DESC_DEVICE_MAX_SIZE);
4760 if (err) {
4761 dev_err(hba->dev, "%s: Failed reading Device Desc. err = %d\n",
4762 __func__, err);
4763 goto out;
4764 }
4765
4766 /*
4767 * getting vendor (manufacturerID) and Bank Index in big endian
4768 * format
4769 */
4770 card_data->wmanufacturerid = desc_buf[DEVICE_DESC_PARAM_MANF_ID] << 8 |
4771 desc_buf[DEVICE_DESC_PARAM_MANF_ID + 1];
4772
4773 model_index = desc_buf[DEVICE_DESC_PARAM_PRDCT_NAME];
4774
4775 err = ufshcd_read_string_desc(hba, model_index, str_desc_buf,
4776 QUERY_DESC_STRING_MAX_SIZE, ASCII_STD);
4777 if (err) {
4778 dev_err(hba->dev, "%s: Failed reading Product Name. err = %d\n",
4779 __func__, err);
4780 goto out;
4781 }
4782
4783 str_desc_buf[QUERY_DESC_STRING_MAX_SIZE] = '\0';
4784 strlcpy(card_data->model, (str_desc_buf + QUERY_DESC_HDR_SIZE),
4785 min_t(u8, str_desc_buf[QUERY_DESC_LENGTH_OFFSET],
4786 MAX_MODEL_LEN));
4787
4788 /* Null terminate the model string */
4789 card_data->model[MAX_MODEL_LEN] = '\0';
4790
4791out:
4792 return err;
4793}
4794
4795void ufs_advertise_fixup_device(struct ufs_hba *hba)
4796{
4797 int err;
4798 struct ufs_dev_fix *f;
4799 struct ufs_device_info card_data;
4800
4801 card_data.wmanufacturerid = 0;
4802
4803 err = ufs_get_device_info(hba, &card_data);
4804 if (err) {
4805 dev_err(hba->dev, "%s: Failed getting device info. err = %d\n",
4806 __func__, err);
4807 return;
4808 }
4809
4810 for (f = ufs_fixups; f->quirk; f++) {
4811 if (((f->card.wmanufacturerid == card_data.wmanufacturerid) ||
4812 (f->card.wmanufacturerid == UFS_ANY_VENDOR)) &&
4813 (STR_PRFX_EQUAL(f->card.model, card_data.model) ||
4814 !strcmp(f->card.model, UFS_ANY_MODEL)))
4815 hba->dev_quirks |= f->quirk;
4816 }
4817}
4818
6ccf44fe 4819/**
1d337ec2
SRT
4820 * ufshcd_probe_hba - probe hba to detect device and initialize
4821 * @hba: per-adapter instance
4822 *
4823 * Execute link-startup and verify device initialization
6ccf44fe 4824 */
1d337ec2 4825static int ufshcd_probe_hba(struct ufs_hba *hba)
6ccf44fe 4826{
6ccf44fe
SJ
4827 int ret;
4828
4829 ret = ufshcd_link_startup(hba);
5a0b0cb9
SRT
4830 if (ret)
4831 goto out;
4832
5064636c
YG
4833 ufshcd_init_pwr_info(hba);
4834
57d104c1
SJ
4835 /* UniPro link is active now */
4836 ufshcd_set_link_active(hba);
d3e89bac 4837
5a0b0cb9
SRT
4838 ret = ufshcd_verify_dev_init(hba);
4839 if (ret)
4840 goto out;
68078d5c
DR
4841
4842 ret = ufshcd_complete_dev_init(hba);
4843 if (ret)
4844 goto out;
5a0b0cb9 4845
c58ab7aa 4846 ufs_advertise_fixup_device(hba);
60f01870
YG
4847
4848 ret = ufshcd_set_vccq_rail_unused(hba,
4849 (hba->dev_quirks & UFS_DEVICE_NO_VCCQ) ? true : false);
4850 if (ret)
4851 goto out;
4852
57d104c1
SJ
4853 /* UFS device is also active now */
4854 ufshcd_set_ufs_dev_active(hba);
66ec6d59 4855 ufshcd_force_reset_auto_bkops(hba);
57d104c1
SJ
4856 hba->wlun_dev_clr_ua = true;
4857
7eb584db
DR
4858 if (ufshcd_get_max_pwr_mode(hba)) {
4859 dev_err(hba->dev,
4860 "%s: Failed getting max supported power mode\n",
4861 __func__);
4862 } else {
4863 ret = ufshcd_config_pwr_mode(hba, &hba->max_pwr_info.info);
4864 if (ret)
4865 dev_err(hba->dev, "%s: Failed setting power mode, err = %d\n",
4866 __func__, ret);
4867 }
57d104c1 4868
53c12d0e
YG
4869 /* set the state as operational after switching to desired gear */
4870 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
57d104c1
SJ
4871 /*
4872 * If we are in error handling context or in power management callbacks
4873 * context, no need to scan the host
4874 */
4875 if (!ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4876 bool flag;
4877
4878 /* clear any previous UFS device information */
4879 memset(&hba->dev_info, 0, sizeof(hba->dev_info));
dc3c8d3a
YG
4880 if (!ufshcd_query_flag_retry(hba, UPIU_QUERY_OPCODE_READ_FLAG,
4881 QUERY_FLAG_IDN_PWR_ON_WPE, &flag))
57d104c1 4882 hba->dev_info.f_power_on_wp_en = flag;
3441da7d 4883
3a4bf06d
YG
4884 if (!hba->is_init_prefetch)
4885 ufshcd_init_icc_levels(hba);
4886
2a8fa600
SJ
4887 /* Add required well known logical units to scsi mid layer */
4888 if (ufshcd_scsi_add_wlus(hba))
4889 goto out;
4890
3441da7d
SRT
4891 scsi_scan_host(hba->host);
4892 pm_runtime_put_sync(hba->dev);
4893 }
3a4bf06d
YG
4894
4895 if (!hba->is_init_prefetch)
4896 hba->is_init_prefetch = true;
4897
856b3483
ST
4898 /* Resume devfreq after UFS device is detected */
4899 if (ufshcd_is_clkscaling_enabled(hba))
4900 devfreq_resume_device(hba->devfreq);
4901
5a0b0cb9 4902out:
1d337ec2
SRT
4903 /*
4904 * If we failed to initialize the device or the device is not
4905 * present, turn off the power/clocks etc.
4906 */
57d104c1
SJ
4907 if (ret && !ufshcd_eh_in_progress(hba) && !hba->pm_op_in_progress) {
4908 pm_runtime_put_sync(hba->dev);
1d337ec2 4909 ufshcd_hba_exit(hba);
57d104c1 4910 }
1d337ec2
SRT
4911
4912 return ret;
4913}
4914
4915/**
4916 * ufshcd_async_scan - asynchronous execution for probing hba
4917 * @data: data pointer to pass to this function
4918 * @cookie: cookie data
4919 */
4920static void ufshcd_async_scan(void *data, async_cookie_t cookie)
4921{
4922 struct ufs_hba *hba = (struct ufs_hba *)data;
4923
4924 ufshcd_probe_hba(hba);
6ccf44fe
SJ
4925}
4926
f550c65b
YG
4927static enum blk_eh_timer_return ufshcd_eh_timed_out(struct scsi_cmnd *scmd)
4928{
4929 unsigned long flags;
4930 struct Scsi_Host *host;
4931 struct ufs_hba *hba;
4932 int index;
4933 bool found = false;
4934
4935 if (!scmd || !scmd->device || !scmd->device->host)
4936 return BLK_EH_NOT_HANDLED;
4937
4938 host = scmd->device->host;
4939 hba = shost_priv(host);
4940 if (!hba)
4941 return BLK_EH_NOT_HANDLED;
4942
4943 spin_lock_irqsave(host->host_lock, flags);
4944
4945 for_each_set_bit(index, &hba->outstanding_reqs, hba->nutrs) {
4946 if (hba->lrb[index].cmd == scmd) {
4947 found = true;
4948 break;
4949 }
4950 }
4951
4952 spin_unlock_irqrestore(host->host_lock, flags);
4953
4954 /*
4955 * Bypass SCSI error handling and reset the block layer timer if this
4956 * SCSI command was not actually dispatched to UFS driver, otherwise
4957 * let SCSI layer handle the error as usual.
4958 */
4959 return found ? BLK_EH_NOT_HANDLED : BLK_EH_RESET_TIMER;
4960}
4961
7a3e97b0
SY
4962static struct scsi_host_template ufshcd_driver_template = {
4963 .module = THIS_MODULE,
4964 .name = UFSHCD,
4965 .proc_name = UFSHCD,
4966 .queuecommand = ufshcd_queuecommand,
4967 .slave_alloc = ufshcd_slave_alloc,
eeda4749 4968 .slave_configure = ufshcd_slave_configure,
7a3e97b0 4969 .slave_destroy = ufshcd_slave_destroy,
4264fd61 4970 .change_queue_depth = ufshcd_change_queue_depth,
7a3e97b0 4971 .eh_abort_handler = ufshcd_abort,
3441da7d
SRT
4972 .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
4973 .eh_host_reset_handler = ufshcd_eh_host_reset_handler,
f550c65b 4974 .eh_timed_out = ufshcd_eh_timed_out,
7a3e97b0
SY
4975 .this_id = -1,
4976 .sg_tablesize = SG_ALL,
4977 .cmd_per_lun = UFSHCD_CMD_PER_LUN,
4978 .can_queue = UFSHCD_CAN_QUEUE,
1ab27c9c 4979 .max_host_blocked = 1,
c40ecc12 4980 .track_queue_depth = 1,
7a3e97b0
SY
4981};
4982
57d104c1
SJ
4983static int ufshcd_config_vreg_load(struct device *dev, struct ufs_vreg *vreg,
4984 int ua)
4985{
7b16a07c 4986 int ret;
57d104c1 4987
7b16a07c
BA
4988 if (!vreg)
4989 return 0;
57d104c1 4990
7b16a07c
BA
4991 ret = regulator_set_load(vreg->reg, ua);
4992 if (ret < 0) {
4993 dev_err(dev, "%s: %s set load (ua=%d) failed, err=%d\n",
4994 __func__, vreg->name, ua, ret);
57d104c1
SJ
4995 }
4996
4997 return ret;
4998}
4999
5000static inline int ufshcd_config_vreg_lpm(struct ufs_hba *hba,
5001 struct ufs_vreg *vreg)
5002{
60f01870
YG
5003 if (!vreg)
5004 return 0;
5005 else if (vreg->unused)
5006 return 0;
5007 else
5008 return ufshcd_config_vreg_load(hba->dev, vreg,
5009 UFS_VREG_LPM_LOAD_UA);
57d104c1
SJ
5010}
5011
5012static inline int ufshcd_config_vreg_hpm(struct ufs_hba *hba,
5013 struct ufs_vreg *vreg)
5014{
60f01870
YG
5015 if (!vreg)
5016 return 0;
5017 else if (vreg->unused)
5018 return 0;
5019 else
5020 return ufshcd_config_vreg_load(hba->dev, vreg, vreg->max_uA);
57d104c1
SJ
5021}
5022
aa497613
SRT
5023static int ufshcd_config_vreg(struct device *dev,
5024 struct ufs_vreg *vreg, bool on)
5025{
5026 int ret = 0;
5027 struct regulator *reg = vreg->reg;
5028 const char *name = vreg->name;
5029 int min_uV, uA_load;
5030
5031 BUG_ON(!vreg);
5032
5033 if (regulator_count_voltages(reg) > 0) {
5034 min_uV = on ? vreg->min_uV : 0;
5035 ret = regulator_set_voltage(reg, min_uV, vreg->max_uV);
5036 if (ret) {
5037 dev_err(dev, "%s: %s set voltage failed, err=%d\n",
5038 __func__, name, ret);
5039 goto out;
5040 }
5041
5042 uA_load = on ? vreg->max_uA : 0;
57d104c1
SJ
5043 ret = ufshcd_config_vreg_load(dev, vreg, uA_load);
5044 if (ret)
aa497613 5045 goto out;
aa497613
SRT
5046 }
5047out:
5048 return ret;
5049}
5050
5051static int ufshcd_enable_vreg(struct device *dev, struct ufs_vreg *vreg)
5052{
5053 int ret = 0;
5054
60f01870
YG
5055 if (!vreg)
5056 goto out;
5057 else if (vreg->enabled || vreg->unused)
aa497613
SRT
5058 goto out;
5059
5060 ret = ufshcd_config_vreg(dev, vreg, true);
5061 if (!ret)
5062 ret = regulator_enable(vreg->reg);
5063
5064 if (!ret)
5065 vreg->enabled = true;
5066 else
5067 dev_err(dev, "%s: %s enable failed, err=%d\n",
5068 __func__, vreg->name, ret);
5069out:
5070 return ret;
5071}
5072
5073static int ufshcd_disable_vreg(struct device *dev, struct ufs_vreg *vreg)
5074{
5075 int ret = 0;
5076
60f01870
YG
5077 if (!vreg)
5078 goto out;
5079 else if (!vreg->enabled || vreg->unused)
aa497613
SRT
5080 goto out;
5081
5082 ret = regulator_disable(vreg->reg);
5083
5084 if (!ret) {
5085 /* ignore errors on applying disable config */
5086 ufshcd_config_vreg(dev, vreg, false);
5087 vreg->enabled = false;
5088 } else {
5089 dev_err(dev, "%s: %s disable failed, err=%d\n",
5090 __func__, vreg->name, ret);
5091 }
5092out:
5093 return ret;
5094}
5095
5096static int ufshcd_setup_vreg(struct ufs_hba *hba, bool on)
5097{
5098 int ret = 0;
5099 struct device *dev = hba->dev;
5100 struct ufs_vreg_info *info = &hba->vreg_info;
5101
5102 if (!info)
5103 goto out;
5104
5105 ret = ufshcd_toggle_vreg(dev, info->vcc, on);
5106 if (ret)
5107 goto out;
5108
5109 ret = ufshcd_toggle_vreg(dev, info->vccq, on);
5110 if (ret)
5111 goto out;
5112
5113 ret = ufshcd_toggle_vreg(dev, info->vccq2, on);
5114 if (ret)
5115 goto out;
5116
5117out:
5118 if (ret) {
5119 ufshcd_toggle_vreg(dev, info->vccq2, false);
5120 ufshcd_toggle_vreg(dev, info->vccq, false);
5121 ufshcd_toggle_vreg(dev, info->vcc, false);
5122 }
5123 return ret;
5124}
5125
6a771a65
RS
5126static int ufshcd_setup_hba_vreg(struct ufs_hba *hba, bool on)
5127{
5128 struct ufs_vreg_info *info = &hba->vreg_info;
5129
5130 if (info)
5131 return ufshcd_toggle_vreg(hba->dev, info->vdd_hba, on);
5132
5133 return 0;
5134}
5135
aa497613
SRT
5136static int ufshcd_get_vreg(struct device *dev, struct ufs_vreg *vreg)
5137{
5138 int ret = 0;
5139
5140 if (!vreg)
5141 goto out;
5142
5143 vreg->reg = devm_regulator_get(dev, vreg->name);
5144 if (IS_ERR(vreg->reg)) {
5145 ret = PTR_ERR(vreg->reg);
5146 dev_err(dev, "%s: %s get failed, err=%d\n",
5147 __func__, vreg->name, ret);
5148 }
5149out:
5150 return ret;
5151}
5152
5153static int ufshcd_init_vreg(struct ufs_hba *hba)
5154{
5155 int ret = 0;
5156 struct device *dev = hba->dev;
5157 struct ufs_vreg_info *info = &hba->vreg_info;
5158
5159 if (!info)
5160 goto out;
5161
5162 ret = ufshcd_get_vreg(dev, info->vcc);
5163 if (ret)
5164 goto out;
5165
5166 ret = ufshcd_get_vreg(dev, info->vccq);
5167 if (ret)
5168 goto out;
5169
5170 ret = ufshcd_get_vreg(dev, info->vccq2);
5171out:
5172 return ret;
5173}
5174
6a771a65
RS
5175static int ufshcd_init_hba_vreg(struct ufs_hba *hba)
5176{
5177 struct ufs_vreg_info *info = &hba->vreg_info;
5178
5179 if (info)
5180 return ufshcd_get_vreg(hba->dev, info->vdd_hba);
5181
5182 return 0;
5183}
5184
60f01870
YG
5185static int ufshcd_set_vccq_rail_unused(struct ufs_hba *hba, bool unused)
5186{
5187 int ret = 0;
5188 struct ufs_vreg_info *info = &hba->vreg_info;
5189
5190 if (!info)
5191 goto out;
5192 else if (!info->vccq)
5193 goto out;
5194
5195 if (unused) {
5196 /* shut off the rail here */
5197 ret = ufshcd_toggle_vreg(hba->dev, info->vccq, false);
5198 /*
5199 * Mark this rail as no longer used, so it doesn't get enabled
5200 * later by mistake
5201 */
5202 if (!ret)
5203 info->vccq->unused = true;
5204 } else {
5205 /*
5206 * rail should have been already enabled hence just make sure
5207 * that unused flag is cleared.
5208 */
5209 info->vccq->unused = false;
5210 }
5211out:
5212 return ret;
5213}
5214
57d104c1
SJ
5215static int __ufshcd_setup_clocks(struct ufs_hba *hba, bool on,
5216 bool skip_ref_clk)
c6e79dac
SRT
5217{
5218 int ret = 0;
5219 struct ufs_clk_info *clki;
5220 struct list_head *head = &hba->clk_list_head;
1ab27c9c 5221 unsigned long flags;
c6e79dac
SRT
5222
5223 if (!head || list_empty(head))
5224 goto out;
5225
5226 list_for_each_entry(clki, head, list) {
5227 if (!IS_ERR_OR_NULL(clki->clk)) {
57d104c1
SJ
5228 if (skip_ref_clk && !strcmp(clki->name, "ref_clk"))
5229 continue;
5230
c6e79dac
SRT
5231 if (on && !clki->enabled) {
5232 ret = clk_prepare_enable(clki->clk);
5233 if (ret) {
5234 dev_err(hba->dev, "%s: %s prepare enable failed, %d\n",
5235 __func__, clki->name, ret);
5236 goto out;
5237 }
5238 } else if (!on && clki->enabled) {
5239 clk_disable_unprepare(clki->clk);
5240 }
5241 clki->enabled = on;
5242 dev_dbg(hba->dev, "%s: clk: %s %sabled\n", __func__,
5243 clki->name, on ? "en" : "dis");
5244 }
5245 }
1ab27c9c 5246
0263bcd0 5247 ret = ufshcd_vops_setup_clocks(hba, on);
c6e79dac
SRT
5248out:
5249 if (ret) {
5250 list_for_each_entry(clki, head, list) {
5251 if (!IS_ERR_OR_NULL(clki->clk) && clki->enabled)
5252 clk_disable_unprepare(clki->clk);
5253 }
eda910e4 5254 } else if (on) {
1ab27c9c
ST
5255 spin_lock_irqsave(hba->host->host_lock, flags);
5256 hba->clk_gating.state = CLKS_ON;
5257 spin_unlock_irqrestore(hba->host->host_lock, flags);
c6e79dac
SRT
5258 }
5259 return ret;
5260}
5261
57d104c1
SJ
5262static int ufshcd_setup_clocks(struct ufs_hba *hba, bool on)
5263{
5264 return __ufshcd_setup_clocks(hba, on, false);
5265}
5266
c6e79dac
SRT
5267static int ufshcd_init_clocks(struct ufs_hba *hba)
5268{
5269 int ret = 0;
5270 struct ufs_clk_info *clki;
5271 struct device *dev = hba->dev;
5272 struct list_head *head = &hba->clk_list_head;
5273
5274 if (!head || list_empty(head))
5275 goto out;
5276
5277 list_for_each_entry(clki, head, list) {
5278 if (!clki->name)
5279 continue;
5280
5281 clki->clk = devm_clk_get(dev, clki->name);
5282 if (IS_ERR(clki->clk)) {
5283 ret = PTR_ERR(clki->clk);
5284 dev_err(dev, "%s: %s clk get failed, %d\n",
5285 __func__, clki->name, ret);
5286 goto out;
5287 }
5288
5289 if (clki->max_freq) {
5290 ret = clk_set_rate(clki->clk, clki->max_freq);
5291 if (ret) {
5292 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
5293 __func__, clki->name,
5294 clki->max_freq, ret);
5295 goto out;
5296 }
856b3483 5297 clki->curr_freq = clki->max_freq;
c6e79dac
SRT
5298 }
5299 dev_dbg(dev, "%s: clk: %s, rate: %lu\n", __func__,
5300 clki->name, clk_get_rate(clki->clk));
5301 }
5302out:
5303 return ret;
5304}
5305
5c0c28a8
SRT
5306static int ufshcd_variant_hba_init(struct ufs_hba *hba)
5307{
5308 int err = 0;
5309
5310 if (!hba->vops)
5311 goto out;
5312
0263bcd0
YG
5313 err = ufshcd_vops_init(hba);
5314 if (err)
5315 goto out;
5c0c28a8 5316
0263bcd0
YG
5317 err = ufshcd_vops_setup_regulators(hba, true);
5318 if (err)
5319 goto out_exit;
5c0c28a8
SRT
5320
5321 goto out;
5322
5c0c28a8 5323out_exit:
0263bcd0 5324 ufshcd_vops_exit(hba);
5c0c28a8
SRT
5325out:
5326 if (err)
5327 dev_err(hba->dev, "%s: variant %s init failed err %d\n",
0263bcd0 5328 __func__, ufshcd_get_var_name(hba), err);
5c0c28a8
SRT
5329 return err;
5330}
5331
5332static void ufshcd_variant_hba_exit(struct ufs_hba *hba)
5333{
5334 if (!hba->vops)
5335 return;
5336
0263bcd0 5337 ufshcd_vops_setup_clocks(hba, false);
5c0c28a8 5338
0263bcd0 5339 ufshcd_vops_setup_regulators(hba, false);
5c0c28a8 5340
0263bcd0 5341 ufshcd_vops_exit(hba);
5c0c28a8
SRT
5342}
5343
aa497613
SRT
5344static int ufshcd_hba_init(struct ufs_hba *hba)
5345{
5346 int err;
5347
6a771a65
RS
5348 /*
5349 * Handle host controller power separately from the UFS device power
5350 * rails as it will help controlling the UFS host controller power
5351 * collapse easily which is different than UFS device power collapse.
5352 * Also, enable the host controller power before we go ahead with rest
5353 * of the initialization here.
5354 */
5355 err = ufshcd_init_hba_vreg(hba);
aa497613
SRT
5356 if (err)
5357 goto out;
5358
6a771a65 5359 err = ufshcd_setup_hba_vreg(hba, true);
aa497613
SRT
5360 if (err)
5361 goto out;
5362
6a771a65
RS
5363 err = ufshcd_init_clocks(hba);
5364 if (err)
5365 goto out_disable_hba_vreg;
5366
5367 err = ufshcd_setup_clocks(hba, true);
5368 if (err)
5369 goto out_disable_hba_vreg;
5370
c6e79dac
SRT
5371 err = ufshcd_init_vreg(hba);
5372 if (err)
5373 goto out_disable_clks;
5374
5375 err = ufshcd_setup_vreg(hba, true);
5376 if (err)
5377 goto out_disable_clks;
5378
aa497613
SRT
5379 err = ufshcd_variant_hba_init(hba);
5380 if (err)
5381 goto out_disable_vreg;
5382
1d337ec2 5383 hba->is_powered = true;
aa497613
SRT
5384 goto out;
5385
5386out_disable_vreg:
5387 ufshcd_setup_vreg(hba, false);
c6e79dac
SRT
5388out_disable_clks:
5389 ufshcd_setup_clocks(hba, false);
6a771a65
RS
5390out_disable_hba_vreg:
5391 ufshcd_setup_hba_vreg(hba, false);
aa497613
SRT
5392out:
5393 return err;
5394}
5395
5396static void ufshcd_hba_exit(struct ufs_hba *hba)
5397{
1d337ec2
SRT
5398 if (hba->is_powered) {
5399 ufshcd_variant_hba_exit(hba);
5400 ufshcd_setup_vreg(hba, false);
5401 ufshcd_setup_clocks(hba, false);
5402 ufshcd_setup_hba_vreg(hba, false);
5403 hba->is_powered = false;
5404 }
aa497613
SRT
5405}
5406
57d104c1
SJ
5407static int
5408ufshcd_send_request_sense(struct ufs_hba *hba, struct scsi_device *sdp)
5409{
5410 unsigned char cmd[6] = {REQUEST_SENSE,
5411 0,
5412 0,
5413 0,
5414 SCSI_SENSE_BUFFERSIZE,
5415 0};
5416 char *buffer;
5417 int ret;
5418
5419 buffer = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_KERNEL);
5420 if (!buffer) {
5421 ret = -ENOMEM;
5422 goto out;
5423 }
5424
5425 ret = scsi_execute_req_flags(sdp, cmd, DMA_FROM_DEVICE, buffer,
5426 SCSI_SENSE_BUFFERSIZE, NULL,
5427 msecs_to_jiffies(1000), 3, NULL, REQ_PM);
5428 if (ret)
5429 pr_err("%s: failed with err %d\n", __func__, ret);
5430
5431 kfree(buffer);
5432out:
5433 return ret;
5434}
5435
5436/**
5437 * ufshcd_set_dev_pwr_mode - sends START STOP UNIT command to set device
5438 * power mode
5439 * @hba: per adapter instance
5440 * @pwr_mode: device power mode to set
5441 *
5442 * Returns 0 if requested power mode is set successfully
5443 * Returns non-zero if failed to set the requested power mode
5444 */
5445static int ufshcd_set_dev_pwr_mode(struct ufs_hba *hba,
5446 enum ufs_dev_pwr_mode pwr_mode)
5447{
5448 unsigned char cmd[6] = { START_STOP };
5449 struct scsi_sense_hdr sshdr;
7c48bfd0
AM
5450 struct scsi_device *sdp;
5451 unsigned long flags;
57d104c1
SJ
5452 int ret;
5453
7c48bfd0
AM
5454 spin_lock_irqsave(hba->host->host_lock, flags);
5455 sdp = hba->sdev_ufs_device;
5456 if (sdp) {
5457 ret = scsi_device_get(sdp);
5458 if (!ret && !scsi_device_online(sdp)) {
5459 ret = -ENODEV;
5460 scsi_device_put(sdp);
5461 }
5462 } else {
5463 ret = -ENODEV;
5464 }
5465 spin_unlock_irqrestore(hba->host->host_lock, flags);
5466
5467 if (ret)
5468 return ret;
57d104c1
SJ
5469
5470 /*
5471 * If scsi commands fail, the scsi mid-layer schedules scsi error-
5472 * handling, which would wait for host to be resumed. Since we know
5473 * we are functional while we are here, skip host resume in error
5474 * handling context.
5475 */
5476 hba->host->eh_noresume = 1;
5477 if (hba->wlun_dev_clr_ua) {
5478 ret = ufshcd_send_request_sense(hba, sdp);
5479 if (ret)
5480 goto out;
5481 /* Unit attention condition is cleared now */
5482 hba->wlun_dev_clr_ua = false;
5483 }
5484
5485 cmd[4] = pwr_mode << 4;
5486
5487 /*
5488 * Current function would be generally called from the power management
5489 * callbacks hence set the REQ_PM flag so that it doesn't resume the
5490 * already suspended childs.
5491 */
5492 ret = scsi_execute_req_flags(sdp, cmd, DMA_NONE, NULL, 0, &sshdr,
5493 START_STOP_TIMEOUT, 0, NULL, REQ_PM);
5494 if (ret) {
5495 sdev_printk(KERN_WARNING, sdp,
ef61329d
HR
5496 "START_STOP failed for power mode: %d, result %x\n",
5497 pwr_mode, ret);
21045519
HR
5498 if (driver_byte(ret) & DRIVER_SENSE)
5499 scsi_print_sense_hdr(sdp, NULL, &sshdr);
57d104c1
SJ
5500 }
5501
5502 if (!ret)
5503 hba->curr_dev_pwr_mode = pwr_mode;
5504out:
7c48bfd0 5505 scsi_device_put(sdp);
57d104c1
SJ
5506 hba->host->eh_noresume = 0;
5507 return ret;
5508}
5509
5510static int ufshcd_link_state_transition(struct ufs_hba *hba,
5511 enum uic_link_state req_link_state,
5512 int check_for_bkops)
5513{
5514 int ret = 0;
5515
5516 if (req_link_state == hba->uic_link_state)
5517 return 0;
5518
5519 if (req_link_state == UIC_LINK_HIBERN8_STATE) {
5520 ret = ufshcd_uic_hibern8_enter(hba);
5521 if (!ret)
5522 ufshcd_set_link_hibern8(hba);
5523 else
5524 goto out;
5525 }
5526 /*
5527 * If autobkops is enabled, link can't be turned off because
5528 * turning off the link would also turn off the device.
5529 */
5530 else if ((req_link_state == UIC_LINK_OFF_STATE) &&
5531 (!check_for_bkops || (check_for_bkops &&
5532 !hba->auto_bkops_enabled))) {
5533 /*
5534 * Change controller state to "reset state" which
5535 * should also put the link in off/reset state
5536 */
596585a2 5537 ufshcd_hba_stop(hba, true);
57d104c1
SJ
5538 /*
5539 * TODO: Check if we need any delay to make sure that
5540 * controller is reset
5541 */
5542 ufshcd_set_link_off(hba);
5543 }
5544
5545out:
5546 return ret;
5547}
5548
5549static void ufshcd_vreg_set_lpm(struct ufs_hba *hba)
5550{
5551 /*
5552 * If UFS device is either in UFS_Sleep turn off VCC rail to save some
5553 * power.
5554 *
5555 * If UFS device and link is in OFF state, all power supplies (VCC,
5556 * VCCQ, VCCQ2) can be turned off if power on write protect is not
5557 * required. If UFS link is inactive (Hibern8 or OFF state) and device
5558 * is in sleep state, put VCCQ & VCCQ2 rails in LPM mode.
5559 *
5560 * Ignore the error returned by ufshcd_toggle_vreg() as device is anyway
5561 * in low power state which would save some power.
5562 */
5563 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5564 !hba->dev_info.is_lu_power_on_wp) {
5565 ufshcd_setup_vreg(hba, false);
5566 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5567 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5568 if (!ufshcd_is_link_active(hba)) {
5569 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5570 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq2);
5571 }
5572 }
5573}
5574
5575static int ufshcd_vreg_set_hpm(struct ufs_hba *hba)
5576{
5577 int ret = 0;
5578
5579 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba) &&
5580 !hba->dev_info.is_lu_power_on_wp) {
5581 ret = ufshcd_setup_vreg(hba, true);
5582 } else if (!ufshcd_is_ufs_dev_active(hba)) {
5583 ret = ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, true);
5584 if (!ret && !ufshcd_is_link_active(hba)) {
5585 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq);
5586 if (ret)
5587 goto vcc_disable;
5588 ret = ufshcd_config_vreg_hpm(hba, hba->vreg_info.vccq2);
5589 if (ret)
5590 goto vccq_lpm;
5591 }
5592 }
5593 goto out;
5594
5595vccq_lpm:
5596 ufshcd_config_vreg_lpm(hba, hba->vreg_info.vccq);
5597vcc_disable:
5598 ufshcd_toggle_vreg(hba->dev, hba->vreg_info.vcc, false);
5599out:
5600 return ret;
5601}
5602
5603static void ufshcd_hba_vreg_set_lpm(struct ufs_hba *hba)
5604{
5605 if (ufshcd_is_link_off(hba))
5606 ufshcd_setup_hba_vreg(hba, false);
5607}
5608
5609static void ufshcd_hba_vreg_set_hpm(struct ufs_hba *hba)
5610{
5611 if (ufshcd_is_link_off(hba))
5612 ufshcd_setup_hba_vreg(hba, true);
5613}
5614
7a3e97b0 5615/**
57d104c1 5616 * ufshcd_suspend - helper function for suspend operations
3b1d0580 5617 * @hba: per adapter instance
57d104c1
SJ
5618 * @pm_op: desired low power operation type
5619 *
5620 * This function will try to put the UFS device and link into low power
5621 * mode based on the "rpm_lvl" (Runtime PM level) or "spm_lvl"
5622 * (System PM level).
5623 *
5624 * If this function is called during shutdown, it will make sure that
5625 * both UFS device and UFS link is powered off.
7a3e97b0 5626 *
57d104c1
SJ
5627 * NOTE: UFS device & link must be active before we enter in this function.
5628 *
5629 * Returns 0 for success and non-zero for failure
7a3e97b0 5630 */
57d104c1 5631static int ufshcd_suspend(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7a3e97b0 5632{
57d104c1
SJ
5633 int ret = 0;
5634 enum ufs_pm_level pm_lvl;
5635 enum ufs_dev_pwr_mode req_dev_pwr_mode;
5636 enum uic_link_state req_link_state;
5637
5638 hba->pm_op_in_progress = 1;
5639 if (!ufshcd_is_shutdown_pm(pm_op)) {
5640 pm_lvl = ufshcd_is_runtime_pm(pm_op) ?
5641 hba->rpm_lvl : hba->spm_lvl;
5642 req_dev_pwr_mode = ufs_get_pm_lvl_to_dev_pwr_mode(pm_lvl);
5643 req_link_state = ufs_get_pm_lvl_to_link_pwr_state(pm_lvl);
5644 } else {
5645 req_dev_pwr_mode = UFS_POWERDOWN_PWR_MODE;
5646 req_link_state = UIC_LINK_OFF_STATE;
5647 }
5648
7a3e97b0 5649 /*
57d104c1
SJ
5650 * If we can't transition into any of the low power modes
5651 * just gate the clocks.
7a3e97b0 5652 */
1ab27c9c
ST
5653 ufshcd_hold(hba, false);
5654 hba->clk_gating.is_suspended = true;
5655
57d104c1
SJ
5656 if (req_dev_pwr_mode == UFS_ACTIVE_PWR_MODE &&
5657 req_link_state == UIC_LINK_ACTIVE_STATE) {
5658 goto disable_clks;
5659 }
7a3e97b0 5660
57d104c1
SJ
5661 if ((req_dev_pwr_mode == hba->curr_dev_pwr_mode) &&
5662 (req_link_state == hba->uic_link_state))
5663 goto out;
5664
5665 /* UFS device & link must be active before we enter in this function */
5666 if (!ufshcd_is_ufs_dev_active(hba) || !ufshcd_is_link_active(hba)) {
5667 ret = -EINVAL;
5668 goto out;
5669 }
5670
5671 if (ufshcd_is_runtime_pm(pm_op)) {
374a246e
SJ
5672 if (ufshcd_can_autobkops_during_suspend(hba)) {
5673 /*
5674 * The device is idle with no requests in the queue,
5675 * allow background operations if bkops status shows
5676 * that performance might be impacted.
5677 */
5678 ret = ufshcd_urgent_bkops(hba);
5679 if (ret)
5680 goto enable_gating;
5681 } else {
5682 /* make sure that auto bkops is disabled */
5683 ufshcd_disable_auto_bkops(hba);
5684 }
57d104c1
SJ
5685 }
5686
5687 if ((req_dev_pwr_mode != hba->curr_dev_pwr_mode) &&
5688 ((ufshcd_is_runtime_pm(pm_op) && !hba->auto_bkops_enabled) ||
5689 !ufshcd_is_runtime_pm(pm_op))) {
5690 /* ensure that bkops is disabled */
5691 ufshcd_disable_auto_bkops(hba);
5692 ret = ufshcd_set_dev_pwr_mode(hba, req_dev_pwr_mode);
5693 if (ret)
1ab27c9c 5694 goto enable_gating;
57d104c1
SJ
5695 }
5696
5697 ret = ufshcd_link_state_transition(hba, req_link_state, 1);
5698 if (ret)
5699 goto set_dev_active;
5700
5701 ufshcd_vreg_set_lpm(hba);
5702
5703disable_clks:
856b3483
ST
5704 /*
5705 * The clock scaling needs access to controller registers. Hence, Wait
5706 * for pending clock scaling work to be done before clocks are
5707 * turned off.
5708 */
5709 if (ufshcd_is_clkscaling_enabled(hba)) {
5710 devfreq_suspend_device(hba->devfreq);
5711 hba->clk_scaling.window_start_t = 0;
5712 }
57d104c1
SJ
5713 /*
5714 * Call vendor specific suspend callback. As these callbacks may access
5715 * vendor specific host controller register space call them before the
5716 * host clocks are ON.
5717 */
0263bcd0
YG
5718 ret = ufshcd_vops_suspend(hba, pm_op);
5719 if (ret)
5720 goto set_link_active;
57d104c1 5721
0263bcd0
YG
5722 ret = ufshcd_vops_setup_clocks(hba, false);
5723 if (ret)
5724 goto vops_resume;
57d104c1
SJ
5725
5726 if (!ufshcd_is_link_active(hba))
5727 ufshcd_setup_clocks(hba, false);
5728 else
5729 /* If link is active, device ref_clk can't be switched off */
5730 __ufshcd_setup_clocks(hba, false, true);
5731
1ab27c9c 5732 hba->clk_gating.state = CLKS_OFF;
57d104c1
SJ
5733 /*
5734 * Disable the host irq as host controller as there won't be any
0263bcd0 5735 * host controller transaction expected till resume.
57d104c1
SJ
5736 */
5737 ufshcd_disable_irq(hba);
5738 /* Put the host controller in low power mode if possible */
5739 ufshcd_hba_vreg_set_lpm(hba);
5740 goto out;
5741
5742vops_resume:
0263bcd0 5743 ufshcd_vops_resume(hba, pm_op);
57d104c1
SJ
5744set_link_active:
5745 ufshcd_vreg_set_hpm(hba);
5746 if (ufshcd_is_link_hibern8(hba) && !ufshcd_uic_hibern8_exit(hba))
5747 ufshcd_set_link_active(hba);
5748 else if (ufshcd_is_link_off(hba))
5749 ufshcd_host_reset_and_restore(hba);
5750set_dev_active:
5751 if (!ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE))
5752 ufshcd_disable_auto_bkops(hba);
1ab27c9c
ST
5753enable_gating:
5754 hba->clk_gating.is_suspended = false;
5755 ufshcd_release(hba);
57d104c1
SJ
5756out:
5757 hba->pm_op_in_progress = 0;
5758 return ret;
7a3e97b0
SY
5759}
5760
5761/**
57d104c1 5762 * ufshcd_resume - helper function for resume operations
3b1d0580 5763 * @hba: per adapter instance
57d104c1 5764 * @pm_op: runtime PM or system PM
7a3e97b0 5765 *
57d104c1
SJ
5766 * This function basically brings the UFS device, UniPro link and controller
5767 * to active state.
5768 *
5769 * Returns 0 for success and non-zero for failure
7a3e97b0 5770 */
57d104c1 5771static int ufshcd_resume(struct ufs_hba *hba, enum ufs_pm_op pm_op)
7a3e97b0 5772{
57d104c1
SJ
5773 int ret;
5774 enum uic_link_state old_link_state;
5775
5776 hba->pm_op_in_progress = 1;
5777 old_link_state = hba->uic_link_state;
5778
5779 ufshcd_hba_vreg_set_hpm(hba);
5780 /* Make sure clocks are enabled before accessing controller */
5781 ret = ufshcd_setup_clocks(hba, true);
5782 if (ret)
5783 goto out;
5784
57d104c1
SJ
5785 /* enable the host irq as host controller would be active soon */
5786 ret = ufshcd_enable_irq(hba);
5787 if (ret)
5788 goto disable_irq_and_vops_clks;
5789
5790 ret = ufshcd_vreg_set_hpm(hba);
5791 if (ret)
5792 goto disable_irq_and_vops_clks;
5793
7a3e97b0 5794 /*
57d104c1
SJ
5795 * Call vendor specific resume callback. As these callbacks may access
5796 * vendor specific host controller register space call them when the
5797 * host clocks are ON.
7a3e97b0 5798 */
0263bcd0
YG
5799 ret = ufshcd_vops_resume(hba, pm_op);
5800 if (ret)
5801 goto disable_vreg;
57d104c1
SJ
5802
5803 if (ufshcd_is_link_hibern8(hba)) {
5804 ret = ufshcd_uic_hibern8_exit(hba);
5805 if (!ret)
5806 ufshcd_set_link_active(hba);
5807 else
5808 goto vendor_suspend;
5809 } else if (ufshcd_is_link_off(hba)) {
5810 ret = ufshcd_host_reset_and_restore(hba);
5811 /*
5812 * ufshcd_host_reset_and_restore() should have already
5813 * set the link state as active
5814 */
5815 if (ret || !ufshcd_is_link_active(hba))
5816 goto vendor_suspend;
5817 }
5818
5819 if (!ufshcd_is_ufs_dev_active(hba)) {
5820 ret = ufshcd_set_dev_pwr_mode(hba, UFS_ACTIVE_PWR_MODE);
5821 if (ret)
5822 goto set_old_link_state;
5823 }
5824
374a246e
SJ
5825 /*
5826 * If BKOPs operations are urgently needed at this moment then
5827 * keep auto-bkops enabled or else disable it.
5828 */
5829 ufshcd_urgent_bkops(hba);
1ab27c9c
ST
5830 hba->clk_gating.is_suspended = false;
5831
856b3483
ST
5832 if (ufshcd_is_clkscaling_enabled(hba))
5833 devfreq_resume_device(hba->devfreq);
5834
1ab27c9c
ST
5835 /* Schedule clock gating in case of no access to UFS device yet */
5836 ufshcd_release(hba);
57d104c1
SJ
5837 goto out;
5838
5839set_old_link_state:
5840 ufshcd_link_state_transition(hba, old_link_state, 0);
5841vendor_suspend:
0263bcd0 5842 ufshcd_vops_suspend(hba, pm_op);
57d104c1
SJ
5843disable_vreg:
5844 ufshcd_vreg_set_lpm(hba);
5845disable_irq_and_vops_clks:
5846 ufshcd_disable_irq(hba);
57d104c1
SJ
5847 ufshcd_setup_clocks(hba, false);
5848out:
5849 hba->pm_op_in_progress = 0;
5850 return ret;
5851}
5852
5853/**
5854 * ufshcd_system_suspend - system suspend routine
5855 * @hba: per adapter instance
5856 * @pm_op: runtime PM or system PM
5857 *
5858 * Check the description of ufshcd_suspend() function for more details.
5859 *
5860 * Returns 0 for success and non-zero for failure
5861 */
5862int ufshcd_system_suspend(struct ufs_hba *hba)
5863{
5864 int ret = 0;
5865
5866 if (!hba || !hba->is_powered)
233b594b 5867 return 0;
57d104c1
SJ
5868
5869 if (pm_runtime_suspended(hba->dev)) {
5870 if (hba->rpm_lvl == hba->spm_lvl)
5871 /*
5872 * There is possibility that device may still be in
5873 * active state during the runtime suspend.
5874 */
5875 if ((ufs_get_pm_lvl_to_dev_pwr_mode(hba->spm_lvl) ==
5876 hba->curr_dev_pwr_mode) && !hba->auto_bkops_enabled)
5877 goto out;
5878
5879 /*
5880 * UFS device and/or UFS link low power states during runtime
5881 * suspend seems to be different than what is expected during
5882 * system suspend. Hence runtime resume the devic & link and
5883 * let the system suspend low power states to take effect.
5884 * TODO: If resume takes longer time, we might have optimize
5885 * it in future by not resuming everything if possible.
5886 */
5887 ret = ufshcd_runtime_resume(hba);
5888 if (ret)
5889 goto out;
5890 }
5891
5892 ret = ufshcd_suspend(hba, UFS_SYSTEM_PM);
5893out:
e785060e
DR
5894 if (!ret)
5895 hba->is_sys_suspended = true;
57d104c1
SJ
5896 return ret;
5897}
5898EXPORT_SYMBOL(ufshcd_system_suspend);
5899
5900/**
5901 * ufshcd_system_resume - system resume routine
5902 * @hba: per adapter instance
5903 *
5904 * Returns 0 for success and non-zero for failure
5905 */
7a3e97b0 5906
57d104c1
SJ
5907int ufshcd_system_resume(struct ufs_hba *hba)
5908{
5909 if (!hba || !hba->is_powered || pm_runtime_suspended(hba->dev))
5910 /*
5911 * Let the runtime resume take care of resuming
5912 * if runtime suspended.
5913 */
5914 return 0;
5915
5916 return ufshcd_resume(hba, UFS_SYSTEM_PM);
7a3e97b0 5917}
57d104c1 5918EXPORT_SYMBOL(ufshcd_system_resume);
3b1d0580 5919
57d104c1
SJ
5920/**
5921 * ufshcd_runtime_suspend - runtime suspend routine
5922 * @hba: per adapter instance
5923 *
5924 * Check the description of ufshcd_suspend() function for more details.
5925 *
5926 * Returns 0 for success and non-zero for failure
5927 */
66ec6d59
SRT
5928int ufshcd_runtime_suspend(struct ufs_hba *hba)
5929{
57d104c1 5930 if (!hba || !hba->is_powered)
66ec6d59
SRT
5931 return 0;
5932
57d104c1 5933 return ufshcd_suspend(hba, UFS_RUNTIME_PM);
66ec6d59
SRT
5934}
5935EXPORT_SYMBOL(ufshcd_runtime_suspend);
5936
57d104c1
SJ
5937/**
5938 * ufshcd_runtime_resume - runtime resume routine
5939 * @hba: per adapter instance
5940 *
5941 * This function basically brings the UFS device, UniPro link and controller
5942 * to active state. Following operations are done in this function:
5943 *
5944 * 1. Turn on all the controller related clocks
5945 * 2. Bring the UniPro link out of Hibernate state
5946 * 3. If UFS device is in sleep state, turn ON VCC rail and bring the UFS device
5947 * to active state.
5948 * 4. If auto-bkops is enabled on the device, disable it.
5949 *
5950 * So following would be the possible power state after this function return
5951 * successfully:
5952 * S1: UFS device in Active state with VCC rail ON
5953 * UniPro link in Active state
5954 * All the UFS/UniPro controller clocks are ON
5955 *
5956 * Returns 0 for success and non-zero for failure
5957 */
66ec6d59
SRT
5958int ufshcd_runtime_resume(struct ufs_hba *hba)
5959{
57d104c1 5960 if (!hba || !hba->is_powered)
66ec6d59 5961 return 0;
57d104c1
SJ
5962 else
5963 return ufshcd_resume(hba, UFS_RUNTIME_PM);
66ec6d59
SRT
5964}
5965EXPORT_SYMBOL(ufshcd_runtime_resume);
5966
5967int ufshcd_runtime_idle(struct ufs_hba *hba)
5968{
5969 return 0;
5970}
5971EXPORT_SYMBOL(ufshcd_runtime_idle);
5972
57d104c1
SJ
5973/**
5974 * ufshcd_shutdown - shutdown routine
5975 * @hba: per adapter instance
5976 *
5977 * This function would power off both UFS device and UFS link.
5978 *
5979 * Returns 0 always to allow force shutdown even in case of errors.
5980 */
5981int ufshcd_shutdown(struct ufs_hba *hba)
5982{
5983 int ret = 0;
5984
5985 if (ufshcd_is_ufs_dev_poweroff(hba) && ufshcd_is_link_off(hba))
5986 goto out;
5987
5988 if (pm_runtime_suspended(hba->dev)) {
5989 ret = ufshcd_runtime_resume(hba);
5990 if (ret)
5991 goto out;
5992 }
5993
5994 ret = ufshcd_suspend(hba, UFS_SHUTDOWN_PM);
5995out:
5996 if (ret)
5997 dev_err(hba->dev, "%s failed, err %d\n", __func__, ret);
5998 /* allow force shutdown even in case of errors */
5999 return 0;
6000}
6001EXPORT_SYMBOL(ufshcd_shutdown);
6002
7a3e97b0 6003/**
3b1d0580 6004 * ufshcd_remove - de-allocate SCSI host and host memory space
7a3e97b0 6005 * data structure memory
3b1d0580 6006 * @hba - per adapter instance
7a3e97b0 6007 */
3b1d0580 6008void ufshcd_remove(struct ufs_hba *hba)
7a3e97b0 6009{
cfdf9c91 6010 scsi_remove_host(hba->host);
7a3e97b0 6011 /* disable interrupts */
2fbd009b 6012 ufshcd_disable_intr(hba, hba->intr_mask);
596585a2 6013 ufshcd_hba_stop(hba, true);
7a3e97b0 6014
7a3e97b0 6015 scsi_host_put(hba->host);
5c0c28a8 6016
1ab27c9c 6017 ufshcd_exit_clk_gating(hba);
856b3483
ST
6018 if (ufshcd_is_clkscaling_enabled(hba))
6019 devfreq_remove_device(hba->devfreq);
aa497613 6020 ufshcd_hba_exit(hba);
3b1d0580
VH
6021}
6022EXPORT_SYMBOL_GPL(ufshcd_remove);
6023
47555a5c
YG
6024/**
6025 * ufshcd_dealloc_host - deallocate Host Bus Adapter (HBA)
6026 * @hba: pointer to Host Bus Adapter (HBA)
6027 */
6028void ufshcd_dealloc_host(struct ufs_hba *hba)
6029{
6030 scsi_host_put(hba->host);
6031}
6032EXPORT_SYMBOL_GPL(ufshcd_dealloc_host);
6033
ca3d7bf9
AM
6034/**
6035 * ufshcd_set_dma_mask - Set dma mask based on the controller
6036 * addressing capability
6037 * @hba: per adapter instance
6038 *
6039 * Returns 0 for success, non-zero for failure
6040 */
6041static int ufshcd_set_dma_mask(struct ufs_hba *hba)
6042{
6043 if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
6044 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
6045 return 0;
6046 }
6047 return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
6048}
6049
7a3e97b0 6050/**
5c0c28a8 6051 * ufshcd_alloc_host - allocate Host Bus Adapter (HBA)
3b1d0580
VH
6052 * @dev: pointer to device handle
6053 * @hba_handle: driver private handle
7a3e97b0
SY
6054 * Returns 0 on success, non-zero value on failure
6055 */
5c0c28a8 6056int ufshcd_alloc_host(struct device *dev, struct ufs_hba **hba_handle)
7a3e97b0
SY
6057{
6058 struct Scsi_Host *host;
6059 struct ufs_hba *hba;
5c0c28a8 6060 int err = 0;
7a3e97b0 6061
3b1d0580
VH
6062 if (!dev) {
6063 dev_err(dev,
6064 "Invalid memory reference for dev is NULL\n");
6065 err = -ENODEV;
7a3e97b0
SY
6066 goto out_error;
6067 }
6068
7a3e97b0
SY
6069 host = scsi_host_alloc(&ufshcd_driver_template,
6070 sizeof(struct ufs_hba));
6071 if (!host) {
3b1d0580 6072 dev_err(dev, "scsi_host_alloc failed\n");
7a3e97b0 6073 err = -ENOMEM;
3b1d0580 6074 goto out_error;
7a3e97b0
SY
6075 }
6076 hba = shost_priv(host);
7a3e97b0 6077 hba->host = host;
3b1d0580 6078 hba->dev = dev;
5c0c28a8
SRT
6079 *hba_handle = hba;
6080
6081out_error:
6082 return err;
6083}
6084EXPORT_SYMBOL(ufshcd_alloc_host);
6085
856b3483
ST
6086static int ufshcd_scale_clks(struct ufs_hba *hba, bool scale_up)
6087{
6088 int ret = 0;
6089 struct ufs_clk_info *clki;
6090 struct list_head *head = &hba->clk_list_head;
6091
6092 if (!head || list_empty(head))
6093 goto out;
6094
f06fcc71
YG
6095 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, PRE_CHANGE);
6096 if (ret)
6097 return ret;
6098
856b3483
ST
6099 list_for_each_entry(clki, head, list) {
6100 if (!IS_ERR_OR_NULL(clki->clk)) {
6101 if (scale_up && clki->max_freq) {
6102 if (clki->curr_freq == clki->max_freq)
6103 continue;
6104 ret = clk_set_rate(clki->clk, clki->max_freq);
6105 if (ret) {
6106 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6107 __func__, clki->name,
6108 clki->max_freq, ret);
6109 break;
6110 }
6111 clki->curr_freq = clki->max_freq;
6112
6113 } else if (!scale_up && clki->min_freq) {
6114 if (clki->curr_freq == clki->min_freq)
6115 continue;
6116 ret = clk_set_rate(clki->clk, clki->min_freq);
6117 if (ret) {
6118 dev_err(hba->dev, "%s: %s clk set rate(%dHz) failed, %d\n",
6119 __func__, clki->name,
6120 clki->min_freq, ret);
6121 break;
6122 }
6123 clki->curr_freq = clki->min_freq;
6124 }
6125 }
6126 dev_dbg(hba->dev, "%s: clk: %s, rate: %lu\n", __func__,
6127 clki->name, clk_get_rate(clki->clk));
6128 }
f06fcc71
YG
6129
6130 ret = ufshcd_vops_clk_scale_notify(hba, scale_up, POST_CHANGE);
6131
856b3483
ST
6132out:
6133 return ret;
6134}
6135
6136static int ufshcd_devfreq_target(struct device *dev,
6137 unsigned long *freq, u32 flags)
6138{
6139 int err = 0;
6140 struct ufs_hba *hba = dev_get_drvdata(dev);
6141
6142 if (!ufshcd_is_clkscaling_enabled(hba))
6143 return -EINVAL;
6144
6145 if (*freq == UINT_MAX)
6146 err = ufshcd_scale_clks(hba, true);
6147 else if (*freq == 0)
6148 err = ufshcd_scale_clks(hba, false);
6149
6150 return err;
6151}
6152
6153static int ufshcd_devfreq_get_dev_status(struct device *dev,
6154 struct devfreq_dev_status *stat)
6155{
6156 struct ufs_hba *hba = dev_get_drvdata(dev);
6157 struct ufs_clk_scaling *scaling = &hba->clk_scaling;
6158 unsigned long flags;
6159
6160 if (!ufshcd_is_clkscaling_enabled(hba))
6161 return -EINVAL;
6162
6163 memset(stat, 0, sizeof(*stat));
6164
6165 spin_lock_irqsave(hba->host->host_lock, flags);
6166 if (!scaling->window_start_t)
6167 goto start_window;
6168
6169 if (scaling->is_busy_started)
6170 scaling->tot_busy_t += ktime_to_us(ktime_sub(ktime_get(),
6171 scaling->busy_start_t));
6172
6173 stat->total_time = jiffies_to_usecs((long)jiffies -
6174 (long)scaling->window_start_t);
6175 stat->busy_time = scaling->tot_busy_t;
6176start_window:
6177 scaling->window_start_t = jiffies;
6178 scaling->tot_busy_t = 0;
6179
6180 if (hba->outstanding_reqs) {
6181 scaling->busy_start_t = ktime_get();
6182 scaling->is_busy_started = true;
6183 } else {
6184 scaling->busy_start_t = ktime_set(0, 0);
6185 scaling->is_busy_started = false;
6186 }
6187 spin_unlock_irqrestore(hba->host->host_lock, flags);
6188 return 0;
6189}
6190
6191static struct devfreq_dev_profile ufs_devfreq_profile = {
6192 .polling_ms = 100,
6193 .target = ufshcd_devfreq_target,
6194 .get_dev_status = ufshcd_devfreq_get_dev_status,
6195};
6196
5c0c28a8
SRT
6197/**
6198 * ufshcd_init - Driver initialization routine
6199 * @hba: per-adapter instance
6200 * @mmio_base: base register address
6201 * @irq: Interrupt line of device
6202 * Returns 0 on success, non-zero value on failure
6203 */
6204int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
6205{
6206 int err;
6207 struct Scsi_Host *host = hba->host;
6208 struct device *dev = hba->dev;
6209
6210 if (!mmio_base) {
6211 dev_err(hba->dev,
6212 "Invalid memory reference for mmio_base is NULL\n");
6213 err = -ENODEV;
6214 goto out_error;
6215 }
6216
3b1d0580
VH
6217 hba->mmio_base = mmio_base;
6218 hba->irq = irq;
7a3e97b0 6219
aa497613 6220 err = ufshcd_hba_init(hba);
5c0c28a8
SRT
6221 if (err)
6222 goto out_error;
6223
7a3e97b0
SY
6224 /* Read capabilities registers */
6225 ufshcd_hba_capabilities(hba);
6226
6227 /* Get UFS version supported by the controller */
6228 hba->ufs_version = ufshcd_get_ufs_version(hba);
6229
2fbd009b
SJ
6230 /* Get Interrupt bit mask per version */
6231 hba->intr_mask = ufshcd_get_intr_mask(hba);
6232
ca3d7bf9
AM
6233 err = ufshcd_set_dma_mask(hba);
6234 if (err) {
6235 dev_err(hba->dev, "set dma mask failed\n");
6236 goto out_disable;
6237 }
6238
7a3e97b0
SY
6239 /* Allocate memory for host memory space */
6240 err = ufshcd_memory_alloc(hba);
6241 if (err) {
3b1d0580
VH
6242 dev_err(hba->dev, "Memory allocation failed\n");
6243 goto out_disable;
7a3e97b0
SY
6244 }
6245
6246 /* Configure LRB */
6247 ufshcd_host_memory_configure(hba);
6248
6249 host->can_queue = hba->nutrs;
6250 host->cmd_per_lun = hba->nutrs;
6251 host->max_id = UFSHCD_MAX_ID;
0ce147d4 6252 host->max_lun = UFS_MAX_LUNS;
7a3e97b0
SY
6253 host->max_channel = UFSHCD_MAX_CHANNEL;
6254 host->unique_id = host->host_no;
6255 host->max_cmd_len = MAX_CDB_SIZE;
6256
7eb584db
DR
6257 hba->max_pwr_info.is_valid = false;
6258
7a3e97b0 6259 /* Initailize wait queue for task management */
e2933132
SRT
6260 init_waitqueue_head(&hba->tm_wq);
6261 init_waitqueue_head(&hba->tm_tag_wq);
7a3e97b0
SY
6262
6263 /* Initialize work queues */
e8e7f271 6264 INIT_WORK(&hba->eh_work, ufshcd_err_handler);
66ec6d59 6265 INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
7a3e97b0 6266
6ccf44fe
SJ
6267 /* Initialize UIC command mutex */
6268 mutex_init(&hba->uic_cmd_mutex);
6269
5a0b0cb9
SRT
6270 /* Initialize mutex for device management commands */
6271 mutex_init(&hba->dev_cmd.lock);
6272
6273 /* Initialize device management tag acquire wait queue */
6274 init_waitqueue_head(&hba->dev_cmd.tag_wq);
6275
1ab27c9c 6276 ufshcd_init_clk_gating(hba);
199ef13c
YG
6277
6278 /*
6279 * In order to avoid any spurious interrupt immediately after
6280 * registering UFS controller interrupt handler, clear any pending UFS
6281 * interrupt status and disable all the UFS interrupts.
6282 */
6283 ufshcd_writel(hba, ufshcd_readl(hba, REG_INTERRUPT_STATUS),
6284 REG_INTERRUPT_STATUS);
6285 ufshcd_writel(hba, 0, REG_INTERRUPT_ENABLE);
6286 /*
6287 * Make sure that UFS interrupts are disabled and any pending interrupt
6288 * status is cleared before registering UFS interrupt handler.
6289 */
6290 mb();
6291
7a3e97b0 6292 /* IRQ registration */
2953f850 6293 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
7a3e97b0 6294 if (err) {
3b1d0580 6295 dev_err(hba->dev, "request irq failed\n");
1ab27c9c 6296 goto exit_gating;
57d104c1
SJ
6297 } else {
6298 hba->is_irq_enabled = true;
7a3e97b0
SY
6299 }
6300
3b1d0580 6301 err = scsi_add_host(host, hba->dev);
7a3e97b0 6302 if (err) {
3b1d0580 6303 dev_err(hba->dev, "scsi_add_host failed\n");
1ab27c9c 6304 goto exit_gating;
7a3e97b0
SY
6305 }
6306
6ccf44fe
SJ
6307 /* Host controller enable */
6308 err = ufshcd_hba_enable(hba);
7a3e97b0 6309 if (err) {
6ccf44fe 6310 dev_err(hba->dev, "Host controller enable failed\n");
3b1d0580 6311 goto out_remove_scsi_host;
7a3e97b0 6312 }
6ccf44fe 6313
856b3483
ST
6314 if (ufshcd_is_clkscaling_enabled(hba)) {
6315 hba->devfreq = devfreq_add_device(dev, &ufs_devfreq_profile,
6316 "simple_ondemand", NULL);
6317 if (IS_ERR(hba->devfreq)) {
6318 dev_err(hba->dev, "Unable to register with devfreq %ld\n",
6319 PTR_ERR(hba->devfreq));
6320 goto out_remove_scsi_host;
6321 }
6322 /* Suspend devfreq until the UFS device is detected */
6323 devfreq_suspend_device(hba->devfreq);
6324 hba->clk_scaling.window_start_t = 0;
6325 }
6326
62694735
SRT
6327 /* Hold auto suspend until async scan completes */
6328 pm_runtime_get_sync(dev);
6329
57d104c1
SJ
6330 /*
6331 * The device-initialize-sequence hasn't been invoked yet.
6332 * Set the device to power-off state
6333 */
6334 ufshcd_set_ufs_dev_poweroff(hba);
6335
6ccf44fe
SJ
6336 async_schedule(ufshcd_async_scan, hba);
6337
7a3e97b0
SY
6338 return 0;
6339
3b1d0580
VH
6340out_remove_scsi_host:
6341 scsi_remove_host(hba->host);
1ab27c9c
ST
6342exit_gating:
6343 ufshcd_exit_clk_gating(hba);
3b1d0580 6344out_disable:
57d104c1 6345 hba->is_irq_enabled = false;
3b1d0580 6346 scsi_host_put(host);
aa497613 6347 ufshcd_hba_exit(hba);
3b1d0580
VH
6348out_error:
6349 return err;
6350}
6351EXPORT_SYMBOL_GPL(ufshcd_init);
6352
3b1d0580
VH
6353MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
6354MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
e0eca63e 6355MODULE_DESCRIPTION("Generic UFS host controller driver Core");
7a3e97b0
SY
6356MODULE_LICENSE("GPL");
6357MODULE_VERSION(UFSHCD_DRIVER_VERSION);