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