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