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