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