Merge tag 'hwspinlock-3.17' of git://git.kernel.org/pub/scm/linux/kernel/git/ohad...
[cascardo/linux.git] / drivers / scsi / ufs / ufshcd.c
1 /*
2  * Universal Flash Storage Host controller driver Core
3  *
4  * This code is based on drivers/scsi/ufs/ufshcd.c
5  * Copyright (C) 2011-2013 Samsung India Software Operations
6  *
7  * Authors:
8  *      Santosh Yaraganavi <santosh.sy@samsung.com>
9  *      Vinayak Holikatti <h.vinayak@samsung.com>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  * See the COPYING file in the top-level directory or visit
16  * <http://www.gnu.org/licenses/gpl-2.0.html>
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * This program is provided "AS IS" and "WITH ALL FAULTS" and
24  * without warranty of any kind. You are solely responsible for
25  * determining the appropriateness of using and distributing
26  * the program and assume all risks associated with your exercise
27  * of rights with respect to the program, including but not limited
28  * to infringement of third party rights, the risks and costs of
29  * program errors, damage to or loss of data, programs or equipment,
30  * and unavailability or interruption of operations. Under no
31  * circumstances will the contributor of this Program be liable for
32  * any damages of any kind arising from your use or distribution of
33  * this program.
34  */
35
36 #include <linux/async.h>
37
38 #include "ufshcd.h"
39 #include "unipro.h"
40
41 #define UFSHCD_ENABLE_INTRS     (UTP_TRANSFER_REQ_COMPL |\
42                                  UTP_TASK_REQ_COMPL |\
43                                  UIC_POWER_MODE |\
44                                  UFSHCD_ERROR_MASK)
45 /* UIC command timeout, unit: ms */
46 #define UIC_CMD_TIMEOUT 500
47
48 /* NOP OUT retries waiting for NOP IN response */
49 #define NOP_OUT_RETRIES    10
50 /* Timeout after 30 msecs if NOP OUT hangs without response */
51 #define NOP_OUT_TIMEOUT    30 /* msecs */
52
53 /* Query request retries */
54 #define QUERY_REQ_RETRIES 10
55 /* Query request timeout */
56 #define QUERY_REQ_TIMEOUT 30 /* msec */
57
58 /* Task management command timeout */
59 #define TM_CMD_TIMEOUT  100 /* msecs */
60
61 /* Expose the flag value from utp_upiu_query.value */
62 #define MASK_QUERY_UPIU_FLAG_LOC 0xFF
63
64 /* Interrupt aggregation default timeout, unit: 40us */
65 #define INT_AGGR_DEF_TO 0x02
66
67 enum {
68         UFSHCD_MAX_CHANNEL      = 0,
69         UFSHCD_MAX_ID           = 1,
70         UFSHCD_MAX_LUNS         = 8,
71         UFSHCD_CMD_PER_LUN      = 32,
72         UFSHCD_CAN_QUEUE        = 32,
73 };
74
75 /* UFSHCD states */
76 enum {
77         UFSHCD_STATE_RESET,
78         UFSHCD_STATE_ERROR,
79         UFSHCD_STATE_OPERATIONAL,
80 };
81
82 /* UFSHCD error handling flags */
83 enum {
84         UFSHCD_EH_IN_PROGRESS = (1 << 0),
85 };
86
87 /* UFSHCD UIC layer error flags */
88 enum {
89         UFSHCD_UIC_DL_PA_INIT_ERROR = (1 << 0), /* Data link layer error */
90         UFSHCD_UIC_NL_ERROR = (1 << 1), /* Network layer error */
91         UFSHCD_UIC_TL_ERROR = (1 << 2), /* Transport Layer error */
92         UFSHCD_UIC_DME_ERROR = (1 << 3), /* DME error */
93 };
94
95 /* Interrupt configuration options */
96 enum {
97         UFSHCD_INT_DISABLE,
98         UFSHCD_INT_ENABLE,
99         UFSHCD_INT_CLEAR,
100 };
101
102 #define ufshcd_set_eh_in_progress(h) \
103         (h->eh_flags |= UFSHCD_EH_IN_PROGRESS)
104 #define ufshcd_eh_in_progress(h) \
105         (h->eh_flags & UFSHCD_EH_IN_PROGRESS)
106 #define ufshcd_clear_eh_in_progress(h) \
107         (h->eh_flags &= ~UFSHCD_EH_IN_PROGRESS)
108
109 static void ufshcd_tmc_handler(struct ufs_hba *hba);
110 static void ufshcd_async_scan(void *data, async_cookie_t cookie);
111 static int ufshcd_reset_and_restore(struct ufs_hba *hba);
112 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag);
113 static int ufshcd_read_sdev_qdepth(struct ufs_hba *hba,
114                                         struct scsi_device *sdev);
115
116 /*
117  * ufshcd_wait_for_register - wait for register value to change
118  * @hba - per-adapter interface
119  * @reg - mmio register offset
120  * @mask - mask to apply to read register value
121  * @val - wait condition
122  * @interval_us - polling interval in microsecs
123  * @timeout_ms - timeout in millisecs
124  *
125  * Returns -ETIMEDOUT on error, zero on success
126  */
127 static int ufshcd_wait_for_register(struct ufs_hba *hba, u32 reg, u32 mask,
128                 u32 val, unsigned long interval_us, unsigned long timeout_ms)
129 {
130         int err = 0;
131         unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
132
133         /* ignore bits that we don't intend to wait on */
134         val = val & mask;
135
136         while ((ufshcd_readl(hba, reg) & mask) != val) {
137                 /* wakeup within 50us of expiry */
138                 usleep_range(interval_us, interval_us + 50);
139
140                 if (time_after(jiffies, timeout)) {
141                         if ((ufshcd_readl(hba, reg) & mask) != val)
142                                 err = -ETIMEDOUT;
143                         break;
144                 }
145         }
146
147         return err;
148 }
149
150 /**
151  * ufshcd_get_intr_mask - Get the interrupt bit mask
152  * @hba - Pointer to adapter instance
153  *
154  * Returns interrupt bit mask per version
155  */
156 static inline u32 ufshcd_get_intr_mask(struct ufs_hba *hba)
157 {
158         if (hba->ufs_version == UFSHCI_VERSION_10)
159                 return INTERRUPT_MASK_ALL_VER_10;
160         else
161                 return INTERRUPT_MASK_ALL_VER_11;
162 }
163
164 /**
165  * ufshcd_get_ufs_version - Get the UFS version supported by the HBA
166  * @hba - Pointer to adapter instance
167  *
168  * Returns UFSHCI version supported by the controller
169  */
170 static inline u32 ufshcd_get_ufs_version(struct ufs_hba *hba)
171 {
172         return ufshcd_readl(hba, REG_UFS_VERSION);
173 }
174
175 /**
176  * ufshcd_is_device_present - Check if any device connected to
177  *                            the host controller
178  * @reg_hcs - host controller status register value
179  *
180  * Returns 1 if device present, 0 if no device detected
181  */
182 static inline int ufshcd_is_device_present(u32 reg_hcs)
183 {
184         return (DEVICE_PRESENT & reg_hcs) ? 1 : 0;
185 }
186
187 /**
188  * ufshcd_get_tr_ocs - Get the UTRD Overall Command Status
189  * @lrb: pointer to local command reference block
190  *
191  * This function is used to get the OCS field from UTRD
192  * Returns the OCS field in the UTRD
193  */
194 static inline int ufshcd_get_tr_ocs(struct ufshcd_lrb *lrbp)
195 {
196         return le32_to_cpu(lrbp->utr_descriptor_ptr->header.dword_2) & MASK_OCS;
197 }
198
199 /**
200  * ufshcd_get_tmr_ocs - Get the UTMRD Overall Command Status
201  * @task_req_descp: pointer to utp_task_req_desc structure
202  *
203  * This function is used to get the OCS field from UTMRD
204  * Returns the OCS field in the UTMRD
205  */
206 static inline int
207 ufshcd_get_tmr_ocs(struct utp_task_req_desc *task_req_descp)
208 {
209         return le32_to_cpu(task_req_descp->header.dword_2) & MASK_OCS;
210 }
211
212 /**
213  * ufshcd_get_tm_free_slot - get a free slot for task management request
214  * @hba: per adapter instance
215  * @free_slot: pointer to variable with available slot value
216  *
217  * Get a free tag and lock it until ufshcd_put_tm_slot() is called.
218  * Returns 0 if free slot is not available, else return 1 with tag value
219  * in @free_slot.
220  */
221 static bool ufshcd_get_tm_free_slot(struct ufs_hba *hba, int *free_slot)
222 {
223         int tag;
224         bool ret = false;
225
226         if (!free_slot)
227                 goto out;
228
229         do {
230                 tag = find_first_zero_bit(&hba->tm_slots_in_use, hba->nutmrs);
231                 if (tag >= hba->nutmrs)
232                         goto out;
233         } while (test_and_set_bit_lock(tag, &hba->tm_slots_in_use));
234
235         *free_slot = tag;
236         ret = true;
237 out:
238         return ret;
239 }
240
241 static inline void ufshcd_put_tm_slot(struct ufs_hba *hba, int slot)
242 {
243         clear_bit_unlock(slot, &hba->tm_slots_in_use);
244 }
245
246 /**
247  * ufshcd_utrl_clear - Clear a bit in UTRLCLR register
248  * @hba: per adapter instance
249  * @pos: position of the bit to be cleared
250  */
251 static inline void ufshcd_utrl_clear(struct ufs_hba *hba, u32 pos)
252 {
253         ufshcd_writel(hba, ~(1 << pos), REG_UTP_TRANSFER_REQ_LIST_CLEAR);
254 }
255
256 /**
257  * ufshcd_get_lists_status - Check UCRDY, UTRLRDY and UTMRLRDY
258  * @reg: Register value of host controller status
259  *
260  * Returns integer, 0 on Success and positive value if failed
261  */
262 static inline int ufshcd_get_lists_status(u32 reg)
263 {
264         /*
265          * The mask 0xFF is for the following HCS register bits
266          * Bit          Description
267          *  0           Device Present
268          *  1           UTRLRDY
269          *  2           UTMRLRDY
270          *  3           UCRDY
271          *  4           HEI
272          *  5           DEI
273          * 6-7          reserved
274          */
275         return (((reg) & (0xFF)) >> 1) ^ (0x07);
276 }
277
278 /**
279  * ufshcd_get_uic_cmd_result - Get the UIC command result
280  * @hba: Pointer to adapter instance
281  *
282  * This function gets the result of UIC command completion
283  * Returns 0 on success, non zero value on error
284  */
285 static inline int ufshcd_get_uic_cmd_result(struct ufs_hba *hba)
286 {
287         return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_2) &
288                MASK_UIC_COMMAND_RESULT;
289 }
290
291 /**
292  * ufshcd_get_dme_attr_val - Get the value of attribute returned by UIC command
293  * @hba: Pointer to adapter instance
294  *
295  * This function gets UIC command argument3
296  * Returns 0 on success, non zero value on error
297  */
298 static inline u32 ufshcd_get_dme_attr_val(struct ufs_hba *hba)
299 {
300         return ufshcd_readl(hba, REG_UIC_COMMAND_ARG_3);
301 }
302
303 /**
304  * ufshcd_get_req_rsp - returns the TR response transaction type
305  * @ucd_rsp_ptr: pointer to response UPIU
306  */
307 static inline int
308 ufshcd_get_req_rsp(struct utp_upiu_rsp *ucd_rsp_ptr)
309 {
310         return be32_to_cpu(ucd_rsp_ptr->header.dword_0) >> 24;
311 }
312
313 /**
314  * ufshcd_get_rsp_upiu_result - Get the result from response UPIU
315  * @ucd_rsp_ptr: pointer to response UPIU
316  *
317  * This function gets the response status and scsi_status from response UPIU
318  * Returns the response result code.
319  */
320 static inline int
321 ufshcd_get_rsp_upiu_result(struct utp_upiu_rsp *ucd_rsp_ptr)
322 {
323         return be32_to_cpu(ucd_rsp_ptr->header.dword_1) & MASK_RSP_UPIU_RESULT;
324 }
325
326 /*
327  * ufshcd_get_rsp_upiu_data_seg_len - Get the data segment length
328  *                              from response UPIU
329  * @ucd_rsp_ptr: pointer to response UPIU
330  *
331  * Return the data segment length.
332  */
333 static inline unsigned int
334 ufshcd_get_rsp_upiu_data_seg_len(struct utp_upiu_rsp *ucd_rsp_ptr)
335 {
336         return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
337                 MASK_RSP_UPIU_DATA_SEG_LEN;
338 }
339
340 /**
341  * ufshcd_is_exception_event - Check if the device raised an exception event
342  * @ucd_rsp_ptr: pointer to response UPIU
343  *
344  * The function checks if the device raised an exception event indicated in
345  * the Device Information field of response UPIU.
346  *
347  * Returns true if exception is raised, false otherwise.
348  */
349 static inline bool ufshcd_is_exception_event(struct utp_upiu_rsp *ucd_rsp_ptr)
350 {
351         return be32_to_cpu(ucd_rsp_ptr->header.dword_2) &
352                         MASK_RSP_EXCEPTION_EVENT ? true : false;
353 }
354
355 /**
356  * ufshcd_reset_intr_aggr - Reset interrupt aggregation values.
357  * @hba: per adapter instance
358  */
359 static inline void
360 ufshcd_reset_intr_aggr(struct ufs_hba *hba)
361 {
362         ufshcd_writel(hba, INT_AGGR_ENABLE |
363                       INT_AGGR_COUNTER_AND_TIMER_RESET,
364                       REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
365 }
366
367 /**
368  * ufshcd_config_intr_aggr - Configure interrupt aggregation values.
369  * @hba: per adapter instance
370  * @cnt: Interrupt aggregation counter threshold
371  * @tmout: Interrupt aggregation timeout value
372  */
373 static inline void
374 ufshcd_config_intr_aggr(struct ufs_hba *hba, u8 cnt, u8 tmout)
375 {
376         ufshcd_writel(hba, INT_AGGR_ENABLE | INT_AGGR_PARAM_WRITE |
377                       INT_AGGR_COUNTER_THLD_VAL(cnt) |
378                       INT_AGGR_TIMEOUT_VAL(tmout),
379                       REG_UTP_TRANSFER_REQ_INT_AGG_CONTROL);
380 }
381
382 /**
383  * ufshcd_enable_run_stop_reg - Enable run-stop registers,
384  *                      When run-stop registers are set to 1, it indicates the
385  *                      host controller that it can process the requests
386  * @hba: per adapter instance
387  */
388 static void ufshcd_enable_run_stop_reg(struct ufs_hba *hba)
389 {
390         ufshcd_writel(hba, UTP_TASK_REQ_LIST_RUN_STOP_BIT,
391                       REG_UTP_TASK_REQ_LIST_RUN_STOP);
392         ufshcd_writel(hba, UTP_TRANSFER_REQ_LIST_RUN_STOP_BIT,
393                       REG_UTP_TRANSFER_REQ_LIST_RUN_STOP);
394 }
395
396 /**
397  * ufshcd_hba_start - Start controller initialization sequence
398  * @hba: per adapter instance
399  */
400 static inline void ufshcd_hba_start(struct ufs_hba *hba)
401 {
402         ufshcd_writel(hba, CONTROLLER_ENABLE, REG_CONTROLLER_ENABLE);
403 }
404
405 /**
406  * ufshcd_is_hba_active - Get controller state
407  * @hba: per adapter instance
408  *
409  * Returns zero if controller is active, 1 otherwise
410  */
411 static inline int ufshcd_is_hba_active(struct ufs_hba *hba)
412 {
413         return (ufshcd_readl(hba, REG_CONTROLLER_ENABLE) & 0x1) ? 0 : 1;
414 }
415
416 /**
417  * ufshcd_send_command - Send SCSI or device management commands
418  * @hba: per adapter instance
419  * @task_tag: Task tag of the command
420  */
421 static inline
422 void ufshcd_send_command(struct ufs_hba *hba, unsigned int task_tag)
423 {
424         __set_bit(task_tag, &hba->outstanding_reqs);
425         ufshcd_writel(hba, 1 << task_tag, REG_UTP_TRANSFER_REQ_DOOR_BELL);
426 }
427
428 /**
429  * ufshcd_copy_sense_data - Copy sense data in case of check condition
430  * @lrb - pointer to local reference block
431  */
432 static inline void ufshcd_copy_sense_data(struct ufshcd_lrb *lrbp)
433 {
434         int len;
435         if (lrbp->sense_buffer &&
436             ufshcd_get_rsp_upiu_data_seg_len(lrbp->ucd_rsp_ptr)) {
437                 len = be16_to_cpu(lrbp->ucd_rsp_ptr->sr.sense_data_len);
438                 memcpy(lrbp->sense_buffer,
439                         lrbp->ucd_rsp_ptr->sr.sense_data,
440                         min_t(int, len, SCSI_SENSE_BUFFERSIZE));
441         }
442 }
443
444 /**
445  * ufshcd_copy_query_response() - Copy the Query Response and the data
446  * descriptor
447  * @hba: per adapter instance
448  * @lrb - pointer to local reference block
449  */
450 static
451 int ufshcd_copy_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
452 {
453         struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
454
455         memcpy(&query_res->upiu_res, &lrbp->ucd_rsp_ptr->qr, QUERY_OSF_SIZE);
456
457         /* Get the descriptor */
458         if (lrbp->ucd_rsp_ptr->qr.opcode == UPIU_QUERY_OPCODE_READ_DESC) {
459                 u8 *descp = (u8 *)lrbp->ucd_rsp_ptr +
460                                 GENERAL_UPIU_REQUEST_SIZE;
461                 u16 resp_len;
462                 u16 buf_len;
463
464                 /* data segment length */
465                 resp_len = be32_to_cpu(lrbp->ucd_rsp_ptr->header.dword_2) &
466                                                 MASK_QUERY_DATA_SEG_LEN;
467                 buf_len = be16_to_cpu(
468                                 hba->dev_cmd.query.request.upiu_req.length);
469                 if (likely(buf_len >= resp_len)) {
470                         memcpy(hba->dev_cmd.query.descriptor, descp, resp_len);
471                 } else {
472                         dev_warn(hba->dev,
473                                 "%s: Response size is bigger than buffer",
474                                 __func__);
475                         return -EINVAL;
476                 }
477         }
478
479         return 0;
480 }
481
482 /**
483  * ufshcd_hba_capabilities - Read controller capabilities
484  * @hba: per adapter instance
485  */
486 static inline void ufshcd_hba_capabilities(struct ufs_hba *hba)
487 {
488         hba->capabilities = ufshcd_readl(hba, REG_CONTROLLER_CAPABILITIES);
489
490         /* nutrs and nutmrs are 0 based values */
491         hba->nutrs = (hba->capabilities & MASK_TRANSFER_REQUESTS_SLOTS) + 1;
492         hba->nutmrs =
493         ((hba->capabilities & MASK_TASK_MANAGEMENT_REQUEST_SLOTS) >> 16) + 1;
494 }
495
496 /**
497  * ufshcd_ready_for_uic_cmd - Check if controller is ready
498  *                            to accept UIC commands
499  * @hba: per adapter instance
500  * Return true on success, else false
501  */
502 static inline bool ufshcd_ready_for_uic_cmd(struct ufs_hba *hba)
503 {
504         if (ufshcd_readl(hba, REG_CONTROLLER_STATUS) & UIC_COMMAND_READY)
505                 return true;
506         else
507                 return false;
508 }
509
510 /**
511  * ufshcd_get_upmcrs - Get the power mode change request status
512  * @hba: Pointer to adapter instance
513  *
514  * This function gets the UPMCRS field of HCS register
515  * Returns value of UPMCRS field
516  */
517 static inline u8 ufshcd_get_upmcrs(struct ufs_hba *hba)
518 {
519         return (ufshcd_readl(hba, REG_CONTROLLER_STATUS) >> 8) & 0x7;
520 }
521
522 /**
523  * ufshcd_dispatch_uic_cmd - Dispatch UIC commands to unipro layers
524  * @hba: per adapter instance
525  * @uic_cmd: UIC command
526  *
527  * Mutex must be held.
528  */
529 static inline void
530 ufshcd_dispatch_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
531 {
532         WARN_ON(hba->active_uic_cmd);
533
534         hba->active_uic_cmd = uic_cmd;
535
536         /* Write Args */
537         ufshcd_writel(hba, uic_cmd->argument1, REG_UIC_COMMAND_ARG_1);
538         ufshcd_writel(hba, uic_cmd->argument2, REG_UIC_COMMAND_ARG_2);
539         ufshcd_writel(hba, uic_cmd->argument3, REG_UIC_COMMAND_ARG_3);
540
541         /* Write UIC Cmd */
542         ufshcd_writel(hba, uic_cmd->command & COMMAND_OPCODE_MASK,
543                       REG_UIC_COMMAND);
544 }
545
546 /**
547  * ufshcd_wait_for_uic_cmd - Wait complectioin of UIC command
548  * @hba: per adapter instance
549  * @uic_command: UIC command
550  *
551  * Must be called with mutex held.
552  * Returns 0 only if success.
553  */
554 static int
555 ufshcd_wait_for_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
556 {
557         int ret;
558         unsigned long flags;
559
560         if (wait_for_completion_timeout(&uic_cmd->done,
561                                         msecs_to_jiffies(UIC_CMD_TIMEOUT)))
562                 ret = uic_cmd->argument2 & MASK_UIC_COMMAND_RESULT;
563         else
564                 ret = -ETIMEDOUT;
565
566         spin_lock_irqsave(hba->host->host_lock, flags);
567         hba->active_uic_cmd = NULL;
568         spin_unlock_irqrestore(hba->host->host_lock, flags);
569
570         return ret;
571 }
572
573 /**
574  * __ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
575  * @hba: per adapter instance
576  * @uic_cmd: UIC command
577  *
578  * Identical to ufshcd_send_uic_cmd() expect mutex. Must be called
579  * with mutex held.
580  * Returns 0 only if success.
581  */
582 static int
583 __ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
584 {
585         int ret;
586         unsigned long flags;
587
588         if (!ufshcd_ready_for_uic_cmd(hba)) {
589                 dev_err(hba->dev,
590                         "Controller not ready to accept UIC commands\n");
591                 return -EIO;
592         }
593
594         init_completion(&uic_cmd->done);
595
596         spin_lock_irqsave(hba->host->host_lock, flags);
597         ufshcd_dispatch_uic_cmd(hba, uic_cmd);
598         spin_unlock_irqrestore(hba->host->host_lock, flags);
599
600         ret = ufshcd_wait_for_uic_cmd(hba, uic_cmd);
601
602         return ret;
603 }
604
605 /**
606  * ufshcd_send_uic_cmd - Send UIC commands and retrieve the result
607  * @hba: per adapter instance
608  * @uic_cmd: UIC command
609  *
610  * Returns 0 only if success.
611  */
612 static int
613 ufshcd_send_uic_cmd(struct ufs_hba *hba, struct uic_command *uic_cmd)
614 {
615         int ret;
616
617         mutex_lock(&hba->uic_cmd_mutex);
618         ret = __ufshcd_send_uic_cmd(hba, uic_cmd);
619         mutex_unlock(&hba->uic_cmd_mutex);
620
621         return ret;
622 }
623
624 /**
625  * ufshcd_map_sg - Map scatter-gather list to prdt
626  * @lrbp - pointer to local reference block
627  *
628  * Returns 0 in case of success, non-zero value in case of failure
629  */
630 static int ufshcd_map_sg(struct ufshcd_lrb *lrbp)
631 {
632         struct ufshcd_sg_entry *prd_table;
633         struct scatterlist *sg;
634         struct scsi_cmnd *cmd;
635         int sg_segments;
636         int i;
637
638         cmd = lrbp->cmd;
639         sg_segments = scsi_dma_map(cmd);
640         if (sg_segments < 0)
641                 return sg_segments;
642
643         if (sg_segments) {
644                 lrbp->utr_descriptor_ptr->prd_table_length =
645                                         cpu_to_le16((u16) (sg_segments));
646
647                 prd_table = (struct ufshcd_sg_entry *)lrbp->ucd_prdt_ptr;
648
649                 scsi_for_each_sg(cmd, sg, sg_segments, i) {
650                         prd_table[i].size  =
651                                 cpu_to_le32(((u32) sg_dma_len(sg))-1);
652                         prd_table[i].base_addr =
653                                 cpu_to_le32(lower_32_bits(sg->dma_address));
654                         prd_table[i].upper_addr =
655                                 cpu_to_le32(upper_32_bits(sg->dma_address));
656                 }
657         } else {
658                 lrbp->utr_descriptor_ptr->prd_table_length = 0;
659         }
660
661         return 0;
662 }
663
664 /**
665  * ufshcd_enable_intr - enable interrupts
666  * @hba: per adapter instance
667  * @intrs: interrupt bits
668  */
669 static void ufshcd_enable_intr(struct ufs_hba *hba, u32 intrs)
670 {
671         u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
672
673         if (hba->ufs_version == UFSHCI_VERSION_10) {
674                 u32 rw;
675                 rw = set & INTERRUPT_MASK_RW_VER_10;
676                 set = rw | ((set ^ intrs) & intrs);
677         } else {
678                 set |= intrs;
679         }
680
681         ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
682 }
683
684 /**
685  * ufshcd_disable_intr - disable interrupts
686  * @hba: per adapter instance
687  * @intrs: interrupt bits
688  */
689 static void ufshcd_disable_intr(struct ufs_hba *hba, u32 intrs)
690 {
691         u32 set = ufshcd_readl(hba, REG_INTERRUPT_ENABLE);
692
693         if (hba->ufs_version == UFSHCI_VERSION_10) {
694                 u32 rw;
695                 rw = (set & INTERRUPT_MASK_RW_VER_10) &
696                         ~(intrs & INTERRUPT_MASK_RW_VER_10);
697                 set = rw | ((set & intrs) & ~INTERRUPT_MASK_RW_VER_10);
698
699         } else {
700                 set &= ~intrs;
701         }
702
703         ufshcd_writel(hba, set, REG_INTERRUPT_ENABLE);
704 }
705
706 /**
707  * ufshcd_prepare_req_desc_hdr() - Fills the requests header
708  * descriptor according to request
709  * @lrbp: pointer to local reference block
710  * @upiu_flags: flags required in the header
711  * @cmd_dir: requests data direction
712  */
713 static void ufshcd_prepare_req_desc_hdr(struct ufshcd_lrb *lrbp,
714                 u32 *upiu_flags, enum dma_data_direction cmd_dir)
715 {
716         struct utp_transfer_req_desc *req_desc = lrbp->utr_descriptor_ptr;
717         u32 data_direction;
718         u32 dword_0;
719
720         if (cmd_dir == DMA_FROM_DEVICE) {
721                 data_direction = UTP_DEVICE_TO_HOST;
722                 *upiu_flags = UPIU_CMD_FLAGS_READ;
723         } else if (cmd_dir == DMA_TO_DEVICE) {
724                 data_direction = UTP_HOST_TO_DEVICE;
725                 *upiu_flags = UPIU_CMD_FLAGS_WRITE;
726         } else {
727                 data_direction = UTP_NO_DATA_TRANSFER;
728                 *upiu_flags = UPIU_CMD_FLAGS_NONE;
729         }
730
731         dword_0 = data_direction | (lrbp->command_type
732                                 << UPIU_COMMAND_TYPE_OFFSET);
733         if (lrbp->intr_cmd)
734                 dword_0 |= UTP_REQ_DESC_INT_CMD;
735
736         /* Transfer request descriptor header fields */
737         req_desc->header.dword_0 = cpu_to_le32(dword_0);
738
739         /*
740          * assigning invalid value for command status. Controller
741          * updates OCS on command completion, with the command
742          * status
743          */
744         req_desc->header.dword_2 =
745                 cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
746 }
747
748 /**
749  * ufshcd_prepare_utp_scsi_cmd_upiu() - fills the utp_transfer_req_desc,
750  * for scsi commands
751  * @lrbp - local reference block pointer
752  * @upiu_flags - flags
753  */
754 static
755 void ufshcd_prepare_utp_scsi_cmd_upiu(struct ufshcd_lrb *lrbp, u32 upiu_flags)
756 {
757         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
758
759         /* command descriptor fields */
760         ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
761                                 UPIU_TRANSACTION_COMMAND, upiu_flags,
762                                 lrbp->lun, lrbp->task_tag);
763         ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
764                                 UPIU_COMMAND_SET_TYPE_SCSI, 0, 0, 0);
765
766         /* Total EHS length and Data segment length will be zero */
767         ucd_req_ptr->header.dword_2 = 0;
768
769         ucd_req_ptr->sc.exp_data_transfer_len =
770                 cpu_to_be32(lrbp->cmd->sdb.length);
771
772         memcpy(ucd_req_ptr->sc.cdb, lrbp->cmd->cmnd,
773                 (min_t(unsigned short, lrbp->cmd->cmd_len, MAX_CDB_SIZE)));
774 }
775
776 /**
777  * ufshcd_prepare_utp_query_req_upiu() - fills the utp_transfer_req_desc,
778  * for query requsts
779  * @hba: UFS hba
780  * @lrbp: local reference block pointer
781  * @upiu_flags: flags
782  */
783 static void ufshcd_prepare_utp_query_req_upiu(struct ufs_hba *hba,
784                                 struct ufshcd_lrb *lrbp, u32 upiu_flags)
785 {
786         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
787         struct ufs_query *query = &hba->dev_cmd.query;
788         u16 len = be16_to_cpu(query->request.upiu_req.length);
789         u8 *descp = (u8 *)lrbp->ucd_req_ptr + GENERAL_UPIU_REQUEST_SIZE;
790
791         /* Query request header */
792         ucd_req_ptr->header.dword_0 = UPIU_HEADER_DWORD(
793                         UPIU_TRANSACTION_QUERY_REQ, upiu_flags,
794                         lrbp->lun, lrbp->task_tag);
795         ucd_req_ptr->header.dword_1 = UPIU_HEADER_DWORD(
796                         0, query->request.query_func, 0, 0);
797
798         /* Data segment length */
799         ucd_req_ptr->header.dword_2 = UPIU_HEADER_DWORD(
800                         0, 0, len >> 8, (u8)len);
801
802         /* Copy the Query Request buffer as is */
803         memcpy(&ucd_req_ptr->qr, &query->request.upiu_req,
804                         QUERY_OSF_SIZE);
805
806         /* Copy the Descriptor */
807         if (query->request.upiu_req.opcode == UPIU_QUERY_OPCODE_WRITE_DESC)
808                 memcpy(descp, query->descriptor, len);
809
810 }
811
812 static inline void ufshcd_prepare_utp_nop_upiu(struct ufshcd_lrb *lrbp)
813 {
814         struct utp_upiu_req *ucd_req_ptr = lrbp->ucd_req_ptr;
815
816         memset(ucd_req_ptr, 0, sizeof(struct utp_upiu_req));
817
818         /* command descriptor fields */
819         ucd_req_ptr->header.dword_0 =
820                 UPIU_HEADER_DWORD(
821                         UPIU_TRANSACTION_NOP_OUT, 0, 0, lrbp->task_tag);
822 }
823
824 /**
825  * ufshcd_compose_upiu - form UFS Protocol Information Unit(UPIU)
826  * @hba - per adapter instance
827  * @lrb - pointer to local reference block
828  */
829 static int ufshcd_compose_upiu(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
830 {
831         u32 upiu_flags;
832         int ret = 0;
833
834         switch (lrbp->command_type) {
835         case UTP_CMD_TYPE_SCSI:
836                 if (likely(lrbp->cmd)) {
837                         ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags,
838                                         lrbp->cmd->sc_data_direction);
839                         ufshcd_prepare_utp_scsi_cmd_upiu(lrbp, upiu_flags);
840                 } else {
841                         ret = -EINVAL;
842                 }
843                 break;
844         case UTP_CMD_TYPE_DEV_MANAGE:
845                 ufshcd_prepare_req_desc_hdr(lrbp, &upiu_flags, DMA_NONE);
846                 if (hba->dev_cmd.type == DEV_CMD_TYPE_QUERY)
847                         ufshcd_prepare_utp_query_req_upiu(
848                                         hba, lrbp, upiu_flags);
849                 else if (hba->dev_cmd.type == DEV_CMD_TYPE_NOP)
850                         ufshcd_prepare_utp_nop_upiu(lrbp);
851                 else
852                         ret = -EINVAL;
853                 break;
854         case UTP_CMD_TYPE_UFS:
855                 /* For UFS native command implementation */
856                 ret = -ENOTSUPP;
857                 dev_err(hba->dev, "%s: UFS native command are not supported\n",
858                         __func__);
859                 break;
860         default:
861                 ret = -ENOTSUPP;
862                 dev_err(hba->dev, "%s: unknown command type: 0x%x\n",
863                                 __func__, lrbp->command_type);
864                 break;
865         } /* end of switch */
866
867         return ret;
868 }
869
870 /**
871  * ufshcd_queuecommand - main entry point for SCSI requests
872  * @cmd: command from SCSI Midlayer
873  * @done: call back function
874  *
875  * Returns 0 for success, non-zero in case of failure
876  */
877 static int ufshcd_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
878 {
879         struct ufshcd_lrb *lrbp;
880         struct ufs_hba *hba;
881         unsigned long flags;
882         int tag;
883         int err = 0;
884
885         hba = shost_priv(host);
886
887         tag = cmd->request->tag;
888
889         spin_lock_irqsave(hba->host->host_lock, flags);
890         switch (hba->ufshcd_state) {
891         case UFSHCD_STATE_OPERATIONAL:
892                 break;
893         case UFSHCD_STATE_RESET:
894                 err = SCSI_MLQUEUE_HOST_BUSY;
895                 goto out_unlock;
896         case UFSHCD_STATE_ERROR:
897                 set_host_byte(cmd, DID_ERROR);
898                 cmd->scsi_done(cmd);
899                 goto out_unlock;
900         default:
901                 dev_WARN_ONCE(hba->dev, 1, "%s: invalid state %d\n",
902                                 __func__, hba->ufshcd_state);
903                 set_host_byte(cmd, DID_BAD_TARGET);
904                 cmd->scsi_done(cmd);
905                 goto out_unlock;
906         }
907         spin_unlock_irqrestore(hba->host->host_lock, flags);
908
909         /* acquire the tag to make sure device cmds don't use it */
910         if (test_and_set_bit_lock(tag, &hba->lrb_in_use)) {
911                 /*
912                  * Dev manage command in progress, requeue the command.
913                  * Requeuing the command helps in cases where the request *may*
914                  * find different tag instead of waiting for dev manage command
915                  * completion.
916                  */
917                 err = SCSI_MLQUEUE_HOST_BUSY;
918                 goto out;
919         }
920
921         lrbp = &hba->lrb[tag];
922
923         WARN_ON(lrbp->cmd);
924         lrbp->cmd = cmd;
925         lrbp->sense_bufflen = SCSI_SENSE_BUFFERSIZE;
926         lrbp->sense_buffer = cmd->sense_buffer;
927         lrbp->task_tag = tag;
928         lrbp->lun = cmd->device->lun;
929         lrbp->intr_cmd = false;
930         lrbp->command_type = UTP_CMD_TYPE_SCSI;
931
932         /* form UPIU before issuing the command */
933         ufshcd_compose_upiu(hba, lrbp);
934         err = ufshcd_map_sg(lrbp);
935         if (err) {
936                 lrbp->cmd = NULL;
937                 clear_bit_unlock(tag, &hba->lrb_in_use);
938                 goto out;
939         }
940
941         /* issue command to the controller */
942         spin_lock_irqsave(hba->host->host_lock, flags);
943         ufshcd_send_command(hba, tag);
944 out_unlock:
945         spin_unlock_irqrestore(hba->host->host_lock, flags);
946 out:
947         return err;
948 }
949
950 static int ufshcd_compose_dev_cmd(struct ufs_hba *hba,
951                 struct ufshcd_lrb *lrbp, enum dev_cmd_type cmd_type, int tag)
952 {
953         lrbp->cmd = NULL;
954         lrbp->sense_bufflen = 0;
955         lrbp->sense_buffer = NULL;
956         lrbp->task_tag = tag;
957         lrbp->lun = 0; /* device management cmd is not specific to any LUN */
958         lrbp->command_type = UTP_CMD_TYPE_DEV_MANAGE;
959         lrbp->intr_cmd = true; /* No interrupt aggregation */
960         hba->dev_cmd.type = cmd_type;
961
962         return ufshcd_compose_upiu(hba, lrbp);
963 }
964
965 static int
966 ufshcd_clear_cmd(struct ufs_hba *hba, int tag)
967 {
968         int err = 0;
969         unsigned long flags;
970         u32 mask = 1 << tag;
971
972         /* clear outstanding transaction before retry */
973         spin_lock_irqsave(hba->host->host_lock, flags);
974         ufshcd_utrl_clear(hba, tag);
975         spin_unlock_irqrestore(hba->host->host_lock, flags);
976
977         /*
978          * wait for for h/w to clear corresponding bit in door-bell.
979          * max. wait is 1 sec.
980          */
981         err = ufshcd_wait_for_register(hba,
982                         REG_UTP_TRANSFER_REQ_DOOR_BELL,
983                         mask, ~mask, 1000, 1000);
984
985         return err;
986 }
987
988 static int
989 ufshcd_check_query_response(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
990 {
991         struct ufs_query_res *query_res = &hba->dev_cmd.query.response;
992
993         /* Get the UPIU response */
994         query_res->response = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr) >>
995                                 UPIU_RSP_CODE_OFFSET;
996         return query_res->response;
997 }
998
999 /**
1000  * ufshcd_dev_cmd_completion() - handles device management command responses
1001  * @hba: per adapter instance
1002  * @lrbp: pointer to local reference block
1003  */
1004 static int
1005 ufshcd_dev_cmd_completion(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
1006 {
1007         int resp;
1008         int err = 0;
1009
1010         resp = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
1011
1012         switch (resp) {
1013         case UPIU_TRANSACTION_NOP_IN:
1014                 if (hba->dev_cmd.type != DEV_CMD_TYPE_NOP) {
1015                         err = -EINVAL;
1016                         dev_err(hba->dev, "%s: unexpected response %x\n",
1017                                         __func__, resp);
1018                 }
1019                 break;
1020         case UPIU_TRANSACTION_QUERY_RSP:
1021                 err = ufshcd_check_query_response(hba, lrbp);
1022                 if (!err)
1023                         err = ufshcd_copy_query_response(hba, lrbp);
1024                 break;
1025         case UPIU_TRANSACTION_REJECT_UPIU:
1026                 /* TODO: handle Reject UPIU Response */
1027                 err = -EPERM;
1028                 dev_err(hba->dev, "%s: Reject UPIU not fully implemented\n",
1029                                 __func__);
1030                 break;
1031         default:
1032                 err = -EINVAL;
1033                 dev_err(hba->dev, "%s: Invalid device management cmd response: %x\n",
1034                                 __func__, resp);
1035                 break;
1036         }
1037
1038         return err;
1039 }
1040
1041 static int ufshcd_wait_for_dev_cmd(struct ufs_hba *hba,
1042                 struct ufshcd_lrb *lrbp, int max_timeout)
1043 {
1044         int err = 0;
1045         unsigned long time_left;
1046         unsigned long flags;
1047
1048         time_left = wait_for_completion_timeout(hba->dev_cmd.complete,
1049                         msecs_to_jiffies(max_timeout));
1050
1051         spin_lock_irqsave(hba->host->host_lock, flags);
1052         hba->dev_cmd.complete = NULL;
1053         if (likely(time_left)) {
1054                 err = ufshcd_get_tr_ocs(lrbp);
1055                 if (!err)
1056                         err = ufshcd_dev_cmd_completion(hba, lrbp);
1057         }
1058         spin_unlock_irqrestore(hba->host->host_lock, flags);
1059
1060         if (!time_left) {
1061                 err = -ETIMEDOUT;
1062                 if (!ufshcd_clear_cmd(hba, lrbp->task_tag))
1063                         /* sucessfully cleared the command, retry if needed */
1064                         err = -EAGAIN;
1065         }
1066
1067         return err;
1068 }
1069
1070 /**
1071  * ufshcd_get_dev_cmd_tag - Get device management command tag
1072  * @hba: per-adapter instance
1073  * @tag: pointer to variable with available slot value
1074  *
1075  * Get a free slot and lock it until device management command
1076  * completes.
1077  *
1078  * Returns false if free slot is unavailable for locking, else
1079  * return true with tag value in @tag.
1080  */
1081 static bool ufshcd_get_dev_cmd_tag(struct ufs_hba *hba, int *tag_out)
1082 {
1083         int tag;
1084         bool ret = false;
1085         unsigned long tmp;
1086
1087         if (!tag_out)
1088                 goto out;
1089
1090         do {
1091                 tmp = ~hba->lrb_in_use;
1092                 tag = find_last_bit(&tmp, hba->nutrs);
1093                 if (tag >= hba->nutrs)
1094                         goto out;
1095         } while (test_and_set_bit_lock(tag, &hba->lrb_in_use));
1096
1097         *tag_out = tag;
1098         ret = true;
1099 out:
1100         return ret;
1101 }
1102
1103 static inline void ufshcd_put_dev_cmd_tag(struct ufs_hba *hba, int tag)
1104 {
1105         clear_bit_unlock(tag, &hba->lrb_in_use);
1106 }
1107
1108 /**
1109  * ufshcd_exec_dev_cmd - API for sending device management requests
1110  * @hba - UFS hba
1111  * @cmd_type - specifies the type (NOP, Query...)
1112  * @timeout - time in seconds
1113  *
1114  * NOTE: Since there is only one available tag for device management commands,
1115  * it is expected you hold the hba->dev_cmd.lock mutex.
1116  */
1117 static int ufshcd_exec_dev_cmd(struct ufs_hba *hba,
1118                 enum dev_cmd_type cmd_type, int timeout)
1119 {
1120         struct ufshcd_lrb *lrbp;
1121         int err;
1122         int tag;
1123         struct completion wait;
1124         unsigned long flags;
1125
1126         /*
1127          * Get free slot, sleep if slots are unavailable.
1128          * Even though we use wait_event() which sleeps indefinitely,
1129          * the maximum wait time is bounded by SCSI request timeout.
1130          */
1131         wait_event(hba->dev_cmd.tag_wq, ufshcd_get_dev_cmd_tag(hba, &tag));
1132
1133         init_completion(&wait);
1134         lrbp = &hba->lrb[tag];
1135         WARN_ON(lrbp->cmd);
1136         err = ufshcd_compose_dev_cmd(hba, lrbp, cmd_type, tag);
1137         if (unlikely(err))
1138                 goto out_put_tag;
1139
1140         hba->dev_cmd.complete = &wait;
1141
1142         spin_lock_irqsave(hba->host->host_lock, flags);
1143         ufshcd_send_command(hba, tag);
1144         spin_unlock_irqrestore(hba->host->host_lock, flags);
1145
1146         err = ufshcd_wait_for_dev_cmd(hba, lrbp, timeout);
1147
1148 out_put_tag:
1149         ufshcd_put_dev_cmd_tag(hba, tag);
1150         wake_up(&hba->dev_cmd.tag_wq);
1151         return err;
1152 }
1153
1154 /**
1155  * ufshcd_init_query() - init the query response and request parameters
1156  * @hba: per-adapter instance
1157  * @request: address of the request pointer to be initialized
1158  * @response: address of the response pointer to be initialized
1159  * @opcode: operation to perform
1160  * @idn: flag idn to access
1161  * @index: LU number to access
1162  * @selector: query/flag/descriptor further identification
1163  */
1164 static inline void ufshcd_init_query(struct ufs_hba *hba,
1165                 struct ufs_query_req **request, struct ufs_query_res **response,
1166                 enum query_opcode opcode, u8 idn, u8 index, u8 selector)
1167 {
1168         *request = &hba->dev_cmd.query.request;
1169         *response = &hba->dev_cmd.query.response;
1170         memset(*request, 0, sizeof(struct ufs_query_req));
1171         memset(*response, 0, sizeof(struct ufs_query_res));
1172         (*request)->upiu_req.opcode = opcode;
1173         (*request)->upiu_req.idn = idn;
1174         (*request)->upiu_req.index = index;
1175         (*request)->upiu_req.selector = selector;
1176 }
1177
1178 /**
1179  * ufshcd_query_flag() - API function for sending flag query requests
1180  * hba: per-adapter instance
1181  * query_opcode: flag query to perform
1182  * idn: flag idn to access
1183  * flag_res: the flag value after the query request completes
1184  *
1185  * Returns 0 for success, non-zero in case of failure
1186  */
1187 static int ufshcd_query_flag(struct ufs_hba *hba, enum query_opcode opcode,
1188                         enum flag_idn idn, bool *flag_res)
1189 {
1190         struct ufs_query_req *request = NULL;
1191         struct ufs_query_res *response = NULL;
1192         int err, index = 0, selector = 0;
1193
1194         BUG_ON(!hba);
1195
1196         mutex_lock(&hba->dev_cmd.lock);
1197         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1198                         selector);
1199
1200         switch (opcode) {
1201         case UPIU_QUERY_OPCODE_SET_FLAG:
1202         case UPIU_QUERY_OPCODE_CLEAR_FLAG:
1203         case UPIU_QUERY_OPCODE_TOGGLE_FLAG:
1204                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1205                 break;
1206         case UPIU_QUERY_OPCODE_READ_FLAG:
1207                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1208                 if (!flag_res) {
1209                         /* No dummy reads */
1210                         dev_err(hba->dev, "%s: Invalid argument for read request\n",
1211                                         __func__);
1212                         err = -EINVAL;
1213                         goto out_unlock;
1214                 }
1215                 break;
1216         default:
1217                 dev_err(hba->dev,
1218                         "%s: Expected query flag opcode but got = %d\n",
1219                         __func__, opcode);
1220                 err = -EINVAL;
1221                 goto out_unlock;
1222         }
1223
1224         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1225
1226         if (err) {
1227                 dev_err(hba->dev,
1228                         "%s: Sending flag query for idn %d failed, err = %d\n",
1229                         __func__, idn, err);
1230                 goto out_unlock;
1231         }
1232
1233         if (flag_res)
1234                 *flag_res = (be32_to_cpu(response->upiu_res.value) &
1235                                 MASK_QUERY_UPIU_FLAG_LOC) & 0x1;
1236
1237 out_unlock:
1238         mutex_unlock(&hba->dev_cmd.lock);
1239         return err;
1240 }
1241
1242 /**
1243  * ufshcd_query_attr - API function for sending attribute requests
1244  * hba: per-adapter instance
1245  * opcode: attribute opcode
1246  * idn: attribute idn to access
1247  * index: index field
1248  * selector: selector field
1249  * attr_val: the attribute value after the query request completes
1250  *
1251  * Returns 0 for success, non-zero in case of failure
1252 */
1253 static int ufshcd_query_attr(struct ufs_hba *hba, enum query_opcode opcode,
1254                         enum attr_idn idn, u8 index, u8 selector, u32 *attr_val)
1255 {
1256         struct ufs_query_req *request = NULL;
1257         struct ufs_query_res *response = NULL;
1258         int err;
1259
1260         BUG_ON(!hba);
1261
1262         if (!attr_val) {
1263                 dev_err(hba->dev, "%s: attribute value required for opcode 0x%x\n",
1264                                 __func__, opcode);
1265                 err = -EINVAL;
1266                 goto out;
1267         }
1268
1269         mutex_lock(&hba->dev_cmd.lock);
1270         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1271                         selector);
1272
1273         switch (opcode) {
1274         case UPIU_QUERY_OPCODE_WRITE_ATTR:
1275                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1276                 request->upiu_req.value = cpu_to_be32(*attr_val);
1277                 break;
1278         case UPIU_QUERY_OPCODE_READ_ATTR:
1279                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1280                 break;
1281         default:
1282                 dev_err(hba->dev, "%s: Expected query attr opcode but got = 0x%.2x\n",
1283                                 __func__, opcode);
1284                 err = -EINVAL;
1285                 goto out_unlock;
1286         }
1287
1288         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1289
1290         if (err) {
1291                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1292                                 __func__, opcode, idn, err);
1293                 goto out_unlock;
1294         }
1295
1296         *attr_val = be32_to_cpu(response->upiu_res.value);
1297
1298 out_unlock:
1299         mutex_unlock(&hba->dev_cmd.lock);
1300 out:
1301         return err;
1302 }
1303
1304 /**
1305  * ufshcd_query_descriptor - API function for sending descriptor requests
1306  * hba: per-adapter instance
1307  * opcode: attribute opcode
1308  * idn: attribute idn to access
1309  * index: index field
1310  * selector: selector field
1311  * desc_buf: the buffer that contains the descriptor
1312  * buf_len: length parameter passed to the device
1313  *
1314  * Returns 0 for success, non-zero in case of failure.
1315  * The buf_len parameter will contain, on return, the length parameter
1316  * received on the response.
1317  */
1318 static int ufshcd_query_descriptor(struct ufs_hba *hba,
1319                         enum query_opcode opcode, enum desc_idn idn, u8 index,
1320                         u8 selector, u8 *desc_buf, int *buf_len)
1321 {
1322         struct ufs_query_req *request = NULL;
1323         struct ufs_query_res *response = NULL;
1324         int err;
1325
1326         BUG_ON(!hba);
1327
1328         if (!desc_buf) {
1329                 dev_err(hba->dev, "%s: descriptor buffer required for opcode 0x%x\n",
1330                                 __func__, opcode);
1331                 err = -EINVAL;
1332                 goto out;
1333         }
1334
1335         if (*buf_len <= QUERY_DESC_MIN_SIZE || *buf_len > QUERY_DESC_MAX_SIZE) {
1336                 dev_err(hba->dev, "%s: descriptor buffer size (%d) is out of range\n",
1337                                 __func__, *buf_len);
1338                 err = -EINVAL;
1339                 goto out;
1340         }
1341
1342         mutex_lock(&hba->dev_cmd.lock);
1343         ufshcd_init_query(hba, &request, &response, opcode, idn, index,
1344                         selector);
1345         hba->dev_cmd.query.descriptor = desc_buf;
1346         request->upiu_req.length = cpu_to_be16(*buf_len);
1347
1348         switch (opcode) {
1349         case UPIU_QUERY_OPCODE_WRITE_DESC:
1350                 request->query_func = UPIU_QUERY_FUNC_STANDARD_WRITE_REQUEST;
1351                 break;
1352         case UPIU_QUERY_OPCODE_READ_DESC:
1353                 request->query_func = UPIU_QUERY_FUNC_STANDARD_READ_REQUEST;
1354                 break;
1355         default:
1356                 dev_err(hba->dev,
1357                                 "%s: Expected query descriptor opcode but got = 0x%.2x\n",
1358                                 __func__, opcode);
1359                 err = -EINVAL;
1360                 goto out_unlock;
1361         }
1362
1363         err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_QUERY, QUERY_REQ_TIMEOUT);
1364
1365         if (err) {
1366                 dev_err(hba->dev, "%s: opcode 0x%.2x for idn %d failed, err = %d\n",
1367                                 __func__, opcode, idn, err);
1368                 goto out_unlock;
1369         }
1370
1371         hba->dev_cmd.query.descriptor = NULL;
1372         *buf_len = be16_to_cpu(response->upiu_res.length);
1373
1374 out_unlock:
1375         mutex_unlock(&hba->dev_cmd.lock);
1376 out:
1377         return err;
1378 }
1379
1380 /**
1381  * ufshcd_memory_alloc - allocate memory for host memory space data structures
1382  * @hba: per adapter instance
1383  *
1384  * 1. Allocate DMA memory for Command Descriptor array
1385  *      Each command descriptor consist of Command UPIU, Response UPIU and PRDT
1386  * 2. Allocate DMA memory for UTP Transfer Request Descriptor List (UTRDL).
1387  * 3. Allocate DMA memory for UTP Task Management Request Descriptor List
1388  *      (UTMRDL)
1389  * 4. Allocate memory for local reference block(lrb).
1390  *
1391  * Returns 0 for success, non-zero in case of failure
1392  */
1393 static int ufshcd_memory_alloc(struct ufs_hba *hba)
1394 {
1395         size_t utmrdl_size, utrdl_size, ucdl_size;
1396
1397         /* Allocate memory for UTP command descriptors */
1398         ucdl_size = (sizeof(struct utp_transfer_cmd_desc) * hba->nutrs);
1399         hba->ucdl_base_addr = dmam_alloc_coherent(hba->dev,
1400                                                   ucdl_size,
1401                                                   &hba->ucdl_dma_addr,
1402                                                   GFP_KERNEL);
1403
1404         /*
1405          * UFSHCI requires UTP command descriptor to be 128 byte aligned.
1406          * make sure hba->ucdl_dma_addr is aligned to PAGE_SIZE
1407          * if hba->ucdl_dma_addr is aligned to PAGE_SIZE, then it will
1408          * be aligned to 128 bytes as well
1409          */
1410         if (!hba->ucdl_base_addr ||
1411             WARN_ON(hba->ucdl_dma_addr & (PAGE_SIZE - 1))) {
1412                 dev_err(hba->dev,
1413                         "Command Descriptor Memory allocation failed\n");
1414                 goto out;
1415         }
1416
1417         /*
1418          * Allocate memory for UTP Transfer descriptors
1419          * UFSHCI requires 1024 byte alignment of UTRD
1420          */
1421         utrdl_size = (sizeof(struct utp_transfer_req_desc) * hba->nutrs);
1422         hba->utrdl_base_addr = dmam_alloc_coherent(hba->dev,
1423                                                    utrdl_size,
1424                                                    &hba->utrdl_dma_addr,
1425                                                    GFP_KERNEL);
1426         if (!hba->utrdl_base_addr ||
1427             WARN_ON(hba->utrdl_dma_addr & (PAGE_SIZE - 1))) {
1428                 dev_err(hba->dev,
1429                         "Transfer Descriptor Memory allocation failed\n");
1430                 goto out;
1431         }
1432
1433         /*
1434          * Allocate memory for UTP Task Management descriptors
1435          * UFSHCI requires 1024 byte alignment of UTMRD
1436          */
1437         utmrdl_size = sizeof(struct utp_task_req_desc) * hba->nutmrs;
1438         hba->utmrdl_base_addr = dmam_alloc_coherent(hba->dev,
1439                                                     utmrdl_size,
1440                                                     &hba->utmrdl_dma_addr,
1441                                                     GFP_KERNEL);
1442         if (!hba->utmrdl_base_addr ||
1443             WARN_ON(hba->utmrdl_dma_addr & (PAGE_SIZE - 1))) {
1444                 dev_err(hba->dev,
1445                 "Task Management Descriptor Memory allocation failed\n");
1446                 goto out;
1447         }
1448
1449         /* Allocate memory for local reference block */
1450         hba->lrb = devm_kzalloc(hba->dev,
1451                                 hba->nutrs * sizeof(struct ufshcd_lrb),
1452                                 GFP_KERNEL);
1453         if (!hba->lrb) {
1454                 dev_err(hba->dev, "LRB Memory allocation failed\n");
1455                 goto out;
1456         }
1457         return 0;
1458 out:
1459         return -ENOMEM;
1460 }
1461
1462 /**
1463  * ufshcd_host_memory_configure - configure local reference block with
1464  *                              memory offsets
1465  * @hba: per adapter instance
1466  *
1467  * Configure Host memory space
1468  * 1. Update Corresponding UTRD.UCDBA and UTRD.UCDBAU with UCD DMA
1469  * address.
1470  * 2. Update each UTRD with Response UPIU offset, Response UPIU length
1471  * and PRDT offset.
1472  * 3. Save the corresponding addresses of UTRD, UCD.CMD, UCD.RSP and UCD.PRDT
1473  * into local reference block.
1474  */
1475 static void ufshcd_host_memory_configure(struct ufs_hba *hba)
1476 {
1477         struct utp_transfer_cmd_desc *cmd_descp;
1478         struct utp_transfer_req_desc *utrdlp;
1479         dma_addr_t cmd_desc_dma_addr;
1480         dma_addr_t cmd_desc_element_addr;
1481         u16 response_offset;
1482         u16 prdt_offset;
1483         int cmd_desc_size;
1484         int i;
1485
1486         utrdlp = hba->utrdl_base_addr;
1487         cmd_descp = hba->ucdl_base_addr;
1488
1489         response_offset =
1490                 offsetof(struct utp_transfer_cmd_desc, response_upiu);
1491         prdt_offset =
1492                 offsetof(struct utp_transfer_cmd_desc, prd_table);
1493
1494         cmd_desc_size = sizeof(struct utp_transfer_cmd_desc);
1495         cmd_desc_dma_addr = hba->ucdl_dma_addr;
1496
1497         for (i = 0; i < hba->nutrs; i++) {
1498                 /* Configure UTRD with command descriptor base address */
1499                 cmd_desc_element_addr =
1500                                 (cmd_desc_dma_addr + (cmd_desc_size * i));
1501                 utrdlp[i].command_desc_base_addr_lo =
1502                                 cpu_to_le32(lower_32_bits(cmd_desc_element_addr));
1503                 utrdlp[i].command_desc_base_addr_hi =
1504                                 cpu_to_le32(upper_32_bits(cmd_desc_element_addr));
1505
1506                 /* Response upiu and prdt offset should be in double words */
1507                 utrdlp[i].response_upiu_offset =
1508                                 cpu_to_le16((response_offset >> 2));
1509                 utrdlp[i].prd_table_offset =
1510                                 cpu_to_le16((prdt_offset >> 2));
1511                 utrdlp[i].response_upiu_length =
1512                                 cpu_to_le16(ALIGNED_UPIU_SIZE >> 2);
1513
1514                 hba->lrb[i].utr_descriptor_ptr = (utrdlp + i);
1515                 hba->lrb[i].ucd_req_ptr =
1516                         (struct utp_upiu_req *)(cmd_descp + i);
1517                 hba->lrb[i].ucd_rsp_ptr =
1518                         (struct utp_upiu_rsp *)cmd_descp[i].response_upiu;
1519                 hba->lrb[i].ucd_prdt_ptr =
1520                         (struct ufshcd_sg_entry *)cmd_descp[i].prd_table;
1521         }
1522 }
1523
1524 /**
1525  * ufshcd_dme_link_startup - Notify Unipro to perform link startup
1526  * @hba: per adapter instance
1527  *
1528  * UIC_CMD_DME_LINK_STARTUP command must be issued to Unipro layer,
1529  * in order to initialize the Unipro link startup procedure.
1530  * Once the Unipro links are up, the device connected to the controller
1531  * is detected.
1532  *
1533  * Returns 0 on success, non-zero value on failure
1534  */
1535 static int ufshcd_dme_link_startup(struct ufs_hba *hba)
1536 {
1537         struct uic_command uic_cmd = {0};
1538         int ret;
1539
1540         uic_cmd.command = UIC_CMD_DME_LINK_STARTUP;
1541
1542         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
1543         if (ret)
1544                 dev_err(hba->dev,
1545                         "dme-link-startup: error code %d\n", ret);
1546         return ret;
1547 }
1548
1549 /**
1550  * ufshcd_dme_set_attr - UIC command for DME_SET, DME_PEER_SET
1551  * @hba: per adapter instance
1552  * @attr_sel: uic command argument1
1553  * @attr_set: attribute set type as uic command argument2
1554  * @mib_val: setting value as uic command argument3
1555  * @peer: indicate whether peer or local
1556  *
1557  * Returns 0 on success, non-zero value on failure
1558  */
1559 int ufshcd_dme_set_attr(struct ufs_hba *hba, u32 attr_sel,
1560                         u8 attr_set, u32 mib_val, u8 peer)
1561 {
1562         struct uic_command uic_cmd = {0};
1563         static const char *const action[] = {
1564                 "dme-set",
1565                 "dme-peer-set"
1566         };
1567         const char *set = action[!!peer];
1568         int ret;
1569
1570         uic_cmd.command = peer ?
1571                 UIC_CMD_DME_PEER_SET : UIC_CMD_DME_SET;
1572         uic_cmd.argument1 = attr_sel;
1573         uic_cmd.argument2 = UIC_ARG_ATTR_TYPE(attr_set);
1574         uic_cmd.argument3 = mib_val;
1575
1576         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
1577         if (ret)
1578                 dev_err(hba->dev, "%s: attr-id 0x%x val 0x%x error code %d\n",
1579                         set, UIC_GET_ATTR_ID(attr_sel), mib_val, ret);
1580
1581         return ret;
1582 }
1583 EXPORT_SYMBOL_GPL(ufshcd_dme_set_attr);
1584
1585 /**
1586  * ufshcd_dme_get_attr - UIC command for DME_GET, DME_PEER_GET
1587  * @hba: per adapter instance
1588  * @attr_sel: uic command argument1
1589  * @mib_val: the value of the attribute as returned by the UIC command
1590  * @peer: indicate whether peer or local
1591  *
1592  * Returns 0 on success, non-zero value on failure
1593  */
1594 int ufshcd_dme_get_attr(struct ufs_hba *hba, u32 attr_sel,
1595                         u32 *mib_val, u8 peer)
1596 {
1597         struct uic_command uic_cmd = {0};
1598         static const char *const action[] = {
1599                 "dme-get",
1600                 "dme-peer-get"
1601         };
1602         const char *get = action[!!peer];
1603         int ret;
1604
1605         uic_cmd.command = peer ?
1606                 UIC_CMD_DME_PEER_GET : UIC_CMD_DME_GET;
1607         uic_cmd.argument1 = attr_sel;
1608
1609         ret = ufshcd_send_uic_cmd(hba, &uic_cmd);
1610         if (ret) {
1611                 dev_err(hba->dev, "%s: attr-id 0x%x error code %d\n",
1612                         get, UIC_GET_ATTR_ID(attr_sel), ret);
1613                 goto out;
1614         }
1615
1616         if (mib_val)
1617                 *mib_val = uic_cmd.argument3;
1618 out:
1619         return ret;
1620 }
1621 EXPORT_SYMBOL_GPL(ufshcd_dme_get_attr);
1622
1623 /**
1624  * ufshcd_uic_change_pwr_mode - Perform the UIC power mode chage
1625  *                              using DME_SET primitives.
1626  * @hba: per adapter instance
1627  * @mode: powr mode value
1628  *
1629  * Returns 0 on success, non-zero value on failure
1630  */
1631 static int ufshcd_uic_change_pwr_mode(struct ufs_hba *hba, u8 mode)
1632 {
1633         struct uic_command uic_cmd = {0};
1634         struct completion pwr_done;
1635         unsigned long flags;
1636         u8 status;
1637         int ret;
1638
1639         uic_cmd.command = UIC_CMD_DME_SET;
1640         uic_cmd.argument1 = UIC_ARG_MIB(PA_PWRMODE);
1641         uic_cmd.argument3 = mode;
1642         init_completion(&pwr_done);
1643
1644         mutex_lock(&hba->uic_cmd_mutex);
1645
1646         spin_lock_irqsave(hba->host->host_lock, flags);
1647         hba->pwr_done = &pwr_done;
1648         spin_unlock_irqrestore(hba->host->host_lock, flags);
1649         ret = __ufshcd_send_uic_cmd(hba, &uic_cmd);
1650         if (ret) {
1651                 dev_err(hba->dev,
1652                         "pwr mode change with mode 0x%x uic error %d\n",
1653                         mode, ret);
1654                 goto out;
1655         }
1656
1657         if (!wait_for_completion_timeout(hba->pwr_done,
1658                                          msecs_to_jiffies(UIC_CMD_TIMEOUT))) {
1659                 dev_err(hba->dev,
1660                         "pwr mode change with mode 0x%x completion timeout\n",
1661                         mode);
1662                 ret = -ETIMEDOUT;
1663                 goto out;
1664         }
1665
1666         status = ufshcd_get_upmcrs(hba);
1667         if (status != PWR_LOCAL) {
1668                 dev_err(hba->dev,
1669                         "pwr mode change failed, host umpcrs:0x%x\n",
1670                         status);
1671                 ret = (status != PWR_OK) ? status : -1;
1672         }
1673 out:
1674         spin_lock_irqsave(hba->host->host_lock, flags);
1675         hba->pwr_done = NULL;
1676         spin_unlock_irqrestore(hba->host->host_lock, flags);
1677         mutex_unlock(&hba->uic_cmd_mutex);
1678         return ret;
1679 }
1680
1681 /**
1682  * ufshcd_config_max_pwr_mode - Set & Change power mode with
1683  *      maximum capability attribute information.
1684  * @hba: per adapter instance
1685  *
1686  * Returns 0 on success, non-zero value on failure
1687  */
1688 static int ufshcd_config_max_pwr_mode(struct ufs_hba *hba)
1689 {
1690         enum {RX = 0, TX = 1};
1691         u32 lanes[] = {1, 1};
1692         u32 gear[] = {1, 1};
1693         u8 pwr[] = {FASTAUTO_MODE, FASTAUTO_MODE};
1694         int ret;
1695
1696         /* Get the connected lane count */
1697         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDRXDATALANES), &lanes[RX]);
1698         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_CONNECTEDTXDATALANES), &lanes[TX]);
1699
1700         /*
1701          * First, get the maximum gears of HS speed.
1702          * If a zero value, it means there is no HSGEAR capability.
1703          * Then, get the maximum gears of PWM speed.
1704          */
1705         ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &gear[RX]);
1706         if (!gear[RX]) {
1707                 ufshcd_dme_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR), &gear[RX]);
1708                 pwr[RX] = SLOWAUTO_MODE;
1709         }
1710
1711         ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXHSGEAR), &gear[TX]);
1712         if (!gear[TX]) {
1713                 ufshcd_dme_peer_get(hba, UIC_ARG_MIB(PA_MAXRXPWMGEAR),
1714                                     &gear[TX]);
1715                 pwr[TX] = SLOWAUTO_MODE;
1716         }
1717
1718         /*
1719          * Configure attributes for power mode change with below.
1720          * - PA_RXGEAR, PA_ACTIVERXDATALANES, PA_RXTERMINATION,
1721          * - PA_TXGEAR, PA_ACTIVETXDATALANES, PA_TXTERMINATION,
1722          * - PA_HSSERIES
1723          */
1724         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXGEAR), gear[RX]);
1725         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVERXDATALANES), lanes[RX]);
1726         if (pwr[RX] == FASTAUTO_MODE)
1727                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_RXTERMINATION), TRUE);
1728
1729         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXGEAR), gear[TX]);
1730         ufshcd_dme_set(hba, UIC_ARG_MIB(PA_ACTIVETXDATALANES), lanes[TX]);
1731         if (pwr[TX] == FASTAUTO_MODE)
1732                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_TXTERMINATION), TRUE);
1733
1734         if (pwr[RX] == FASTAUTO_MODE || pwr[TX] == FASTAUTO_MODE)
1735                 ufshcd_dme_set(hba, UIC_ARG_MIB(PA_HSSERIES), PA_HS_MODE_B);
1736
1737         ret = ufshcd_uic_change_pwr_mode(hba, pwr[RX] << 4 | pwr[TX]);
1738         if (ret)
1739                 dev_err(hba->dev,
1740                         "pwr_mode: power mode change failed %d\n", ret);
1741
1742         return ret;
1743 }
1744
1745 /**
1746  * ufshcd_complete_dev_init() - checks device readiness
1747  * hba: per-adapter instance
1748  *
1749  * Set fDeviceInit flag and poll until device toggles it.
1750  */
1751 static int ufshcd_complete_dev_init(struct ufs_hba *hba)
1752 {
1753         int i, retries, err = 0;
1754         bool flag_res = 1;
1755
1756         for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1757                 /* Set the fDeviceInit flag */
1758                 err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
1759                                         QUERY_FLAG_IDN_FDEVICEINIT, NULL);
1760                 if (!err || err == -ETIMEDOUT)
1761                         break;
1762                 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
1763         }
1764         if (err) {
1765                 dev_err(hba->dev,
1766                         "%s setting fDeviceInit flag failed with error %d\n",
1767                         __func__, err);
1768                 goto out;
1769         }
1770
1771         /* poll for max. 100 iterations for fDeviceInit flag to clear */
1772         for (i = 0; i < 100 && !err && flag_res; i++) {
1773                 for (retries = QUERY_REQ_RETRIES; retries > 0; retries--) {
1774                         err = ufshcd_query_flag(hba,
1775                                         UPIU_QUERY_OPCODE_READ_FLAG,
1776                                         QUERY_FLAG_IDN_FDEVICEINIT, &flag_res);
1777                         if (!err || err == -ETIMEDOUT)
1778                                 break;
1779                         dev_dbg(hba->dev, "%s: error %d retrying\n", __func__,
1780                                         err);
1781                 }
1782         }
1783         if (err)
1784                 dev_err(hba->dev,
1785                         "%s reading fDeviceInit flag failed with error %d\n",
1786                         __func__, err);
1787         else if (flag_res)
1788                 dev_err(hba->dev,
1789                         "%s fDeviceInit was not cleared by the device\n",
1790                         __func__);
1791
1792 out:
1793         return err;
1794 }
1795
1796 /**
1797  * ufshcd_make_hba_operational - Make UFS controller operational
1798  * @hba: per adapter instance
1799  *
1800  * To bring UFS host controller to operational state,
1801  * 1. Check if device is present
1802  * 2. Enable required interrupts
1803  * 3. Configure interrupt aggregation
1804  * 4. Program UTRL and UTMRL base addres
1805  * 5. Configure run-stop-registers
1806  *
1807  * Returns 0 on success, non-zero value on failure
1808  */
1809 static int ufshcd_make_hba_operational(struct ufs_hba *hba)
1810 {
1811         int err = 0;
1812         u32 reg;
1813
1814         /* check if device present */
1815         reg = ufshcd_readl(hba, REG_CONTROLLER_STATUS);
1816         if (!ufshcd_is_device_present(reg)) {
1817                 dev_err(hba->dev, "cc: Device not present\n");
1818                 err = -ENXIO;
1819                 goto out;
1820         }
1821
1822         /* Enable required interrupts */
1823         ufshcd_enable_intr(hba, UFSHCD_ENABLE_INTRS);
1824
1825         /* Configure interrupt aggregation */
1826         ufshcd_config_intr_aggr(hba, hba->nutrs - 1, INT_AGGR_DEF_TO);
1827
1828         /* Configure UTRL and UTMRL base address registers */
1829         ufshcd_writel(hba, lower_32_bits(hba->utrdl_dma_addr),
1830                         REG_UTP_TRANSFER_REQ_LIST_BASE_L);
1831         ufshcd_writel(hba, upper_32_bits(hba->utrdl_dma_addr),
1832                         REG_UTP_TRANSFER_REQ_LIST_BASE_H);
1833         ufshcd_writel(hba, lower_32_bits(hba->utmrdl_dma_addr),
1834                         REG_UTP_TASK_REQ_LIST_BASE_L);
1835         ufshcd_writel(hba, upper_32_bits(hba->utmrdl_dma_addr),
1836                         REG_UTP_TASK_REQ_LIST_BASE_H);
1837
1838         /*
1839          * UCRDY, UTMRLDY and UTRLRDY bits must be 1
1840          * DEI, HEI bits must be 0
1841          */
1842         if (!(ufshcd_get_lists_status(reg))) {
1843                 ufshcd_enable_run_stop_reg(hba);
1844         } else {
1845                 dev_err(hba->dev,
1846                         "Host controller not ready to process requests");
1847                 err = -EIO;
1848                 goto out;
1849         }
1850
1851 out:
1852         return err;
1853 }
1854
1855 /**
1856  * ufshcd_hba_enable - initialize the controller
1857  * @hba: per adapter instance
1858  *
1859  * The controller resets itself and controller firmware initialization
1860  * sequence kicks off. When controller is ready it will set
1861  * the Host Controller Enable bit to 1.
1862  *
1863  * Returns 0 on success, non-zero value on failure
1864  */
1865 static int ufshcd_hba_enable(struct ufs_hba *hba)
1866 {
1867         int retry;
1868
1869         /*
1870          * msleep of 1 and 5 used in this function might result in msleep(20),
1871          * but it was necessary to send the UFS FPGA to reset mode during
1872          * development and testing of this driver. msleep can be changed to
1873          * mdelay and retry count can be reduced based on the controller.
1874          */
1875         if (!ufshcd_is_hba_active(hba)) {
1876
1877                 /* change controller state to "reset state" */
1878                 ufshcd_hba_stop(hba);
1879
1880                 /*
1881                  * This delay is based on the testing done with UFS host
1882                  * controller FPGA. The delay can be changed based on the
1883                  * host controller used.
1884                  */
1885                 msleep(5);
1886         }
1887
1888         /* start controller initialization sequence */
1889         ufshcd_hba_start(hba);
1890
1891         /*
1892          * To initialize a UFS host controller HCE bit must be set to 1.
1893          * During initialization the HCE bit value changes from 1->0->1.
1894          * When the host controller completes initialization sequence
1895          * it sets the value of HCE bit to 1. The same HCE bit is read back
1896          * to check if the controller has completed initialization sequence.
1897          * So without this delay the value HCE = 1, set in the previous
1898          * instruction might be read back.
1899          * This delay can be changed based on the controller.
1900          */
1901         msleep(1);
1902
1903         /* wait for the host controller to complete initialization */
1904         retry = 10;
1905         while (ufshcd_is_hba_active(hba)) {
1906                 if (retry) {
1907                         retry--;
1908                 } else {
1909                         dev_err(hba->dev,
1910                                 "Controller enable failed\n");
1911                         return -EIO;
1912                 }
1913                 msleep(5);
1914         }
1915         return 0;
1916 }
1917
1918 /**
1919  * ufshcd_link_startup - Initialize unipro link startup
1920  * @hba: per adapter instance
1921  *
1922  * Returns 0 for success, non-zero in case of failure
1923  */
1924 static int ufshcd_link_startup(struct ufs_hba *hba)
1925 {
1926         int ret;
1927
1928         /* enable UIC related interrupts */
1929         ufshcd_enable_intr(hba, UIC_COMMAND_COMPL);
1930
1931         ret = ufshcd_dme_link_startup(hba);
1932         if (ret)
1933                 goto out;
1934
1935         ret = ufshcd_make_hba_operational(hba);
1936
1937 out:
1938         if (ret)
1939                 dev_err(hba->dev, "link startup failed %d\n", ret);
1940         return ret;
1941 }
1942
1943 /**
1944  * ufshcd_verify_dev_init() - Verify device initialization
1945  * @hba: per-adapter instance
1946  *
1947  * Send NOP OUT UPIU and wait for NOP IN response to check whether the
1948  * device Transport Protocol (UTP) layer is ready after a reset.
1949  * If the UTP layer at the device side is not initialized, it may
1950  * not respond with NOP IN UPIU within timeout of %NOP_OUT_TIMEOUT
1951  * and we retry sending NOP OUT for %NOP_OUT_RETRIES iterations.
1952  */
1953 static int ufshcd_verify_dev_init(struct ufs_hba *hba)
1954 {
1955         int err = 0;
1956         int retries;
1957
1958         mutex_lock(&hba->dev_cmd.lock);
1959         for (retries = NOP_OUT_RETRIES; retries > 0; retries--) {
1960                 err = ufshcd_exec_dev_cmd(hba, DEV_CMD_TYPE_NOP,
1961                                                NOP_OUT_TIMEOUT);
1962
1963                 if (!err || err == -ETIMEDOUT)
1964                         break;
1965
1966                 dev_dbg(hba->dev, "%s: error %d retrying\n", __func__, err);
1967         }
1968         mutex_unlock(&hba->dev_cmd.lock);
1969
1970         if (err)
1971                 dev_err(hba->dev, "%s: NOP OUT failed %d\n", __func__, err);
1972         return err;
1973 }
1974
1975 /**
1976  * ufshcd_slave_alloc - handle initial SCSI device configurations
1977  * @sdev: pointer to SCSI device
1978  *
1979  * Returns success
1980  */
1981 static int ufshcd_slave_alloc(struct scsi_device *sdev)
1982 {
1983         struct ufs_hba *hba;
1984         int lun_qdepth;
1985
1986         hba = shost_priv(sdev->host);
1987         sdev->tagged_supported = 1;
1988
1989         /* Mode sense(6) is not supported by UFS, so use Mode sense(10) */
1990         sdev->use_10_for_ms = 1;
1991         scsi_set_tag_type(sdev, MSG_SIMPLE_TAG);
1992
1993         /* allow SCSI layer to restart the device in case of errors */
1994         sdev->allow_restart = 1;
1995
1996         /* REPORT SUPPORTED OPERATION CODES is not supported */
1997         sdev->no_report_opcodes = 1;
1998
1999         lun_qdepth = ufshcd_read_sdev_qdepth(hba, sdev);
2000         if (lun_qdepth <= 0)
2001                 /* eventually, we can figure out the real queue depth */
2002                 lun_qdepth = hba->nutrs;
2003         else
2004                 lun_qdepth = min_t(int, lun_qdepth, hba->nutrs);
2005
2006         dev_dbg(hba->dev, "%s: activate tcq with queue depth %d\n",
2007                         __func__, lun_qdepth);
2008         scsi_activate_tcq(sdev, lun_qdepth);
2009
2010         return 0;
2011 }
2012
2013 /**
2014  * ufshcd_change_queue_depth - change queue depth
2015  * @sdev: pointer to SCSI device
2016  * @depth: required depth to set
2017  * @reason: reason for changing the depth
2018  *
2019  * Change queue depth according to the reason and make sure
2020  * the max. limits are not crossed.
2021  */
2022 static int ufshcd_change_queue_depth(struct scsi_device *sdev,
2023                 int depth, int reason)
2024 {
2025         struct ufs_hba *hba = shost_priv(sdev->host);
2026
2027         if (depth > hba->nutrs)
2028                 depth = hba->nutrs;
2029
2030         switch (reason) {
2031         case SCSI_QDEPTH_DEFAULT:
2032         case SCSI_QDEPTH_RAMP_UP:
2033                 if (!sdev->tagged_supported)
2034                         depth = 1;
2035                 scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev), depth);
2036                 break;
2037         case SCSI_QDEPTH_QFULL:
2038                 scsi_track_queue_full(sdev, depth);
2039                 break;
2040         default:
2041                 return -EOPNOTSUPP;
2042         }
2043
2044         return depth;
2045 }
2046
2047 /**
2048  * ufshcd_slave_configure - adjust SCSI device configurations
2049  * @sdev: pointer to SCSI device
2050  */
2051 static int ufshcd_slave_configure(struct scsi_device *sdev)
2052 {
2053         struct request_queue *q = sdev->request_queue;
2054
2055         blk_queue_update_dma_pad(q, PRDT_DATA_BYTE_COUNT_PAD - 1);
2056         blk_queue_max_segment_size(q, PRDT_DATA_BYTE_COUNT_MAX);
2057
2058         return 0;
2059 }
2060
2061 /**
2062  * ufshcd_slave_destroy - remove SCSI device configurations
2063  * @sdev: pointer to SCSI device
2064  */
2065 static void ufshcd_slave_destroy(struct scsi_device *sdev)
2066 {
2067         struct ufs_hba *hba;
2068
2069         hba = shost_priv(sdev->host);
2070         scsi_deactivate_tcq(sdev, hba->nutrs);
2071 }
2072
2073 /**
2074  * ufshcd_task_req_compl - handle task management request completion
2075  * @hba: per adapter instance
2076  * @index: index of the completed request
2077  * @resp: task management service response
2078  *
2079  * Returns non-zero value on error, zero on success
2080  */
2081 static int ufshcd_task_req_compl(struct ufs_hba *hba, u32 index, u8 *resp)
2082 {
2083         struct utp_task_req_desc *task_req_descp;
2084         struct utp_upiu_task_rsp *task_rsp_upiup;
2085         unsigned long flags;
2086         int ocs_value;
2087         int task_result;
2088
2089         spin_lock_irqsave(hba->host->host_lock, flags);
2090
2091         /* Clear completed tasks from outstanding_tasks */
2092         __clear_bit(index, &hba->outstanding_tasks);
2093
2094         task_req_descp = hba->utmrdl_base_addr;
2095         ocs_value = ufshcd_get_tmr_ocs(&task_req_descp[index]);
2096
2097         if (ocs_value == OCS_SUCCESS) {
2098                 task_rsp_upiup = (struct utp_upiu_task_rsp *)
2099                                 task_req_descp[index].task_rsp_upiu;
2100                 task_result = be32_to_cpu(task_rsp_upiup->header.dword_1);
2101                 task_result = ((task_result & MASK_TASK_RESPONSE) >> 8);
2102                 if (resp)
2103                         *resp = (u8)task_result;
2104         } else {
2105                 dev_err(hba->dev, "%s: failed, ocs = 0x%x\n",
2106                                 __func__, ocs_value);
2107         }
2108         spin_unlock_irqrestore(hba->host->host_lock, flags);
2109
2110         return ocs_value;
2111 }
2112
2113 /**
2114  * ufshcd_scsi_cmd_status - Update SCSI command result based on SCSI status
2115  * @lrb: pointer to local reference block of completed command
2116  * @scsi_status: SCSI command status
2117  *
2118  * Returns value base on SCSI command status
2119  */
2120 static inline int
2121 ufshcd_scsi_cmd_status(struct ufshcd_lrb *lrbp, int scsi_status)
2122 {
2123         int result = 0;
2124
2125         switch (scsi_status) {
2126         case SAM_STAT_CHECK_CONDITION:
2127                 ufshcd_copy_sense_data(lrbp);
2128         case SAM_STAT_GOOD:
2129                 result |= DID_OK << 16 |
2130                           COMMAND_COMPLETE << 8 |
2131                           scsi_status;
2132                 break;
2133         case SAM_STAT_TASK_SET_FULL:
2134         case SAM_STAT_BUSY:
2135         case SAM_STAT_TASK_ABORTED:
2136                 ufshcd_copy_sense_data(lrbp);
2137                 result |= scsi_status;
2138                 break;
2139         default:
2140                 result |= DID_ERROR << 16;
2141                 break;
2142         } /* end of switch */
2143
2144         return result;
2145 }
2146
2147 /**
2148  * ufshcd_transfer_rsp_status - Get overall status of the response
2149  * @hba: per adapter instance
2150  * @lrb: pointer to local reference block of completed command
2151  *
2152  * Returns result of the command to notify SCSI midlayer
2153  */
2154 static inline int
2155 ufshcd_transfer_rsp_status(struct ufs_hba *hba, struct ufshcd_lrb *lrbp)
2156 {
2157         int result = 0;
2158         int scsi_status;
2159         int ocs;
2160
2161         /* overall command status of utrd */
2162         ocs = ufshcd_get_tr_ocs(lrbp);
2163
2164         switch (ocs) {
2165         case OCS_SUCCESS:
2166                 result = ufshcd_get_req_rsp(lrbp->ucd_rsp_ptr);
2167
2168                 switch (result) {
2169                 case UPIU_TRANSACTION_RESPONSE:
2170                         /*
2171                          * get the response UPIU result to extract
2172                          * the SCSI command status
2173                          */
2174                         result = ufshcd_get_rsp_upiu_result(lrbp->ucd_rsp_ptr);
2175
2176                         /*
2177                          * get the result based on SCSI status response
2178                          * to notify the SCSI midlayer of the command status
2179                          */
2180                         scsi_status = result & MASK_SCSI_STATUS;
2181                         result = ufshcd_scsi_cmd_status(lrbp, scsi_status);
2182
2183                         if (ufshcd_is_exception_event(lrbp->ucd_rsp_ptr))
2184                                 schedule_work(&hba->eeh_work);
2185                         break;
2186                 case UPIU_TRANSACTION_REJECT_UPIU:
2187                         /* TODO: handle Reject UPIU Response */
2188                         result = DID_ERROR << 16;
2189                         dev_err(hba->dev,
2190                                 "Reject UPIU not fully implemented\n");
2191                         break;
2192                 default:
2193                         result = DID_ERROR << 16;
2194                         dev_err(hba->dev,
2195                                 "Unexpected request response code = %x\n",
2196                                 result);
2197                         break;
2198                 }
2199                 break;
2200         case OCS_ABORTED:
2201                 result |= DID_ABORT << 16;
2202                 break;
2203         case OCS_INVALID_COMMAND_STATUS:
2204                 result |= DID_REQUEUE << 16;
2205                 break;
2206         case OCS_INVALID_CMD_TABLE_ATTR:
2207         case OCS_INVALID_PRDT_ATTR:
2208         case OCS_MISMATCH_DATA_BUF_SIZE:
2209         case OCS_MISMATCH_RESP_UPIU_SIZE:
2210         case OCS_PEER_COMM_FAILURE:
2211         case OCS_FATAL_ERROR:
2212         default:
2213                 result |= DID_ERROR << 16;
2214                 dev_err(hba->dev,
2215                 "OCS error from controller = %x\n", ocs);
2216                 break;
2217         } /* end of switch */
2218
2219         return result;
2220 }
2221
2222 /**
2223  * ufshcd_uic_cmd_compl - handle completion of uic command
2224  * @hba: per adapter instance
2225  * @intr_status: interrupt status generated by the controller
2226  */
2227 static void ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status)
2228 {
2229         if ((intr_status & UIC_COMMAND_COMPL) && hba->active_uic_cmd) {
2230                 hba->active_uic_cmd->argument2 |=
2231                         ufshcd_get_uic_cmd_result(hba);
2232                 hba->active_uic_cmd->argument3 =
2233                         ufshcd_get_dme_attr_val(hba);
2234                 complete(&hba->active_uic_cmd->done);
2235         }
2236
2237         if ((intr_status & UIC_POWER_MODE) && hba->pwr_done)
2238                 complete(hba->pwr_done);
2239 }
2240
2241 /**
2242  * ufshcd_transfer_req_compl - handle SCSI and query command completion
2243  * @hba: per adapter instance
2244  */
2245 static void ufshcd_transfer_req_compl(struct ufs_hba *hba)
2246 {
2247         struct ufshcd_lrb *lrbp;
2248         struct scsi_cmnd *cmd;
2249         unsigned long completed_reqs;
2250         u32 tr_doorbell;
2251         int result;
2252         int index;
2253
2254         /* Resetting interrupt aggregation counters first and reading the
2255          * DOOR_BELL afterward allows us to handle all the completed requests.
2256          * In order to prevent other interrupts starvation the DB is read once
2257          * after reset. The down side of this solution is the possibility of
2258          * false interrupt if device completes another request after resetting
2259          * aggregation and before reading the DB.
2260          */
2261         ufshcd_reset_intr_aggr(hba);
2262
2263         tr_doorbell = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2264         completed_reqs = tr_doorbell ^ hba->outstanding_reqs;
2265
2266         for_each_set_bit(index, &completed_reqs, hba->nutrs) {
2267                 lrbp = &hba->lrb[index];
2268                 cmd = lrbp->cmd;
2269                 if (cmd) {
2270                         result = ufshcd_transfer_rsp_status(hba, lrbp);
2271                         scsi_dma_unmap(cmd);
2272                         cmd->result = result;
2273                         /* Mark completed command as NULL in LRB */
2274                         lrbp->cmd = NULL;
2275                         clear_bit_unlock(index, &hba->lrb_in_use);
2276                         /* Do not touch lrbp after scsi done */
2277                         cmd->scsi_done(cmd);
2278                 } else if (lrbp->command_type == UTP_CMD_TYPE_DEV_MANAGE) {
2279                         if (hba->dev_cmd.complete)
2280                                 complete(hba->dev_cmd.complete);
2281                 }
2282         }
2283
2284         /* clear corresponding bits of completed commands */
2285         hba->outstanding_reqs ^= completed_reqs;
2286
2287         /* we might have free'd some tags above */
2288         wake_up(&hba->dev_cmd.tag_wq);
2289 }
2290
2291 /**
2292  * ufshcd_disable_ee - disable exception event
2293  * @hba: per-adapter instance
2294  * @mask: exception event to disable
2295  *
2296  * Disables exception event in the device so that the EVENT_ALERT
2297  * bit is not set.
2298  *
2299  * Returns zero on success, non-zero error value on failure.
2300  */
2301 static int ufshcd_disable_ee(struct ufs_hba *hba, u16 mask)
2302 {
2303         int err = 0;
2304         u32 val;
2305
2306         if (!(hba->ee_ctrl_mask & mask))
2307                 goto out;
2308
2309         val = hba->ee_ctrl_mask & ~mask;
2310         val &= 0xFFFF; /* 2 bytes */
2311         err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
2312                         QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
2313         if (!err)
2314                 hba->ee_ctrl_mask &= ~mask;
2315 out:
2316         return err;
2317 }
2318
2319 /**
2320  * ufshcd_enable_ee - enable exception event
2321  * @hba: per-adapter instance
2322  * @mask: exception event to enable
2323  *
2324  * Enable corresponding exception event in the device to allow
2325  * device to alert host in critical scenarios.
2326  *
2327  * Returns zero on success, non-zero error value on failure.
2328  */
2329 static int ufshcd_enable_ee(struct ufs_hba *hba, u16 mask)
2330 {
2331         int err = 0;
2332         u32 val;
2333
2334         if (hba->ee_ctrl_mask & mask)
2335                 goto out;
2336
2337         val = hba->ee_ctrl_mask | mask;
2338         val &= 0xFFFF; /* 2 bytes */
2339         err = ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_WRITE_ATTR,
2340                         QUERY_ATTR_IDN_EE_CONTROL, 0, 0, &val);
2341         if (!err)
2342                 hba->ee_ctrl_mask |= mask;
2343 out:
2344         return err;
2345 }
2346
2347 /**
2348  * ufshcd_enable_auto_bkops - Allow device managed BKOPS
2349  * @hba: per-adapter instance
2350  *
2351  * Allow device to manage background operations on its own. Enabling
2352  * this might lead to inconsistent latencies during normal data transfers
2353  * as the device is allowed to manage its own way of handling background
2354  * operations.
2355  *
2356  * Returns zero on success, non-zero on failure.
2357  */
2358 static int ufshcd_enable_auto_bkops(struct ufs_hba *hba)
2359 {
2360         int err = 0;
2361
2362         if (hba->auto_bkops_enabled)
2363                 goto out;
2364
2365         err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_SET_FLAG,
2366                         QUERY_FLAG_IDN_BKOPS_EN, NULL);
2367         if (err) {
2368                 dev_err(hba->dev, "%s: failed to enable bkops %d\n",
2369                                 __func__, err);
2370                 goto out;
2371         }
2372
2373         hba->auto_bkops_enabled = true;
2374
2375         /* No need of URGENT_BKOPS exception from the device */
2376         err = ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
2377         if (err)
2378                 dev_err(hba->dev, "%s: failed to disable exception event %d\n",
2379                                 __func__, err);
2380 out:
2381         return err;
2382 }
2383
2384 /**
2385  * ufshcd_disable_auto_bkops - block device in doing background operations
2386  * @hba: per-adapter instance
2387  *
2388  * Disabling background operations improves command response latency but
2389  * has drawback of device moving into critical state where the device is
2390  * not-operable. Make sure to call ufshcd_enable_auto_bkops() whenever the
2391  * host is idle so that BKOPS are managed effectively without any negative
2392  * impacts.
2393  *
2394  * Returns zero on success, non-zero on failure.
2395  */
2396 static int ufshcd_disable_auto_bkops(struct ufs_hba *hba)
2397 {
2398         int err = 0;
2399
2400         if (!hba->auto_bkops_enabled)
2401                 goto out;
2402
2403         /*
2404          * If host assisted BKOPs is to be enabled, make sure
2405          * urgent bkops exception is allowed.
2406          */
2407         err = ufshcd_enable_ee(hba, MASK_EE_URGENT_BKOPS);
2408         if (err) {
2409                 dev_err(hba->dev, "%s: failed to enable exception event %d\n",
2410                                 __func__, err);
2411                 goto out;
2412         }
2413
2414         err = ufshcd_query_flag(hba, UPIU_QUERY_OPCODE_CLEAR_FLAG,
2415                         QUERY_FLAG_IDN_BKOPS_EN, NULL);
2416         if (err) {
2417                 dev_err(hba->dev, "%s: failed to disable bkops %d\n",
2418                                 __func__, err);
2419                 ufshcd_disable_ee(hba, MASK_EE_URGENT_BKOPS);
2420                 goto out;
2421         }
2422
2423         hba->auto_bkops_enabled = false;
2424 out:
2425         return err;
2426 }
2427
2428 /**
2429  * ufshcd_force_reset_auto_bkops - force enable of auto bkops
2430  * @hba: per adapter instance
2431  *
2432  * After a device reset the device may toggle the BKOPS_EN flag
2433  * to default value. The s/w tracking variables should be updated
2434  * as well. Do this by forcing enable of auto bkops.
2435  */
2436 static void  ufshcd_force_reset_auto_bkops(struct ufs_hba *hba)
2437 {
2438         hba->auto_bkops_enabled = false;
2439         hba->ee_ctrl_mask |= MASK_EE_URGENT_BKOPS;
2440         ufshcd_enable_auto_bkops(hba);
2441 }
2442
2443 static inline int ufshcd_get_bkops_status(struct ufs_hba *hba, u32 *status)
2444 {
2445         return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
2446                         QUERY_ATTR_IDN_BKOPS_STATUS, 0, 0, status);
2447 }
2448
2449 /**
2450  * ufshcd_urgent_bkops - handle urgent bkops exception event
2451  * @hba: per-adapter instance
2452  *
2453  * Enable fBackgroundOpsEn flag in the device to permit background
2454  * operations.
2455  */
2456 static int ufshcd_urgent_bkops(struct ufs_hba *hba)
2457 {
2458         int err;
2459         u32 status = 0;
2460
2461         err = ufshcd_get_bkops_status(hba, &status);
2462         if (err) {
2463                 dev_err(hba->dev, "%s: failed to get BKOPS status %d\n",
2464                                 __func__, err);
2465                 goto out;
2466         }
2467
2468         status = status & 0xF;
2469
2470         /* handle only if status indicates performance impact or critical */
2471         if (status >= BKOPS_STATUS_PERF_IMPACT)
2472                 err = ufshcd_enable_auto_bkops(hba);
2473 out:
2474         return err;
2475 }
2476
2477 static inline int ufshcd_get_ee_status(struct ufs_hba *hba, u32 *status)
2478 {
2479         return ufshcd_query_attr(hba, UPIU_QUERY_OPCODE_READ_ATTR,
2480                         QUERY_ATTR_IDN_EE_STATUS, 0, 0, status);
2481 }
2482
2483 /**
2484  * ufshcd_exception_event_handler - handle exceptions raised by device
2485  * @work: pointer to work data
2486  *
2487  * Read bExceptionEventStatus attribute from the device and handle the
2488  * exception event accordingly.
2489  */
2490 static void ufshcd_exception_event_handler(struct work_struct *work)
2491 {
2492         struct ufs_hba *hba;
2493         int err;
2494         u32 status = 0;
2495         hba = container_of(work, struct ufs_hba, eeh_work);
2496
2497         pm_runtime_get_sync(hba->dev);
2498         err = ufshcd_get_ee_status(hba, &status);
2499         if (err) {
2500                 dev_err(hba->dev, "%s: failed to get exception status %d\n",
2501                                 __func__, err);
2502                 goto out;
2503         }
2504
2505         status &= hba->ee_ctrl_mask;
2506         if (status & MASK_EE_URGENT_BKOPS) {
2507                 err = ufshcd_urgent_bkops(hba);
2508                 if (err)
2509                         dev_err(hba->dev, "%s: failed to handle urgent bkops %d\n",
2510                                         __func__, err);
2511         }
2512 out:
2513         pm_runtime_put_sync(hba->dev);
2514         return;
2515 }
2516
2517 /**
2518  * ufshcd_err_handler - handle UFS errors that require s/w attention
2519  * @work: pointer to work structure
2520  */
2521 static void ufshcd_err_handler(struct work_struct *work)
2522 {
2523         struct ufs_hba *hba;
2524         unsigned long flags;
2525         u32 err_xfer = 0;
2526         u32 err_tm = 0;
2527         int err = 0;
2528         int tag;
2529
2530         hba = container_of(work, struct ufs_hba, eh_work);
2531
2532         pm_runtime_get_sync(hba->dev);
2533
2534         spin_lock_irqsave(hba->host->host_lock, flags);
2535         if (hba->ufshcd_state == UFSHCD_STATE_RESET) {
2536                 spin_unlock_irqrestore(hba->host->host_lock, flags);
2537                 goto out;
2538         }
2539
2540         hba->ufshcd_state = UFSHCD_STATE_RESET;
2541         ufshcd_set_eh_in_progress(hba);
2542
2543         /* Complete requests that have door-bell cleared by h/w */
2544         ufshcd_transfer_req_compl(hba);
2545         ufshcd_tmc_handler(hba);
2546         spin_unlock_irqrestore(hba->host->host_lock, flags);
2547
2548         /* Clear pending transfer requests */
2549         for_each_set_bit(tag, &hba->outstanding_reqs, hba->nutrs)
2550                 if (ufshcd_clear_cmd(hba, tag))
2551                         err_xfer |= 1 << tag;
2552
2553         /* Clear pending task management requests */
2554         for_each_set_bit(tag, &hba->outstanding_tasks, hba->nutmrs)
2555                 if (ufshcd_clear_tm_cmd(hba, tag))
2556                         err_tm |= 1 << tag;
2557
2558         /* Complete the requests that are cleared by s/w */
2559         spin_lock_irqsave(hba->host->host_lock, flags);
2560         ufshcd_transfer_req_compl(hba);
2561         ufshcd_tmc_handler(hba);
2562         spin_unlock_irqrestore(hba->host->host_lock, flags);
2563
2564         /* Fatal errors need reset */
2565         if (err_xfer || err_tm || (hba->saved_err & INT_FATAL_ERRORS) ||
2566                         ((hba->saved_err & UIC_ERROR) &&
2567                          (hba->saved_uic_err & UFSHCD_UIC_DL_PA_INIT_ERROR))) {
2568                 err = ufshcd_reset_and_restore(hba);
2569                 if (err) {
2570                         dev_err(hba->dev, "%s: reset and restore failed\n",
2571                                         __func__);
2572                         hba->ufshcd_state = UFSHCD_STATE_ERROR;
2573                 }
2574                 /*
2575                  * Inform scsi mid-layer that we did reset and allow to handle
2576                  * Unit Attention properly.
2577                  */
2578                 scsi_report_bus_reset(hba->host, 0);
2579                 hba->saved_err = 0;
2580                 hba->saved_uic_err = 0;
2581         }
2582         ufshcd_clear_eh_in_progress(hba);
2583
2584 out:
2585         scsi_unblock_requests(hba->host);
2586         pm_runtime_put_sync(hba->dev);
2587 }
2588
2589 /**
2590  * ufshcd_update_uic_error - check and set fatal UIC error flags.
2591  * @hba: per-adapter instance
2592  */
2593 static void ufshcd_update_uic_error(struct ufs_hba *hba)
2594 {
2595         u32 reg;
2596
2597         /* PA_INIT_ERROR is fatal and needs UIC reset */
2598         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DATA_LINK_LAYER);
2599         if (reg & UIC_DATA_LINK_LAYER_ERROR_PA_INIT)
2600                 hba->uic_error |= UFSHCD_UIC_DL_PA_INIT_ERROR;
2601
2602         /* UIC NL/TL/DME errors needs software retry */
2603         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_NETWORK_LAYER);
2604         if (reg)
2605                 hba->uic_error |= UFSHCD_UIC_NL_ERROR;
2606
2607         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_TRANSPORT_LAYER);
2608         if (reg)
2609                 hba->uic_error |= UFSHCD_UIC_TL_ERROR;
2610
2611         reg = ufshcd_readl(hba, REG_UIC_ERROR_CODE_DME);
2612         if (reg)
2613                 hba->uic_error |= UFSHCD_UIC_DME_ERROR;
2614
2615         dev_dbg(hba->dev, "%s: UIC error flags = 0x%08x\n",
2616                         __func__, hba->uic_error);
2617 }
2618
2619 /**
2620  * ufshcd_check_errors - Check for errors that need s/w attention
2621  * @hba: per-adapter instance
2622  */
2623 static void ufshcd_check_errors(struct ufs_hba *hba)
2624 {
2625         bool queue_eh_work = false;
2626
2627         if (hba->errors & INT_FATAL_ERRORS)
2628                 queue_eh_work = true;
2629
2630         if (hba->errors & UIC_ERROR) {
2631                 hba->uic_error = 0;
2632                 ufshcd_update_uic_error(hba);
2633                 if (hba->uic_error)
2634                         queue_eh_work = true;
2635         }
2636
2637         if (queue_eh_work) {
2638                 /* handle fatal errors only when link is functional */
2639                 if (hba->ufshcd_state == UFSHCD_STATE_OPERATIONAL) {
2640                         /* block commands from scsi mid-layer */
2641                         scsi_block_requests(hba->host);
2642
2643                         /* transfer error masks to sticky bits */
2644                         hba->saved_err |= hba->errors;
2645                         hba->saved_uic_err |= hba->uic_error;
2646
2647                         hba->ufshcd_state = UFSHCD_STATE_ERROR;
2648                         schedule_work(&hba->eh_work);
2649                 }
2650         }
2651         /*
2652          * if (!queue_eh_work) -
2653          * Other errors are either non-fatal where host recovers
2654          * itself without s/w intervention or errors that will be
2655          * handled by the SCSI core layer.
2656          */
2657 }
2658
2659 /**
2660  * ufshcd_tmc_handler - handle task management function completion
2661  * @hba: per adapter instance
2662  */
2663 static void ufshcd_tmc_handler(struct ufs_hba *hba)
2664 {
2665         u32 tm_doorbell;
2666
2667         tm_doorbell = ufshcd_readl(hba, REG_UTP_TASK_REQ_DOOR_BELL);
2668         hba->tm_condition = tm_doorbell ^ hba->outstanding_tasks;
2669         wake_up(&hba->tm_wq);
2670 }
2671
2672 /**
2673  * ufshcd_sl_intr - Interrupt service routine
2674  * @hba: per adapter instance
2675  * @intr_status: contains interrupts generated by the controller
2676  */
2677 static void ufshcd_sl_intr(struct ufs_hba *hba, u32 intr_status)
2678 {
2679         hba->errors = UFSHCD_ERROR_MASK & intr_status;
2680         if (hba->errors)
2681                 ufshcd_check_errors(hba);
2682
2683         if (intr_status & UFSHCD_UIC_MASK)
2684                 ufshcd_uic_cmd_compl(hba, intr_status);
2685
2686         if (intr_status & UTP_TASK_REQ_COMPL)
2687                 ufshcd_tmc_handler(hba);
2688
2689         if (intr_status & UTP_TRANSFER_REQ_COMPL)
2690                 ufshcd_transfer_req_compl(hba);
2691 }
2692
2693 /**
2694  * ufshcd_intr - Main interrupt service routine
2695  * @irq: irq number
2696  * @__hba: pointer to adapter instance
2697  *
2698  * Returns IRQ_HANDLED - If interrupt is valid
2699  *              IRQ_NONE - If invalid interrupt
2700  */
2701 static irqreturn_t ufshcd_intr(int irq, void *__hba)
2702 {
2703         u32 intr_status;
2704         irqreturn_t retval = IRQ_NONE;
2705         struct ufs_hba *hba = __hba;
2706
2707         spin_lock(hba->host->host_lock);
2708         intr_status = ufshcd_readl(hba, REG_INTERRUPT_STATUS);
2709
2710         if (intr_status) {
2711                 ufshcd_writel(hba, intr_status, REG_INTERRUPT_STATUS);
2712                 ufshcd_sl_intr(hba, intr_status);
2713                 retval = IRQ_HANDLED;
2714         }
2715         spin_unlock(hba->host->host_lock);
2716         return retval;
2717 }
2718
2719 static int ufshcd_clear_tm_cmd(struct ufs_hba *hba, int tag)
2720 {
2721         int err = 0;
2722         u32 mask = 1 << tag;
2723         unsigned long flags;
2724
2725         if (!test_bit(tag, &hba->outstanding_tasks))
2726                 goto out;
2727
2728         spin_lock_irqsave(hba->host->host_lock, flags);
2729         ufshcd_writel(hba, ~(1 << tag), REG_UTP_TASK_REQ_LIST_CLEAR);
2730         spin_unlock_irqrestore(hba->host->host_lock, flags);
2731
2732         /* poll for max. 1 sec to clear door bell register by h/w */
2733         err = ufshcd_wait_for_register(hba,
2734                         REG_UTP_TASK_REQ_DOOR_BELL,
2735                         mask, 0, 1000, 1000);
2736 out:
2737         return err;
2738 }
2739
2740 /**
2741  * ufshcd_issue_tm_cmd - issues task management commands to controller
2742  * @hba: per adapter instance
2743  * @lun_id: LUN ID to which TM command is sent
2744  * @task_id: task ID to which the TM command is applicable
2745  * @tm_function: task management function opcode
2746  * @tm_response: task management service response return value
2747  *
2748  * Returns non-zero value on error, zero on success.
2749  */
2750 static int ufshcd_issue_tm_cmd(struct ufs_hba *hba, int lun_id, int task_id,
2751                 u8 tm_function, u8 *tm_response)
2752 {
2753         struct utp_task_req_desc *task_req_descp;
2754         struct utp_upiu_task_req *task_req_upiup;
2755         struct Scsi_Host *host;
2756         unsigned long flags;
2757         int free_slot;
2758         int err;
2759         int task_tag;
2760
2761         host = hba->host;
2762
2763         /*
2764          * Get free slot, sleep if slots are unavailable.
2765          * Even though we use wait_event() which sleeps indefinitely,
2766          * the maximum wait time is bounded by %TM_CMD_TIMEOUT.
2767          */
2768         wait_event(hba->tm_tag_wq, ufshcd_get_tm_free_slot(hba, &free_slot));
2769
2770         spin_lock_irqsave(host->host_lock, flags);
2771         task_req_descp = hba->utmrdl_base_addr;
2772         task_req_descp += free_slot;
2773
2774         /* Configure task request descriptor */
2775         task_req_descp->header.dword_0 = cpu_to_le32(UTP_REQ_DESC_INT_CMD);
2776         task_req_descp->header.dword_2 =
2777                         cpu_to_le32(OCS_INVALID_COMMAND_STATUS);
2778
2779         /* Configure task request UPIU */
2780         task_req_upiup =
2781                 (struct utp_upiu_task_req *) task_req_descp->task_req_upiu;
2782         task_tag = hba->nutrs + free_slot;
2783         task_req_upiup->header.dword_0 =
2784                 UPIU_HEADER_DWORD(UPIU_TRANSACTION_TASK_REQ, 0,
2785                                               lun_id, task_tag);
2786         task_req_upiup->header.dword_1 =
2787                 UPIU_HEADER_DWORD(0, tm_function, 0, 0);
2788
2789         task_req_upiup->input_param1 = cpu_to_be32(lun_id);
2790         task_req_upiup->input_param2 = cpu_to_be32(task_id);
2791
2792         /* send command to the controller */
2793         __set_bit(free_slot, &hba->outstanding_tasks);
2794         ufshcd_writel(hba, 1 << free_slot, REG_UTP_TASK_REQ_DOOR_BELL);
2795
2796         spin_unlock_irqrestore(host->host_lock, flags);
2797
2798         /* wait until the task management command is completed */
2799         err = wait_event_timeout(hba->tm_wq,
2800                         test_bit(free_slot, &hba->tm_condition),
2801                         msecs_to_jiffies(TM_CMD_TIMEOUT));
2802         if (!err) {
2803                 dev_err(hba->dev, "%s: task management cmd 0x%.2x timed-out\n",
2804                                 __func__, tm_function);
2805                 if (ufshcd_clear_tm_cmd(hba, free_slot))
2806                         dev_WARN(hba->dev, "%s: unable clear tm cmd (slot %d) after timeout\n",
2807                                         __func__, free_slot);
2808                 err = -ETIMEDOUT;
2809         } else {
2810                 err = ufshcd_task_req_compl(hba, free_slot, tm_response);
2811         }
2812
2813         clear_bit(free_slot, &hba->tm_condition);
2814         ufshcd_put_tm_slot(hba, free_slot);
2815         wake_up(&hba->tm_tag_wq);
2816
2817         return err;
2818 }
2819
2820 /**
2821  * ufshcd_eh_device_reset_handler - device reset handler registered to
2822  *                                    scsi layer.
2823  * @cmd: SCSI command pointer
2824  *
2825  * Returns SUCCESS/FAILED
2826  */
2827 static int ufshcd_eh_device_reset_handler(struct scsi_cmnd *cmd)
2828 {
2829         struct Scsi_Host *host;
2830         struct ufs_hba *hba;
2831         unsigned int tag;
2832         u32 pos;
2833         int err;
2834         u8 resp = 0xF;
2835         struct ufshcd_lrb *lrbp;
2836         unsigned long flags;
2837
2838         host = cmd->device->host;
2839         hba = shost_priv(host);
2840         tag = cmd->request->tag;
2841
2842         lrbp = &hba->lrb[tag];
2843         err = ufshcd_issue_tm_cmd(hba, lrbp->lun, 0, UFS_LOGICAL_RESET, &resp);
2844         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
2845                 if (!err)
2846                         err = resp;
2847                 goto out;
2848         }
2849
2850         /* clear the commands that were pending for corresponding LUN */
2851         for_each_set_bit(pos, &hba->outstanding_reqs, hba->nutrs) {
2852                 if (hba->lrb[pos].lun == lrbp->lun) {
2853                         err = ufshcd_clear_cmd(hba, pos);
2854                         if (err)
2855                                 break;
2856                 }
2857         }
2858         spin_lock_irqsave(host->host_lock, flags);
2859         ufshcd_transfer_req_compl(hba);
2860         spin_unlock_irqrestore(host->host_lock, flags);
2861 out:
2862         if (!err) {
2863                 err = SUCCESS;
2864         } else {
2865                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
2866                 err = FAILED;
2867         }
2868         return err;
2869 }
2870
2871 /**
2872  * ufshcd_abort - abort a specific command
2873  * @cmd: SCSI command pointer
2874  *
2875  * Abort the pending command in device by sending UFS_ABORT_TASK task management
2876  * command, and in host controller by clearing the door-bell register. There can
2877  * be race between controller sending the command to the device while abort is
2878  * issued. To avoid that, first issue UFS_QUERY_TASK to check if the command is
2879  * really issued and then try to abort it.
2880  *
2881  * Returns SUCCESS/FAILED
2882  */
2883 static int ufshcd_abort(struct scsi_cmnd *cmd)
2884 {
2885         struct Scsi_Host *host;
2886         struct ufs_hba *hba;
2887         unsigned long flags;
2888         unsigned int tag;
2889         int err = 0;
2890         int poll_cnt;
2891         u8 resp = 0xF;
2892         struct ufshcd_lrb *lrbp;
2893         u32 reg;
2894
2895         host = cmd->device->host;
2896         hba = shost_priv(host);
2897         tag = cmd->request->tag;
2898
2899         /* If command is already aborted/completed, return SUCCESS */
2900         if (!(test_bit(tag, &hba->outstanding_reqs)))
2901                 goto out;
2902
2903         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2904         if (!(reg & (1 << tag))) {
2905                 dev_err(hba->dev,
2906                 "%s: cmd was completed, but without a notifying intr, tag = %d",
2907                 __func__, tag);
2908         }
2909
2910         lrbp = &hba->lrb[tag];
2911         for (poll_cnt = 100; poll_cnt; poll_cnt--) {
2912                 err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
2913                                 UFS_QUERY_TASK, &resp);
2914                 if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_SUCCEEDED) {
2915                         /* cmd pending in the device */
2916                         break;
2917                 } else if (!err && resp == UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
2918                         /*
2919                          * cmd not pending in the device, check if it is
2920                          * in transition.
2921                          */
2922                         reg = ufshcd_readl(hba, REG_UTP_TRANSFER_REQ_DOOR_BELL);
2923                         if (reg & (1 << tag)) {
2924                                 /* sleep for max. 200us to stabilize */
2925                                 usleep_range(100, 200);
2926                                 continue;
2927                         }
2928                         /* command completed already */
2929                         goto out;
2930                 } else {
2931                         if (!err)
2932                                 err = resp; /* service response error */
2933                         goto out;
2934                 }
2935         }
2936
2937         if (!poll_cnt) {
2938                 err = -EBUSY;
2939                 goto out;
2940         }
2941
2942         err = ufshcd_issue_tm_cmd(hba, lrbp->lun, lrbp->task_tag,
2943                         UFS_ABORT_TASK, &resp);
2944         if (err || resp != UPIU_TASK_MANAGEMENT_FUNC_COMPL) {
2945                 if (!err)
2946                         err = resp; /* service response error */
2947                 goto out;
2948         }
2949
2950         err = ufshcd_clear_cmd(hba, tag);
2951         if (err)
2952                 goto out;
2953
2954         scsi_dma_unmap(cmd);
2955
2956         spin_lock_irqsave(host->host_lock, flags);
2957         __clear_bit(tag, &hba->outstanding_reqs);
2958         hba->lrb[tag].cmd = NULL;
2959         spin_unlock_irqrestore(host->host_lock, flags);
2960
2961         clear_bit_unlock(tag, &hba->lrb_in_use);
2962         wake_up(&hba->dev_cmd.tag_wq);
2963 out:
2964         if (!err) {
2965                 err = SUCCESS;
2966         } else {
2967                 dev_err(hba->dev, "%s: failed with err %d\n", __func__, err);
2968                 err = FAILED;
2969         }
2970
2971         return err;
2972 }
2973
2974 /**
2975  * ufshcd_host_reset_and_restore - reset and restore host controller
2976  * @hba: per-adapter instance
2977  *
2978  * Note that host controller reset may issue DME_RESET to
2979  * local and remote (device) Uni-Pro stack and the attributes
2980  * are reset to default state.
2981  *
2982  * Returns zero on success, non-zero on failure
2983  */
2984 static int ufshcd_host_reset_and_restore(struct ufs_hba *hba)
2985 {
2986         int err;
2987         async_cookie_t cookie;
2988         unsigned long flags;
2989
2990         /* Reset the host controller */
2991         spin_lock_irqsave(hba->host->host_lock, flags);
2992         ufshcd_hba_stop(hba);
2993         spin_unlock_irqrestore(hba->host->host_lock, flags);
2994
2995         err = ufshcd_hba_enable(hba);
2996         if (err)
2997                 goto out;
2998
2999         /* Establish the link again and restore the device */
3000         cookie = async_schedule(ufshcd_async_scan, hba);
3001         /* wait for async scan to be completed */
3002         async_synchronize_cookie(++cookie);
3003         if (hba->ufshcd_state != UFSHCD_STATE_OPERATIONAL)
3004                 err = -EIO;
3005 out:
3006         if (err)
3007                 dev_err(hba->dev, "%s: Host init failed %d\n", __func__, err);
3008
3009         return err;
3010 }
3011
3012 /**
3013  * ufshcd_reset_and_restore - reset and re-initialize host/device
3014  * @hba: per-adapter instance
3015  *
3016  * Reset and recover device, host and re-establish link. This
3017  * is helpful to recover the communication in fatal error conditions.
3018  *
3019  * Returns zero on success, non-zero on failure
3020  */
3021 static int ufshcd_reset_and_restore(struct ufs_hba *hba)
3022 {
3023         int err = 0;
3024         unsigned long flags;
3025
3026         err = ufshcd_host_reset_and_restore(hba);
3027
3028         /*
3029          * After reset the door-bell might be cleared, complete
3030          * outstanding requests in s/w here.
3031          */
3032         spin_lock_irqsave(hba->host->host_lock, flags);
3033         ufshcd_transfer_req_compl(hba);
3034         ufshcd_tmc_handler(hba);
3035         spin_unlock_irqrestore(hba->host->host_lock, flags);
3036
3037         return err;
3038 }
3039
3040 /**
3041  * ufshcd_eh_host_reset_handler - host reset handler registered to scsi layer
3042  * @cmd - SCSI command pointer
3043  *
3044  * Returns SUCCESS/FAILED
3045  */
3046 static int ufshcd_eh_host_reset_handler(struct scsi_cmnd *cmd)
3047 {
3048         int err;
3049         unsigned long flags;
3050         struct ufs_hba *hba;
3051
3052         hba = shost_priv(cmd->device->host);
3053
3054         /*
3055          * Check if there is any race with fatal error handling.
3056          * If so, wait for it to complete. Even though fatal error
3057          * handling does reset and restore in some cases, don't assume
3058          * anything out of it. We are just avoiding race here.
3059          */
3060         do {
3061                 spin_lock_irqsave(hba->host->host_lock, flags);
3062                 if (!(work_pending(&hba->eh_work) ||
3063                                 hba->ufshcd_state == UFSHCD_STATE_RESET))
3064                         break;
3065                 spin_unlock_irqrestore(hba->host->host_lock, flags);
3066                 dev_dbg(hba->dev, "%s: reset in progress\n", __func__);
3067                 flush_work(&hba->eh_work);
3068         } while (1);
3069
3070         hba->ufshcd_state = UFSHCD_STATE_RESET;
3071         ufshcd_set_eh_in_progress(hba);
3072         spin_unlock_irqrestore(hba->host->host_lock, flags);
3073
3074         err = ufshcd_reset_and_restore(hba);
3075
3076         spin_lock_irqsave(hba->host->host_lock, flags);
3077         if (!err) {
3078                 err = SUCCESS;
3079                 hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
3080         } else {
3081                 err = FAILED;
3082                 hba->ufshcd_state = UFSHCD_STATE_ERROR;
3083         }
3084         ufshcd_clear_eh_in_progress(hba);
3085         spin_unlock_irqrestore(hba->host->host_lock, flags);
3086
3087         return err;
3088 }
3089
3090 /**
3091  * ufshcd_read_sdev_qdepth - read the lun command queue depth
3092  * @hba: Pointer to adapter instance
3093  * @sdev: pointer to SCSI device
3094  *
3095  * Return in case of success the lun's queue depth else error.
3096  */
3097 static int ufshcd_read_sdev_qdepth(struct ufs_hba *hba,
3098                                 struct scsi_device *sdev)
3099 {
3100         int ret;
3101         int buff_len = UNIT_DESC_MAX_SIZE;
3102         u8 desc_buf[UNIT_DESC_MAX_SIZE];
3103
3104         ret = ufshcd_query_descriptor(hba, UPIU_QUERY_OPCODE_READ_DESC,
3105                         QUERY_DESC_IDN_UNIT, sdev->lun, 0, desc_buf, &buff_len);
3106
3107         if (ret || (buff_len < UNIT_DESC_PARAM_LU_Q_DEPTH)) {
3108                 dev_err(hba->dev,
3109                         "%s:Failed reading unit descriptor. len = %d ret = %d"
3110                         , __func__, buff_len, ret);
3111                 if (!ret)
3112                         ret = -EINVAL;
3113
3114                 goto out;
3115         }
3116
3117         ret = desc_buf[UNIT_DESC_PARAM_LU_Q_DEPTH] & 0xFF;
3118 out:
3119         return ret;
3120 }
3121
3122 /**
3123  * ufshcd_async_scan - asynchronous execution for link startup
3124  * @data: data pointer to pass to this function
3125  * @cookie: cookie data
3126  */
3127 static void ufshcd_async_scan(void *data, async_cookie_t cookie)
3128 {
3129         struct ufs_hba *hba = (struct ufs_hba *)data;
3130         int ret;
3131
3132         ret = ufshcd_link_startup(hba);
3133         if (ret)
3134                 goto out;
3135
3136         ufshcd_config_max_pwr_mode(hba);
3137
3138         ret = ufshcd_verify_dev_init(hba);
3139         if (ret)
3140                 goto out;
3141
3142         ret = ufshcd_complete_dev_init(hba);
3143         if (ret)
3144                 goto out;
3145
3146         ufshcd_force_reset_auto_bkops(hba);
3147         hba->ufshcd_state = UFSHCD_STATE_OPERATIONAL;
3148
3149         /* If we are in error handling context no need to scan the host */
3150         if (!ufshcd_eh_in_progress(hba)) {
3151                 scsi_scan_host(hba->host);
3152                 pm_runtime_put_sync(hba->dev);
3153         }
3154 out:
3155         return;
3156 }
3157
3158 static struct scsi_host_template ufshcd_driver_template = {
3159         .module                 = THIS_MODULE,
3160         .name                   = UFSHCD,
3161         .proc_name              = UFSHCD,
3162         .queuecommand           = ufshcd_queuecommand,
3163         .slave_alloc            = ufshcd_slave_alloc,
3164         .slave_configure        = ufshcd_slave_configure,
3165         .slave_destroy          = ufshcd_slave_destroy,
3166         .change_queue_depth     = ufshcd_change_queue_depth,
3167         .eh_abort_handler       = ufshcd_abort,
3168         .eh_device_reset_handler = ufshcd_eh_device_reset_handler,
3169         .eh_host_reset_handler   = ufshcd_eh_host_reset_handler,
3170         .this_id                = -1,
3171         .sg_tablesize           = SG_ALL,
3172         .cmd_per_lun            = UFSHCD_CMD_PER_LUN,
3173         .can_queue              = UFSHCD_CAN_QUEUE,
3174 };
3175
3176 /**
3177  * ufshcd_suspend - suspend power management function
3178  * @hba: per adapter instance
3179  * @state: power state
3180  *
3181  * Returns -ENOSYS
3182  */
3183 int ufshcd_suspend(struct ufs_hba *hba, pm_message_t state)
3184 {
3185         /*
3186          * TODO:
3187          * 1. Block SCSI requests from SCSI midlayer
3188          * 2. Change the internal driver state to non operational
3189          * 3. Set UTRLRSR and UTMRLRSR bits to zero
3190          * 4. Wait until outstanding commands are completed
3191          * 5. Set HCE to zero to send the UFS host controller to reset state
3192          */
3193
3194         return -ENOSYS;
3195 }
3196 EXPORT_SYMBOL_GPL(ufshcd_suspend);
3197
3198 /**
3199  * ufshcd_resume - resume power management function
3200  * @hba: per adapter instance
3201  *
3202  * Returns -ENOSYS
3203  */
3204 int ufshcd_resume(struct ufs_hba *hba)
3205 {
3206         /*
3207          * TODO:
3208          * 1. Set HCE to 1, to start the UFS host controller
3209          * initialization process
3210          * 2. Set UTRLRSR and UTMRLRSR bits to 1
3211          * 3. Change the internal driver state to operational
3212          * 4. Unblock SCSI requests from SCSI midlayer
3213          */
3214
3215         return -ENOSYS;
3216 }
3217 EXPORT_SYMBOL_GPL(ufshcd_resume);
3218
3219 int ufshcd_runtime_suspend(struct ufs_hba *hba)
3220 {
3221         if (!hba)
3222                 return 0;
3223
3224         /*
3225          * The device is idle with no requests in the queue,
3226          * allow background operations.
3227          */
3228         return ufshcd_enable_auto_bkops(hba);
3229 }
3230 EXPORT_SYMBOL(ufshcd_runtime_suspend);
3231
3232 int ufshcd_runtime_resume(struct ufs_hba *hba)
3233 {
3234         if (!hba)
3235                 return 0;
3236
3237         return ufshcd_disable_auto_bkops(hba);
3238 }
3239 EXPORT_SYMBOL(ufshcd_runtime_resume);
3240
3241 int ufshcd_runtime_idle(struct ufs_hba *hba)
3242 {
3243         return 0;
3244 }
3245 EXPORT_SYMBOL(ufshcd_runtime_idle);
3246
3247 /**
3248  * ufshcd_remove - de-allocate SCSI host and host memory space
3249  *              data structure memory
3250  * @hba - per adapter instance
3251  */
3252 void ufshcd_remove(struct ufs_hba *hba)
3253 {
3254         scsi_remove_host(hba->host);
3255         /* disable interrupts */
3256         ufshcd_disable_intr(hba, hba->intr_mask);
3257         ufshcd_hba_stop(hba);
3258
3259         scsi_host_put(hba->host);
3260 }
3261 EXPORT_SYMBOL_GPL(ufshcd_remove);
3262
3263 /**
3264  * ufshcd_set_dma_mask - Set dma mask based on the controller
3265  *                       addressing capability
3266  * @hba: per adapter instance
3267  *
3268  * Returns 0 for success, non-zero for failure
3269  */
3270 static int ufshcd_set_dma_mask(struct ufs_hba *hba)
3271 {
3272         if (hba->capabilities & MASK_64_ADDRESSING_SUPPORT) {
3273                 if (!dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(64)))
3274                         return 0;
3275         }
3276         return dma_set_mask_and_coherent(hba->dev, DMA_BIT_MASK(32));
3277 }
3278
3279 /**
3280  * ufshcd_init - Driver initialization routine
3281  * @dev: pointer to device handle
3282  * @hba_handle: driver private handle
3283  * @mmio_base: base register address
3284  * @irq: Interrupt line of device
3285  * Returns 0 on success, non-zero value on failure
3286  */
3287 int ufshcd_init(struct device *dev, struct ufs_hba **hba_handle,
3288                  void __iomem *mmio_base, unsigned int irq)
3289 {
3290         struct Scsi_Host *host;
3291         struct ufs_hba *hba;
3292         int err;
3293
3294         if (!dev) {
3295                 dev_err(dev,
3296                 "Invalid memory reference for dev is NULL\n");
3297                 err = -ENODEV;
3298                 goto out_error;
3299         }
3300
3301         if (!mmio_base) {
3302                 dev_err(dev,
3303                 "Invalid memory reference for mmio_base is NULL\n");
3304                 err = -ENODEV;
3305                 goto out_error;
3306         }
3307
3308         host = scsi_host_alloc(&ufshcd_driver_template,
3309                                 sizeof(struct ufs_hba));
3310         if (!host) {
3311                 dev_err(dev, "scsi_host_alloc failed\n");
3312                 err = -ENOMEM;
3313                 goto out_error;
3314         }
3315         hba = shost_priv(host);
3316         hba->host = host;
3317         hba->dev = dev;
3318         hba->mmio_base = mmio_base;
3319         hba->irq = irq;
3320
3321         /* Read capabilities registers */
3322         ufshcd_hba_capabilities(hba);
3323
3324         /* Get UFS version supported by the controller */
3325         hba->ufs_version = ufshcd_get_ufs_version(hba);
3326
3327         /* Get Interrupt bit mask per version */
3328         hba->intr_mask = ufshcd_get_intr_mask(hba);
3329
3330         err = ufshcd_set_dma_mask(hba);
3331         if (err) {
3332                 dev_err(hba->dev, "set dma mask failed\n");
3333                 goto out_disable;
3334         }
3335
3336         /* Allocate memory for host memory space */
3337         err = ufshcd_memory_alloc(hba);
3338         if (err) {
3339                 dev_err(hba->dev, "Memory allocation failed\n");
3340                 goto out_disable;
3341         }
3342
3343         /* Configure LRB */
3344         ufshcd_host_memory_configure(hba);
3345
3346         host->can_queue = hba->nutrs;
3347         host->cmd_per_lun = hba->nutrs;
3348         host->max_id = UFSHCD_MAX_ID;
3349         host->max_lun = UFSHCD_MAX_LUNS;
3350         host->max_channel = UFSHCD_MAX_CHANNEL;
3351         host->unique_id = host->host_no;
3352         host->max_cmd_len = MAX_CDB_SIZE;
3353
3354         /* Initailize wait queue for task management */
3355         init_waitqueue_head(&hba->tm_wq);
3356         init_waitqueue_head(&hba->tm_tag_wq);
3357
3358         /* Initialize work queues */
3359         INIT_WORK(&hba->eh_work, ufshcd_err_handler);
3360         INIT_WORK(&hba->eeh_work, ufshcd_exception_event_handler);
3361
3362         /* Initialize UIC command mutex */
3363         mutex_init(&hba->uic_cmd_mutex);
3364
3365         /* Initialize mutex for device management commands */
3366         mutex_init(&hba->dev_cmd.lock);
3367
3368         /* Initialize device management tag acquire wait queue */
3369         init_waitqueue_head(&hba->dev_cmd.tag_wq);
3370
3371         /* IRQ registration */
3372         err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
3373         if (err) {
3374                 dev_err(hba->dev, "request irq failed\n");
3375                 goto out_disable;
3376         }
3377
3378         /* Enable SCSI tag mapping */
3379         err = scsi_init_shared_tag_map(host, host->can_queue);
3380         if (err) {
3381                 dev_err(hba->dev, "init shared queue failed\n");
3382                 goto out_disable;
3383         }
3384
3385         err = scsi_add_host(host, hba->dev);
3386         if (err) {
3387                 dev_err(hba->dev, "scsi_add_host failed\n");
3388                 goto out_disable;
3389         }
3390
3391         /* Host controller enable */
3392         err = ufshcd_hba_enable(hba);
3393         if (err) {
3394                 dev_err(hba->dev, "Host controller enable failed\n");
3395                 goto out_remove_scsi_host;
3396         }
3397
3398         *hba_handle = hba;
3399
3400         /* Hold auto suspend until async scan completes */
3401         pm_runtime_get_sync(dev);
3402
3403         async_schedule(ufshcd_async_scan, hba);
3404
3405         return 0;
3406
3407 out_remove_scsi_host:
3408         scsi_remove_host(hba->host);
3409 out_disable:
3410         scsi_host_put(host);
3411 out_error:
3412         return err;
3413 }
3414 EXPORT_SYMBOL_GPL(ufshcd_init);
3415
3416 MODULE_AUTHOR("Santosh Yaragnavi <santosh.sy@samsung.com>");
3417 MODULE_AUTHOR("Vinayak Holikatti <h.vinayak@samsung.com>");
3418 MODULE_DESCRIPTION("Generic UFS host controller driver Core");
3419 MODULE_LICENSE("GPL");
3420 MODULE_VERSION(UFSHCD_DRIVER_VERSION);