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