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