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