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