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