d893c6d61a60ef4e73c1491c7994571c47638e1b
[linux-2.6-microblaze.git] / drivers / scsi / mpi3mr / mpi3mr_os.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Driver for Broadcom MPI3 Storage Controllers
4  *
5  * Copyright (C) 2017-2021 Broadcom Inc.
6  *  (mailto: mpi3mr-linuxdrv.pdl@broadcom.com)
7  *
8  */
9
10 #include "mpi3mr.h"
11
12 /* global driver scop variables */
13 LIST_HEAD(mrioc_list);
14 DEFINE_SPINLOCK(mrioc_list_lock);
15 static int mrioc_ids;
16 static int warn_non_secure_ctlr;
17
18 MODULE_AUTHOR(MPI3MR_DRIVER_AUTHOR);
19 MODULE_DESCRIPTION(MPI3MR_DRIVER_DESC);
20 MODULE_LICENSE(MPI3MR_DRIVER_LICENSE);
21 MODULE_VERSION(MPI3MR_DRIVER_VERSION);
22
23 /* Module parameters*/
24 int prot_mask = -1;
25 module_param(prot_mask, int, 0);
26 MODULE_PARM_DESC(prot_mask, "Host protection capabilities mask, def=0x07");
27
28 static int prot_guard_mask = 3;
29 module_param(prot_guard_mask, int, 0);
30 MODULE_PARM_DESC(prot_guard_mask, " Host protection guard mask, def=3");
31 static int logging_level;
32 module_param(logging_level, int, 0);
33 MODULE_PARM_DESC(logging_level,
34         " bits for enabling additional logging info (default=0)");
35
36 /* Forward declarations*/
37 static void mpi3mr_send_event_ack(struct mpi3mr_ioc *mrioc, u8 event,
38         struct mpi3mr_drv_cmd *cmdparam, u32 event_ctx);
39
40 /**
41  * mpi3mr_host_tag_for_scmd - Get host tag for a scmd
42  * @mrioc: Adapter instance reference
43  * @scmd: SCSI command reference
44  *
45  * Calculate the host tag based on block tag for a given scmd.
46  *
47  * Return: Valid host tag or MPI3MR_HOSTTAG_INVALID.
48  */
49 static u16 mpi3mr_host_tag_for_scmd(struct mpi3mr_ioc *mrioc,
50         struct scsi_cmnd *scmd)
51 {
52         struct scmd_priv *priv = NULL;
53         u32 unique_tag;
54         u16 host_tag, hw_queue;
55
56         unique_tag = blk_mq_unique_tag(scsi_cmd_to_rq(scmd));
57
58         hw_queue = blk_mq_unique_tag_to_hwq(unique_tag);
59         if (hw_queue >= mrioc->num_op_reply_q)
60                 return MPI3MR_HOSTTAG_INVALID;
61         host_tag = blk_mq_unique_tag_to_tag(unique_tag);
62
63         if (WARN_ON(host_tag >= mrioc->max_host_ios))
64                 return MPI3MR_HOSTTAG_INVALID;
65
66         priv = scsi_cmd_priv(scmd);
67         /*host_tag 0 is invalid hence incrementing by 1*/
68         priv->host_tag = host_tag + 1;
69         priv->scmd = scmd;
70         priv->in_lld_scope = 1;
71         priv->req_q_idx = hw_queue;
72         priv->meta_chain_idx = -1;
73         priv->chain_idx = -1;
74         priv->meta_sg_valid = 0;
75         return priv->host_tag;
76 }
77
78 /**
79  * mpi3mr_scmd_from_host_tag - Get SCSI command from host tag
80  * @mrioc: Adapter instance reference
81  * @host_tag: Host tag
82  * @qidx: Operational queue index
83  *
84  * Identify the block tag from the host tag and queue index and
85  * retrieve associated scsi command using scsi_host_find_tag().
86  *
87  * Return: SCSI command reference or NULL.
88  */
89 static struct scsi_cmnd *mpi3mr_scmd_from_host_tag(
90         struct mpi3mr_ioc *mrioc, u16 host_tag, u16 qidx)
91 {
92         struct scsi_cmnd *scmd = NULL;
93         struct scmd_priv *priv = NULL;
94         u32 unique_tag = host_tag - 1;
95
96         if (WARN_ON(host_tag > mrioc->max_host_ios))
97                 goto out;
98
99         unique_tag |= (qidx << BLK_MQ_UNIQUE_TAG_BITS);
100
101         scmd = scsi_host_find_tag(mrioc->shost, unique_tag);
102         if (scmd) {
103                 priv = scsi_cmd_priv(scmd);
104                 if (!priv->in_lld_scope)
105                         scmd = NULL;
106         }
107 out:
108         return scmd;
109 }
110
111 /**
112  * mpi3mr_clear_scmd_priv - Cleanup SCSI command private date
113  * @mrioc: Adapter instance reference
114  * @scmd: SCSI command reference
115  *
116  * Invalidate the SCSI command private data to mark the command
117  * is not in LLD scope anymore.
118  *
119  * Return: Nothing.
120  */
121 static void mpi3mr_clear_scmd_priv(struct mpi3mr_ioc *mrioc,
122         struct scsi_cmnd *scmd)
123 {
124         struct scmd_priv *priv = NULL;
125
126         priv = scsi_cmd_priv(scmd);
127
128         if (WARN_ON(priv->in_lld_scope == 0))
129                 return;
130         priv->host_tag = MPI3MR_HOSTTAG_INVALID;
131         priv->req_q_idx = 0xFFFF;
132         priv->scmd = NULL;
133         priv->in_lld_scope = 0;
134         priv->meta_sg_valid = 0;
135         if (priv->chain_idx >= 0) {
136                 clear_bit(priv->chain_idx, mrioc->chain_bitmap);
137                 priv->chain_idx = -1;
138         }
139         if (priv->meta_chain_idx >= 0) {
140                 clear_bit(priv->meta_chain_idx, mrioc->chain_bitmap);
141                 priv->meta_chain_idx = -1;
142         }
143 }
144
145 static void mpi3mr_dev_rmhs_send_tm(struct mpi3mr_ioc *mrioc, u16 handle,
146         struct mpi3mr_drv_cmd *cmdparam, u8 iou_rc);
147 static void mpi3mr_fwevt_worker(struct work_struct *work);
148
149 /**
150  * mpi3mr_fwevt_free - firmware event memory dealloctor
151  * @r: k reference pointer of the firmware event
152  *
153  * Free firmware event memory when no reference.
154  */
155 static void mpi3mr_fwevt_free(struct kref *r)
156 {
157         kfree(container_of(r, struct mpi3mr_fwevt, ref_count));
158 }
159
160 /**
161  * mpi3mr_fwevt_get - k reference incrementor
162  * @fwevt: Firmware event reference
163  *
164  * Increment firmware event reference count.
165  */
166 static void mpi3mr_fwevt_get(struct mpi3mr_fwevt *fwevt)
167 {
168         kref_get(&fwevt->ref_count);
169 }
170
171 /**
172  * mpi3mr_fwevt_put - k reference decrementor
173  * @fwevt: Firmware event reference
174  *
175  * decrement firmware event reference count.
176  */
177 static void mpi3mr_fwevt_put(struct mpi3mr_fwevt *fwevt)
178 {
179         kref_put(&fwevt->ref_count, mpi3mr_fwevt_free);
180 }
181
182 /**
183  * mpi3mr_alloc_fwevt - Allocate firmware event
184  * @len: length of firmware event data to allocate
185  *
186  * Allocate firmware event with required length and initialize
187  * the reference counter.
188  *
189  * Return: firmware event reference.
190  */
191 static struct mpi3mr_fwevt *mpi3mr_alloc_fwevt(int len)
192 {
193         struct mpi3mr_fwevt *fwevt;
194
195         fwevt = kzalloc(sizeof(*fwevt) + len, GFP_ATOMIC);
196         if (!fwevt)
197                 return NULL;
198
199         kref_init(&fwevt->ref_count);
200         return fwevt;
201 }
202
203 /**
204  * mpi3mr_fwevt_add_to_list - Add firmware event to the list
205  * @mrioc: Adapter instance reference
206  * @fwevt: Firmware event reference
207  *
208  * Add the given firmware event to the firmware event list.
209  *
210  * Return: Nothing.
211  */
212 static void mpi3mr_fwevt_add_to_list(struct mpi3mr_ioc *mrioc,
213         struct mpi3mr_fwevt *fwevt)
214 {
215         unsigned long flags;
216
217         if (!mrioc->fwevt_worker_thread)
218                 return;
219
220         spin_lock_irqsave(&mrioc->fwevt_lock, flags);
221         /* get fwevt reference count while adding it to fwevt_list */
222         mpi3mr_fwevt_get(fwevt);
223         INIT_LIST_HEAD(&fwevt->list);
224         list_add_tail(&fwevt->list, &mrioc->fwevt_list);
225         INIT_WORK(&fwevt->work, mpi3mr_fwevt_worker);
226         /* get fwevt reference count while enqueueing it to worker queue */
227         mpi3mr_fwevt_get(fwevt);
228         queue_work(mrioc->fwevt_worker_thread, &fwevt->work);
229         spin_unlock_irqrestore(&mrioc->fwevt_lock, flags);
230 }
231
232 /**
233  * mpi3mr_fwevt_del_from_list - Delete firmware event from list
234  * @mrioc: Adapter instance reference
235  * @fwevt: Firmware event reference
236  *
237  * Delete the given firmware event from the firmware event list.
238  *
239  * Return: Nothing.
240  */
241 static void mpi3mr_fwevt_del_from_list(struct mpi3mr_ioc *mrioc,
242         struct mpi3mr_fwevt *fwevt)
243 {
244         unsigned long flags;
245
246         spin_lock_irqsave(&mrioc->fwevt_lock, flags);
247         if (!list_empty(&fwevt->list)) {
248                 list_del_init(&fwevt->list);
249                 /*
250                  * Put fwevt reference count after
251                  * removing it from fwevt_list
252                  */
253                 mpi3mr_fwevt_put(fwevt);
254         }
255         spin_unlock_irqrestore(&mrioc->fwevt_lock, flags);
256 }
257
258 /**
259  * mpi3mr_dequeue_fwevt - Dequeue firmware event from the list
260  * @mrioc: Adapter instance reference
261  *
262  * Dequeue a firmware event from the firmware event list.
263  *
264  * Return: firmware event.
265  */
266 static struct mpi3mr_fwevt *mpi3mr_dequeue_fwevt(
267         struct mpi3mr_ioc *mrioc)
268 {
269         unsigned long flags;
270         struct mpi3mr_fwevt *fwevt = NULL;
271
272         spin_lock_irqsave(&mrioc->fwevt_lock, flags);
273         if (!list_empty(&mrioc->fwevt_list)) {
274                 fwevt = list_first_entry(&mrioc->fwevt_list,
275                     struct mpi3mr_fwevt, list);
276                 list_del_init(&fwevt->list);
277                 /*
278                  * Put fwevt reference count after
279                  * removing it from fwevt_list
280                  */
281                 mpi3mr_fwevt_put(fwevt);
282         }
283         spin_unlock_irqrestore(&mrioc->fwevt_lock, flags);
284
285         return fwevt;
286 }
287
288 /**
289  * mpi3mr_cleanup_fwevt_list - Cleanup firmware event list
290  * @mrioc: Adapter instance reference
291  *
292  * Flush all pending firmware events from the firmware event
293  * list.
294  *
295  * Return: Nothing.
296  */
297 void mpi3mr_cleanup_fwevt_list(struct mpi3mr_ioc *mrioc)
298 {
299         struct mpi3mr_fwevt *fwevt = NULL;
300
301         if ((list_empty(&mrioc->fwevt_list) && !mrioc->current_event) ||
302             !mrioc->fwevt_worker_thread)
303                 return;
304
305         while ((fwevt = mpi3mr_dequeue_fwevt(mrioc)) ||
306             (fwevt = mrioc->current_event)) {
307                 /*
308                  * Wait on the fwevt to complete. If this returns 1, then
309                  * the event was never executed, and we need a put for the
310                  * reference the work had on the fwevt.
311                  *
312                  * If it did execute, we wait for it to finish, and the put will
313                  * happen from mpi3mr_process_fwevt()
314                  */
315                 if (cancel_work_sync(&fwevt->work)) {
316                         /*
317                          * Put fwevt reference count after
318                          * dequeuing it from worker queue
319                          */
320                         mpi3mr_fwevt_put(fwevt);
321                         /*
322                          * Put fwevt reference count to neutralize
323                          * kref_init increment
324                          */
325                         mpi3mr_fwevt_put(fwevt);
326                 }
327         }
328 }
329
330 /**
331  * mpi3mr_invalidate_devhandles -Invalidate device handles
332  * @mrioc: Adapter instance reference
333  *
334  * Invalidate the device handles in the target device structures
335  * . Called post reset prior to reinitializing the controller.
336  *
337  * Return: Nothing.
338  */
339 void mpi3mr_invalidate_devhandles(struct mpi3mr_ioc *mrioc)
340 {
341         struct mpi3mr_tgt_dev *tgtdev;
342         struct mpi3mr_stgt_priv_data *tgt_priv;
343
344         list_for_each_entry(tgtdev, &mrioc->tgtdev_list, list) {
345                 tgtdev->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
346                 if (tgtdev->starget && tgtdev->starget->hostdata) {
347                         tgt_priv = tgtdev->starget->hostdata;
348                         tgt_priv->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
349                 }
350         }
351 }
352
353 /**
354  * mpi3mr_print_scmd - print individual SCSI command
355  * @rq: Block request
356  * @data: Adapter instance reference
357  * @reserved: N/A. Currently not used
358  *
359  * Print the SCSI command details if it is in LLD scope.
360  *
361  * Return: true always.
362  */
363 static bool mpi3mr_print_scmd(struct request *rq,
364         void *data, bool reserved)
365 {
366         struct mpi3mr_ioc *mrioc = (struct mpi3mr_ioc *)data;
367         struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(rq);
368         struct scmd_priv *priv = NULL;
369
370         if (scmd) {
371                 priv = scsi_cmd_priv(scmd);
372                 if (!priv->in_lld_scope)
373                         goto out;
374
375                 ioc_info(mrioc, "%s :Host Tag = %d, qid = %d\n",
376                     __func__, priv->host_tag, priv->req_q_idx + 1);
377                 scsi_print_command(scmd);
378         }
379
380 out:
381         return(true);
382 }
383
384 /**
385  * mpi3mr_flush_scmd - Flush individual SCSI command
386  * @rq: Block request
387  * @data: Adapter instance reference
388  * @reserved: N/A. Currently not used
389  *
390  * Return the SCSI command to the upper layers if it is in LLD
391  * scope.
392  *
393  * Return: true always.
394  */
395
396 static bool mpi3mr_flush_scmd(struct request *rq,
397         void *data, bool reserved)
398 {
399         struct mpi3mr_ioc *mrioc = (struct mpi3mr_ioc *)data;
400         struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(rq);
401         struct scmd_priv *priv = NULL;
402
403         if (scmd) {
404                 priv = scsi_cmd_priv(scmd);
405                 if (!priv->in_lld_scope)
406                         goto out;
407
408                 if (priv->meta_sg_valid)
409                         dma_unmap_sg(&mrioc->pdev->dev, scsi_prot_sglist(scmd),
410                             scsi_prot_sg_count(scmd), scmd->sc_data_direction);
411                 mpi3mr_clear_scmd_priv(mrioc, scmd);
412                 scsi_dma_unmap(scmd);
413                 scmd->result = DID_RESET << 16;
414                 scsi_print_command(scmd);
415                 scsi_done(scmd);
416                 mrioc->flush_io_count++;
417         }
418
419 out:
420         return(true);
421 }
422
423 /**
424  * mpi3mr_flush_host_io -  Flush host I/Os
425  * @mrioc: Adapter instance reference
426  *
427  * Flush all of the pending I/Os by calling
428  * blk_mq_tagset_busy_iter() for each possible tag. This is
429  * executed post controller reset
430  *
431  * Return: Nothing.
432  */
433 void mpi3mr_flush_host_io(struct mpi3mr_ioc *mrioc)
434 {
435         struct Scsi_Host *shost = mrioc->shost;
436
437         mrioc->flush_io_count = 0;
438         ioc_info(mrioc, "%s :Flushing Host I/O cmds post reset\n", __func__);
439         blk_mq_tagset_busy_iter(&shost->tag_set,
440             mpi3mr_flush_scmd, (void *)mrioc);
441         ioc_info(mrioc, "%s :Flushed %d Host I/O cmds\n", __func__,
442             mrioc->flush_io_count);
443 }
444
445 /**
446  * mpi3mr_alloc_tgtdev - target device allocator
447  *
448  * Allocate target device instance and initialize the reference
449  * count
450  *
451  * Return: target device instance.
452  */
453 static struct mpi3mr_tgt_dev *mpi3mr_alloc_tgtdev(void)
454 {
455         struct mpi3mr_tgt_dev *tgtdev;
456
457         tgtdev = kzalloc(sizeof(*tgtdev), GFP_ATOMIC);
458         if (!tgtdev)
459                 return NULL;
460         kref_init(&tgtdev->ref_count);
461         return tgtdev;
462 }
463
464 /**
465  * mpi3mr_tgtdev_add_to_list -Add tgtdevice to the list
466  * @mrioc: Adapter instance reference
467  * @tgtdev: Target device
468  *
469  * Add the target device to the target device list
470  *
471  * Return: Nothing.
472  */
473 static void mpi3mr_tgtdev_add_to_list(struct mpi3mr_ioc *mrioc,
474         struct mpi3mr_tgt_dev *tgtdev)
475 {
476         unsigned long flags;
477
478         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
479         mpi3mr_tgtdev_get(tgtdev);
480         INIT_LIST_HEAD(&tgtdev->list);
481         list_add_tail(&tgtdev->list, &mrioc->tgtdev_list);
482         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
483 }
484
485 /**
486  * mpi3mr_tgtdev_del_from_list -Delete tgtdevice from the list
487  * @mrioc: Adapter instance reference
488  * @tgtdev: Target device
489  *
490  * Remove the target device from the target device list
491  *
492  * Return: Nothing.
493  */
494 static void mpi3mr_tgtdev_del_from_list(struct mpi3mr_ioc *mrioc,
495         struct mpi3mr_tgt_dev *tgtdev)
496 {
497         unsigned long flags;
498
499         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
500         if (!list_empty(&tgtdev->list)) {
501                 list_del_init(&tgtdev->list);
502                 mpi3mr_tgtdev_put(tgtdev);
503         }
504         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
505 }
506
507 /**
508  * __mpi3mr_get_tgtdev_by_handle -Get tgtdev from device handle
509  * @mrioc: Adapter instance reference
510  * @handle: Device handle
511  *
512  * Accessor to retrieve target device from the device handle.
513  * Non Lock version
514  *
515  * Return: Target device reference.
516  */
517 static struct mpi3mr_tgt_dev  *__mpi3mr_get_tgtdev_by_handle(
518         struct mpi3mr_ioc *mrioc, u16 handle)
519 {
520         struct mpi3mr_tgt_dev *tgtdev;
521
522         assert_spin_locked(&mrioc->tgtdev_lock);
523         list_for_each_entry(tgtdev, &mrioc->tgtdev_list, list)
524                 if (tgtdev->dev_handle == handle)
525                         goto found_tgtdev;
526         return NULL;
527
528 found_tgtdev:
529         mpi3mr_tgtdev_get(tgtdev);
530         return tgtdev;
531 }
532
533 /**
534  * mpi3mr_get_tgtdev_by_handle -Get tgtdev from device handle
535  * @mrioc: Adapter instance reference
536  * @handle: Device handle
537  *
538  * Accessor to retrieve target device from the device handle.
539  * Lock version
540  *
541  * Return: Target device reference.
542  */
543 static struct mpi3mr_tgt_dev *mpi3mr_get_tgtdev_by_handle(
544         struct mpi3mr_ioc *mrioc, u16 handle)
545 {
546         struct mpi3mr_tgt_dev *tgtdev;
547         unsigned long flags;
548
549         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
550         tgtdev = __mpi3mr_get_tgtdev_by_handle(mrioc, handle);
551         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
552         return tgtdev;
553 }
554
555 /**
556  * __mpi3mr_get_tgtdev_by_perst_id -Get tgtdev from persist ID
557  * @mrioc: Adapter instance reference
558  * @persist_id: Persistent ID
559  *
560  * Accessor to retrieve target device from the Persistent ID.
561  * Non Lock version
562  *
563  * Return: Target device reference.
564  */
565 static struct mpi3mr_tgt_dev  *__mpi3mr_get_tgtdev_by_perst_id(
566         struct mpi3mr_ioc *mrioc, u16 persist_id)
567 {
568         struct mpi3mr_tgt_dev *tgtdev;
569
570         assert_spin_locked(&mrioc->tgtdev_lock);
571         list_for_each_entry(tgtdev, &mrioc->tgtdev_list, list)
572                 if (tgtdev->perst_id == persist_id)
573                         goto found_tgtdev;
574         return NULL;
575
576 found_tgtdev:
577         mpi3mr_tgtdev_get(tgtdev);
578         return tgtdev;
579 }
580
581 /**
582  * mpi3mr_get_tgtdev_by_perst_id -Get tgtdev from persistent ID
583  * @mrioc: Adapter instance reference
584  * @persist_id: Persistent ID
585  *
586  * Accessor to retrieve target device from the Persistent ID.
587  * Lock version
588  *
589  * Return: Target device reference.
590  */
591 static struct mpi3mr_tgt_dev *mpi3mr_get_tgtdev_by_perst_id(
592         struct mpi3mr_ioc *mrioc, u16 persist_id)
593 {
594         struct mpi3mr_tgt_dev *tgtdev;
595         unsigned long flags;
596
597         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
598         tgtdev = __mpi3mr_get_tgtdev_by_perst_id(mrioc, persist_id);
599         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
600         return tgtdev;
601 }
602
603 /**
604  * __mpi3mr_get_tgtdev_from_tgtpriv -Get tgtdev from tgt private
605  * @mrioc: Adapter instance reference
606  * @tgt_priv: Target private data
607  *
608  * Accessor to return target device from the target private
609  * data. Non Lock version
610  *
611  * Return: Target device reference.
612  */
613 static struct mpi3mr_tgt_dev  *__mpi3mr_get_tgtdev_from_tgtpriv(
614         struct mpi3mr_ioc *mrioc, struct mpi3mr_stgt_priv_data *tgt_priv)
615 {
616         struct mpi3mr_tgt_dev *tgtdev;
617
618         assert_spin_locked(&mrioc->tgtdev_lock);
619         tgtdev = tgt_priv->tgt_dev;
620         if (tgtdev)
621                 mpi3mr_tgtdev_get(tgtdev);
622         return tgtdev;
623 }
624
625 /**
626  * mpi3mr_remove_tgtdev_from_host - Remove dev from upper layers
627  * @mrioc: Adapter instance reference
628  * @tgtdev: Target device structure
629  *
630  * Checks whether the device is exposed to upper layers and if it
631  * is then remove the device from upper layers by calling
632  * scsi_remove_target().
633  *
634  * Return: 0 on success, non zero on failure.
635  */
636 static void mpi3mr_remove_tgtdev_from_host(struct mpi3mr_ioc *mrioc,
637         struct mpi3mr_tgt_dev *tgtdev)
638 {
639         struct mpi3mr_stgt_priv_data *tgt_priv;
640
641         ioc_info(mrioc, "%s :Removing handle(0x%04x), wwid(0x%016llx)\n",
642             __func__, tgtdev->dev_handle, (unsigned long long)tgtdev->wwid);
643         if (tgtdev->starget && tgtdev->starget->hostdata) {
644                 tgt_priv = tgtdev->starget->hostdata;
645                 tgt_priv->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
646         }
647
648         if (tgtdev->starget) {
649                 scsi_remove_target(&tgtdev->starget->dev);
650                 tgtdev->host_exposed = 0;
651         }
652         ioc_info(mrioc, "%s :Removed handle(0x%04x), wwid(0x%016llx)\n",
653             __func__, tgtdev->dev_handle, (unsigned long long)tgtdev->wwid);
654 }
655
656 /**
657  * mpi3mr_report_tgtdev_to_host - Expose device to upper layers
658  * @mrioc: Adapter instance reference
659  * @perst_id: Persistent ID of the device
660  *
661  * Checks whether the device can be exposed to upper layers and
662  * if it is not then expose the device to upper layers by
663  * calling scsi_scan_target().
664  *
665  * Return: 0 on success, non zero on failure.
666  */
667 static int mpi3mr_report_tgtdev_to_host(struct mpi3mr_ioc *mrioc,
668         u16 perst_id)
669 {
670         int retval = 0;
671         struct mpi3mr_tgt_dev *tgtdev;
672
673         tgtdev = mpi3mr_get_tgtdev_by_perst_id(mrioc, perst_id);
674         if (!tgtdev) {
675                 retval = -1;
676                 goto out;
677         }
678         if (tgtdev->is_hidden) {
679                 retval = -1;
680                 goto out;
681         }
682         if (!tgtdev->host_exposed && !mrioc->reset_in_progress) {
683                 tgtdev->host_exposed = 1;
684                 scsi_scan_target(&mrioc->shost->shost_gendev, 0,
685                     tgtdev->perst_id,
686                     SCAN_WILD_CARD, SCSI_SCAN_INITIAL);
687                 if (!tgtdev->starget)
688                         tgtdev->host_exposed = 0;
689         }
690 out:
691         if (tgtdev)
692                 mpi3mr_tgtdev_put(tgtdev);
693
694         return retval;
695 }
696
697 /**
698  * mpi3mr_change_queue_depth- Change QD callback handler
699  * @sdev: SCSI device reference
700  * @q_depth: Queue depth
701  *
702  * Validate and limit QD and call scsi_change_queue_depth.
703  *
704  * Return: return value of scsi_change_queue_depth
705  */
706 static int mpi3mr_change_queue_depth(struct scsi_device *sdev,
707         int q_depth)
708 {
709         struct scsi_target *starget = scsi_target(sdev);
710         struct Scsi_Host *shost = dev_to_shost(&starget->dev);
711         int retval = 0;
712
713         if (!sdev->tagged_supported)
714                 q_depth = 1;
715         if (q_depth > shost->can_queue)
716                 q_depth = shost->can_queue;
717         else if (!q_depth)
718                 q_depth = MPI3MR_DEFAULT_SDEV_QD;
719         retval = scsi_change_queue_depth(sdev, q_depth);
720
721         return retval;
722 }
723
724 /**
725  * mpi3mr_update_sdev - Update SCSI device information
726  * @sdev: SCSI device reference
727  * @data: target device reference
728  *
729  * This is an iterator function called for each SCSI device in a
730  * target to update the target specific information into each
731  * SCSI device.
732  *
733  * Return: Nothing.
734  */
735 static void
736 mpi3mr_update_sdev(struct scsi_device *sdev, void *data)
737 {
738         struct mpi3mr_tgt_dev *tgtdev;
739
740         tgtdev = (struct mpi3mr_tgt_dev *)data;
741         if (!tgtdev)
742                 return;
743
744         mpi3mr_change_queue_depth(sdev, tgtdev->q_depth);
745         switch (tgtdev->dev_type) {
746         case MPI3_DEVICE_DEVFORM_PCIE:
747                 /*The block layer hw sector size = 512*/
748                 if ((tgtdev->dev_spec.pcie_inf.dev_info &
749                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) ==
750                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_NVME_DEVICE) {
751                         blk_queue_max_hw_sectors(sdev->request_queue,
752                             tgtdev->dev_spec.pcie_inf.mdts / 512);
753                         if (tgtdev->dev_spec.pcie_inf.pgsz == 0)
754                                 blk_queue_virt_boundary(sdev->request_queue,
755                                     ((1 << MPI3MR_DEFAULT_PGSZEXP) - 1));
756                         else
757                                 blk_queue_virt_boundary(sdev->request_queue,
758                                     ((1 << tgtdev->dev_spec.pcie_inf.pgsz) - 1));
759                 }
760                 break;
761         default:
762                 break;
763         }
764 }
765
766 /**
767  * mpi3mr_rfresh_tgtdevs - Refresh target device exposure
768  * @mrioc: Adapter instance reference
769  *
770  * This is executed post controller reset to identify any
771  * missing devices during reset and remove from the upper layers
772  * or expose any newly detected device to the upper layers.
773  *
774  * Return: Nothing.
775  */
776
777 void mpi3mr_rfresh_tgtdevs(struct mpi3mr_ioc *mrioc)
778 {
779         struct mpi3mr_tgt_dev *tgtdev, *tgtdev_next;
780
781         list_for_each_entry_safe(tgtdev, tgtdev_next, &mrioc->tgtdev_list,
782             list) {
783                 if ((tgtdev->dev_handle == MPI3MR_INVALID_DEV_HANDLE) &&
784                     tgtdev->host_exposed) {
785                         mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
786                         mpi3mr_tgtdev_del_from_list(mrioc, tgtdev);
787                         mpi3mr_tgtdev_put(tgtdev);
788                 }
789         }
790
791         tgtdev = NULL;
792         list_for_each_entry(tgtdev, &mrioc->tgtdev_list, list) {
793                 if ((tgtdev->dev_handle != MPI3MR_INVALID_DEV_HANDLE) &&
794                     !tgtdev->is_hidden && !tgtdev->host_exposed)
795                         mpi3mr_report_tgtdev_to_host(mrioc, tgtdev->perst_id);
796         }
797 }
798
799 /**
800  * mpi3mr_update_tgtdev - DevStatusChange evt bottomhalf
801  * @mrioc: Adapter instance reference
802  * @tgtdev: Target device internal structure
803  * @dev_pg0: New device page0
804  *
805  * Update the information from the device page0 into the driver
806  * cached target device structure.
807  *
808  * Return: Nothing.
809  */
810 static void mpi3mr_update_tgtdev(struct mpi3mr_ioc *mrioc,
811         struct mpi3mr_tgt_dev *tgtdev, struct mpi3_device_page0 *dev_pg0)
812 {
813         u16 flags = 0;
814         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data;
815         u8 prot_mask = 0;
816
817         tgtdev->perst_id = le16_to_cpu(dev_pg0->persistent_id);
818         tgtdev->dev_handle = le16_to_cpu(dev_pg0->dev_handle);
819         tgtdev->dev_type = dev_pg0->device_form;
820         tgtdev->encl_handle = le16_to_cpu(dev_pg0->enclosure_handle);
821         tgtdev->parent_handle = le16_to_cpu(dev_pg0->parent_dev_handle);
822         tgtdev->slot = le16_to_cpu(dev_pg0->slot);
823         tgtdev->q_depth = le16_to_cpu(dev_pg0->queue_depth);
824         tgtdev->wwid = le64_to_cpu(dev_pg0->wwid);
825
826         flags = le16_to_cpu(dev_pg0->flags);
827         tgtdev->is_hidden = (flags & MPI3_DEVICE0_FLAGS_HIDDEN);
828
829         if (tgtdev->starget && tgtdev->starget->hostdata) {
830                 scsi_tgt_priv_data = (struct mpi3mr_stgt_priv_data *)
831                     tgtdev->starget->hostdata;
832                 scsi_tgt_priv_data->perst_id = tgtdev->perst_id;
833                 scsi_tgt_priv_data->dev_handle = tgtdev->dev_handle;
834                 scsi_tgt_priv_data->dev_type = tgtdev->dev_type;
835         }
836
837         switch (dev_pg0->access_status) {
838         case MPI3_DEVICE0_ASTATUS_NO_ERRORS:
839         case MPI3_DEVICE0_ASTATUS_PREPARE:
840         case MPI3_DEVICE0_ASTATUS_NEEDS_INITIALIZATION:
841         case MPI3_DEVICE0_ASTATUS_DEVICE_MISSING_DELAY:
842                 break;
843         default:
844                 tgtdev->is_hidden = 1;
845                 break;
846         }
847
848         switch (tgtdev->dev_type) {
849         case MPI3_DEVICE_DEVFORM_SAS_SATA:
850         {
851                 struct mpi3_device0_sas_sata_format *sasinf =
852                     &dev_pg0->device_specific.sas_sata_format;
853                 u16 dev_info = le16_to_cpu(sasinf->device_info);
854
855                 tgtdev->dev_spec.sas_sata_inf.dev_info = dev_info;
856                 tgtdev->dev_spec.sas_sata_inf.sas_address =
857                     le64_to_cpu(sasinf->sas_address);
858                 if ((dev_info & MPI3_SAS_DEVICE_INFO_DEVICE_TYPE_MASK) !=
859                     MPI3_SAS_DEVICE_INFO_DEVICE_TYPE_END_DEVICE)
860                         tgtdev->is_hidden = 1;
861                 else if (!(dev_info & (MPI3_SAS_DEVICE_INFO_STP_SATA_TARGET |
862                     MPI3_SAS_DEVICE_INFO_SSP_TARGET)))
863                         tgtdev->is_hidden = 1;
864                 break;
865         }
866         case MPI3_DEVICE_DEVFORM_PCIE:
867         {
868                 struct mpi3_device0_pcie_format *pcieinf =
869                     &dev_pg0->device_specific.pcie_format;
870                 u16 dev_info = le16_to_cpu(pcieinf->device_info);
871
872                 tgtdev->dev_spec.pcie_inf.dev_info = dev_info;
873                 tgtdev->dev_spec.pcie_inf.capb =
874                     le32_to_cpu(pcieinf->capabilities);
875                 tgtdev->dev_spec.pcie_inf.mdts = MPI3MR_DEFAULT_MDTS;
876                 /* 2^12 = 4096 */
877                 tgtdev->dev_spec.pcie_inf.pgsz = 12;
878                 if (dev_pg0->access_status == MPI3_DEVICE0_ASTATUS_NO_ERRORS) {
879                         tgtdev->dev_spec.pcie_inf.mdts =
880                             le32_to_cpu(pcieinf->maximum_data_transfer_size);
881                         tgtdev->dev_spec.pcie_inf.pgsz = pcieinf->page_size;
882                         tgtdev->dev_spec.pcie_inf.reset_to =
883                             max_t(u8, pcieinf->controller_reset_to,
884                              MPI3MR_INTADMCMD_TIMEOUT);
885                         tgtdev->dev_spec.pcie_inf.abort_to =
886                             max_t(u8, pcieinf->nvme_abort_to,
887                             MPI3MR_INTADMCMD_TIMEOUT);
888                 }
889                 if (tgtdev->dev_spec.pcie_inf.mdts > (1024 * 1024))
890                         tgtdev->dev_spec.pcie_inf.mdts = (1024 * 1024);
891                 if (((dev_info & MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) !=
892                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_NVME_DEVICE) &&
893                     ((dev_info & MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) !=
894                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_SCSI_DEVICE))
895                         tgtdev->is_hidden = 1;
896                 if (!mrioc->shost)
897                         break;
898                 prot_mask = scsi_host_get_prot(mrioc->shost);
899                 if (prot_mask & SHOST_DIX_TYPE0_PROTECTION) {
900                         scsi_host_set_prot(mrioc->shost, prot_mask & 0x77);
901                         ioc_info(mrioc,
902                             "%s : Disabling DIX0 prot capability\n", __func__);
903                         ioc_info(mrioc,
904                             "because HBA does not support DIX0 operation on NVME drives\n");
905                 }
906                 break;
907         }
908         case MPI3_DEVICE_DEVFORM_VD:
909         {
910                 struct mpi3_device0_vd_format *vdinf =
911                     &dev_pg0->device_specific.vd_format;
912
913                 tgtdev->dev_spec.vol_inf.state = vdinf->vd_state;
914                 if (vdinf->vd_state == MPI3_DEVICE0_VD_STATE_OFFLINE)
915                         tgtdev->is_hidden = 1;
916                 break;
917         }
918         default:
919                 break;
920         }
921 }
922
923 /**
924  * mpi3mr_devstatuschg_evt_bh - DevStatusChange evt bottomhalf
925  * @mrioc: Adapter instance reference
926  * @fwevt: Firmware event information.
927  *
928  * Process Device status Change event and based on device's new
929  * information, either expose the device to the upper layers, or
930  * remove the device from upper layers.
931  *
932  * Return: Nothing.
933  */
934 static void mpi3mr_devstatuschg_evt_bh(struct mpi3mr_ioc *mrioc,
935         struct mpi3mr_fwevt *fwevt)
936 {
937         u16 dev_handle = 0;
938         u8 uhide = 0, delete = 0, cleanup = 0;
939         struct mpi3mr_tgt_dev *tgtdev = NULL;
940         struct mpi3_event_data_device_status_change *evtdata =
941             (struct mpi3_event_data_device_status_change *)fwevt->event_data;
942
943         dev_handle = le16_to_cpu(evtdata->dev_handle);
944         ioc_info(mrioc,
945             "%s :device status change: handle(0x%04x): reason code(0x%x)\n",
946             __func__, dev_handle, evtdata->reason_code);
947         switch (evtdata->reason_code) {
948         case MPI3_EVENT_DEV_STAT_RC_HIDDEN:
949                 delete = 1;
950                 break;
951         case MPI3_EVENT_DEV_STAT_RC_NOT_HIDDEN:
952                 uhide = 1;
953                 break;
954         case MPI3_EVENT_DEV_STAT_RC_VD_NOT_RESPONDING:
955                 delete = 1;
956                 cleanup = 1;
957                 break;
958         default:
959                 ioc_info(mrioc, "%s :Unhandled reason code(0x%x)\n", __func__,
960                     evtdata->reason_code);
961                 break;
962         }
963
964         tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, dev_handle);
965         if (!tgtdev)
966                 goto out;
967         if (uhide) {
968                 tgtdev->is_hidden = 0;
969                 if (!tgtdev->host_exposed)
970                         mpi3mr_report_tgtdev_to_host(mrioc, tgtdev->perst_id);
971         }
972         if (tgtdev->starget && tgtdev->starget->hostdata) {
973                 if (delete)
974                         mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
975         }
976         if (cleanup) {
977                 mpi3mr_tgtdev_del_from_list(mrioc, tgtdev);
978                 mpi3mr_tgtdev_put(tgtdev);
979         }
980
981 out:
982         if (tgtdev)
983                 mpi3mr_tgtdev_put(tgtdev);
984 }
985
986 /**
987  * mpi3mr_devinfochg_evt_bh - DeviceInfoChange evt bottomhalf
988  * @mrioc: Adapter instance reference
989  * @dev_pg0: New device page0
990  *
991  * Process Device Info Change event and based on device's new
992  * information, either expose the device to the upper layers, or
993  * remove the device from upper layers or update the details of
994  * the device.
995  *
996  * Return: Nothing.
997  */
998 static void mpi3mr_devinfochg_evt_bh(struct mpi3mr_ioc *mrioc,
999         struct mpi3_device_page0 *dev_pg0)
1000 {
1001         struct mpi3mr_tgt_dev *tgtdev = NULL;
1002         u16 dev_handle = 0, perst_id = 0;
1003
1004         perst_id = le16_to_cpu(dev_pg0->persistent_id);
1005         dev_handle = le16_to_cpu(dev_pg0->dev_handle);
1006         ioc_info(mrioc,
1007             "%s :Device info change: handle(0x%04x): persist_id(0x%x)\n",
1008             __func__, dev_handle, perst_id);
1009         tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, dev_handle);
1010         if (!tgtdev)
1011                 goto out;
1012         mpi3mr_update_tgtdev(mrioc, tgtdev, dev_pg0);
1013         if (!tgtdev->is_hidden && !tgtdev->host_exposed)
1014                 mpi3mr_report_tgtdev_to_host(mrioc, perst_id);
1015         if (tgtdev->is_hidden && tgtdev->host_exposed)
1016                 mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
1017         if (!tgtdev->is_hidden && tgtdev->host_exposed && tgtdev->starget)
1018                 starget_for_each_device(tgtdev->starget, (void *)tgtdev,
1019                     mpi3mr_update_sdev);
1020 out:
1021         if (tgtdev)
1022                 mpi3mr_tgtdev_put(tgtdev);
1023 }
1024
1025 /**
1026  * mpi3mr_sastopochg_evt_debug - SASTopoChange details
1027  * @mrioc: Adapter instance reference
1028  * @event_data: SAS topology change list event data
1029  *
1030  * Prints information about the SAS topology change event.
1031  *
1032  * Return: Nothing.
1033  */
1034 static void
1035 mpi3mr_sastopochg_evt_debug(struct mpi3mr_ioc *mrioc,
1036         struct mpi3_event_data_sas_topology_change_list *event_data)
1037 {
1038         int i;
1039         u16 handle;
1040         u8 reason_code, phy_number;
1041         char *status_str = NULL;
1042         u8 link_rate, prev_link_rate;
1043
1044         switch (event_data->exp_status) {
1045         case MPI3_EVENT_SAS_TOPO_ES_NOT_RESPONDING:
1046                 status_str = "remove";
1047                 break;
1048         case MPI3_EVENT_SAS_TOPO_ES_RESPONDING:
1049                 status_str =  "responding";
1050                 break;
1051         case MPI3_EVENT_SAS_TOPO_ES_DELAY_NOT_RESPONDING:
1052                 status_str = "remove delay";
1053                 break;
1054         case MPI3_EVENT_SAS_TOPO_ES_NO_EXPANDER:
1055                 status_str = "direct attached";
1056                 break;
1057         default:
1058                 status_str = "unknown status";
1059                 break;
1060         }
1061         ioc_info(mrioc, "%s :sas topology change: (%s)\n",
1062             __func__, status_str);
1063         ioc_info(mrioc,
1064             "%s :\texpander_handle(0x%04x), enclosure_handle(0x%04x) start_phy(%02d), num_entries(%d)\n",
1065             __func__, le16_to_cpu(event_data->expander_dev_handle),
1066             le16_to_cpu(event_data->enclosure_handle),
1067             event_data->start_phy_num, event_data->num_entries);
1068         for (i = 0; i < event_data->num_entries; i++) {
1069                 handle = le16_to_cpu(event_data->phy_entry[i].attached_dev_handle);
1070                 if (!handle)
1071                         continue;
1072                 phy_number = event_data->start_phy_num + i;
1073                 reason_code = event_data->phy_entry[i].status &
1074                     MPI3_EVENT_SAS_TOPO_PHY_RC_MASK;
1075                 switch (reason_code) {
1076                 case MPI3_EVENT_SAS_TOPO_PHY_RC_TARG_NOT_RESPONDING:
1077                         status_str = "target remove";
1078                         break;
1079                 case MPI3_EVENT_SAS_TOPO_PHY_RC_DELAY_NOT_RESPONDING:
1080                         status_str = "delay target remove";
1081                         break;
1082                 case MPI3_EVENT_SAS_TOPO_PHY_RC_PHY_CHANGED:
1083                         status_str = "link status change";
1084                         break;
1085                 case MPI3_EVENT_SAS_TOPO_PHY_RC_NO_CHANGE:
1086                         status_str = "link status no change";
1087                         break;
1088                 case MPI3_EVENT_SAS_TOPO_PHY_RC_RESPONDING:
1089                         status_str = "target responding";
1090                         break;
1091                 default:
1092                         status_str = "unknown";
1093                         break;
1094                 }
1095                 link_rate = event_data->phy_entry[i].link_rate >> 4;
1096                 prev_link_rate = event_data->phy_entry[i].link_rate & 0xF;
1097                 ioc_info(mrioc,
1098                     "%s :\tphy(%02d), attached_handle(0x%04x): %s: link rate: new(0x%02x), old(0x%02x)\n",
1099                     __func__, phy_number, handle, status_str, link_rate,
1100                     prev_link_rate);
1101         }
1102 }
1103
1104 /**
1105  * mpi3mr_sastopochg_evt_bh - SASTopologyChange evt bottomhalf
1106  * @mrioc: Adapter instance reference
1107  * @fwevt: Firmware event reference
1108  *
1109  * Prints information about the SAS topology change event and
1110  * for "not responding" event code, removes the device from the
1111  * upper layers.
1112  *
1113  * Return: Nothing.
1114  */
1115 static void mpi3mr_sastopochg_evt_bh(struct mpi3mr_ioc *mrioc,
1116         struct mpi3mr_fwevt *fwevt)
1117 {
1118         struct mpi3_event_data_sas_topology_change_list *event_data =
1119             (struct mpi3_event_data_sas_topology_change_list *)fwevt->event_data;
1120         int i;
1121         u16 handle;
1122         u8 reason_code;
1123         struct mpi3mr_tgt_dev *tgtdev = NULL;
1124
1125         mpi3mr_sastopochg_evt_debug(mrioc, event_data);
1126
1127         for (i = 0; i < event_data->num_entries; i++) {
1128                 handle = le16_to_cpu(event_data->phy_entry[i].attached_dev_handle);
1129                 if (!handle)
1130                         continue;
1131                 tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, handle);
1132                 if (!tgtdev)
1133                         continue;
1134
1135                 reason_code = event_data->phy_entry[i].status &
1136                     MPI3_EVENT_SAS_TOPO_PHY_RC_MASK;
1137
1138                 switch (reason_code) {
1139                 case MPI3_EVENT_SAS_TOPO_PHY_RC_TARG_NOT_RESPONDING:
1140                         if (tgtdev->host_exposed)
1141                                 mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
1142                         mpi3mr_tgtdev_del_from_list(mrioc, tgtdev);
1143                         mpi3mr_tgtdev_put(tgtdev);
1144                         break;
1145                 default:
1146                         break;
1147                 }
1148                 if (tgtdev)
1149                         mpi3mr_tgtdev_put(tgtdev);
1150         }
1151 }
1152
1153 /**
1154  * mpi3mr_pcietopochg_evt_debug - PCIeTopoChange details
1155  * @mrioc: Adapter instance reference
1156  * @event_data: PCIe topology change list event data
1157  *
1158  * Prints information about the PCIe topology change event.
1159  *
1160  * Return: Nothing.
1161  */
1162 static void
1163 mpi3mr_pcietopochg_evt_debug(struct mpi3mr_ioc *mrioc,
1164         struct mpi3_event_data_pcie_topology_change_list *event_data)
1165 {
1166         int i;
1167         u16 handle;
1168         u16 reason_code;
1169         u8 port_number;
1170         char *status_str = NULL;
1171         u8 link_rate, prev_link_rate;
1172
1173         switch (event_data->switch_status) {
1174         case MPI3_EVENT_PCIE_TOPO_SS_NOT_RESPONDING:
1175                 status_str = "remove";
1176                 break;
1177         case MPI3_EVENT_PCIE_TOPO_SS_RESPONDING:
1178                 status_str =  "responding";
1179                 break;
1180         case MPI3_EVENT_PCIE_TOPO_SS_DELAY_NOT_RESPONDING:
1181                 status_str = "remove delay";
1182                 break;
1183         case MPI3_EVENT_PCIE_TOPO_SS_NO_PCIE_SWITCH:
1184                 status_str = "direct attached";
1185                 break;
1186         default:
1187                 status_str = "unknown status";
1188                 break;
1189         }
1190         ioc_info(mrioc, "%s :pcie topology change: (%s)\n",
1191             __func__, status_str);
1192         ioc_info(mrioc,
1193             "%s :\tswitch_handle(0x%04x), enclosure_handle(0x%04x) start_port(%02d), num_entries(%d)\n",
1194             __func__, le16_to_cpu(event_data->switch_dev_handle),
1195             le16_to_cpu(event_data->enclosure_handle),
1196             event_data->start_port_num, event_data->num_entries);
1197         for (i = 0; i < event_data->num_entries; i++) {
1198                 handle =
1199                     le16_to_cpu(event_data->port_entry[i].attached_dev_handle);
1200                 if (!handle)
1201                         continue;
1202                 port_number = event_data->start_port_num + i;
1203                 reason_code = event_data->port_entry[i].port_status;
1204                 switch (reason_code) {
1205                 case MPI3_EVENT_PCIE_TOPO_PS_NOT_RESPONDING:
1206                         status_str = "target remove";
1207                         break;
1208                 case MPI3_EVENT_PCIE_TOPO_PS_DELAY_NOT_RESPONDING:
1209                         status_str = "delay target remove";
1210                         break;
1211                 case MPI3_EVENT_PCIE_TOPO_PS_PORT_CHANGED:
1212                         status_str = "link status change";
1213                         break;
1214                 case MPI3_EVENT_PCIE_TOPO_PS_NO_CHANGE:
1215                         status_str = "link status no change";
1216                         break;
1217                 case MPI3_EVENT_PCIE_TOPO_PS_RESPONDING:
1218                         status_str = "target responding";
1219                         break;
1220                 default:
1221                         status_str = "unknown";
1222                         break;
1223                 }
1224                 link_rate = event_data->port_entry[i].current_port_info &
1225                     MPI3_EVENT_PCIE_TOPO_PI_RATE_MASK;
1226                 prev_link_rate = event_data->port_entry[i].previous_port_info &
1227                     MPI3_EVENT_PCIE_TOPO_PI_RATE_MASK;
1228                 ioc_info(mrioc,
1229                     "%s :\tport(%02d), attached_handle(0x%04x): %s: link rate: new(0x%02x), old(0x%02x)\n",
1230                     __func__, port_number, handle, status_str, link_rate,
1231                     prev_link_rate);
1232         }
1233 }
1234
1235 /**
1236  * mpi3mr_pcietopochg_evt_bh - PCIeTopologyChange evt bottomhalf
1237  * @mrioc: Adapter instance reference
1238  * @fwevt: Firmware event reference
1239  *
1240  * Prints information about the PCIe topology change event and
1241  * for "not responding" event code, removes the device from the
1242  * upper layers.
1243  *
1244  * Return: Nothing.
1245  */
1246 static void mpi3mr_pcietopochg_evt_bh(struct mpi3mr_ioc *mrioc,
1247         struct mpi3mr_fwevt *fwevt)
1248 {
1249         struct mpi3_event_data_pcie_topology_change_list *event_data =
1250             (struct mpi3_event_data_pcie_topology_change_list *)fwevt->event_data;
1251         int i;
1252         u16 handle;
1253         u8 reason_code;
1254         struct mpi3mr_tgt_dev *tgtdev = NULL;
1255
1256         mpi3mr_pcietopochg_evt_debug(mrioc, event_data);
1257
1258         for (i = 0; i < event_data->num_entries; i++) {
1259                 handle =
1260                     le16_to_cpu(event_data->port_entry[i].attached_dev_handle);
1261                 if (!handle)
1262                         continue;
1263                 tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, handle);
1264                 if (!tgtdev)
1265                         continue;
1266
1267                 reason_code = event_data->port_entry[i].port_status;
1268
1269                 switch (reason_code) {
1270                 case MPI3_EVENT_PCIE_TOPO_PS_NOT_RESPONDING:
1271                         if (tgtdev->host_exposed)
1272                                 mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
1273                         mpi3mr_tgtdev_del_from_list(mrioc, tgtdev);
1274                         mpi3mr_tgtdev_put(tgtdev);
1275                         break;
1276                 default:
1277                         break;
1278                 }
1279                 if (tgtdev)
1280                         mpi3mr_tgtdev_put(tgtdev);
1281         }
1282 }
1283
1284 /**
1285  * mpi3mr_fwevt_bh - Firmware event bottomhalf handler
1286  * @mrioc: Adapter instance reference
1287  * @fwevt: Firmware event reference
1288  *
1289  * Identifies the firmware event and calls corresponding bottomg
1290  * half handler and sends event acknowledgment if required.
1291  *
1292  * Return: Nothing.
1293  */
1294 static void mpi3mr_fwevt_bh(struct mpi3mr_ioc *mrioc,
1295         struct mpi3mr_fwevt *fwevt)
1296 {
1297         mrioc->current_event = fwevt;
1298         mpi3mr_fwevt_del_from_list(mrioc, fwevt);
1299
1300         if (mrioc->stop_drv_processing)
1301                 goto out;
1302
1303         if (!fwevt->process_evt)
1304                 goto evt_ack;
1305
1306         switch (fwevt->event_id) {
1307         case MPI3_EVENT_DEVICE_ADDED:
1308         {
1309                 struct mpi3_device_page0 *dev_pg0 =
1310                     (struct mpi3_device_page0 *)fwevt->event_data;
1311                 mpi3mr_report_tgtdev_to_host(mrioc,
1312                     le16_to_cpu(dev_pg0->persistent_id));
1313                 break;
1314         }
1315         case MPI3_EVENT_DEVICE_INFO_CHANGED:
1316         {
1317                 mpi3mr_devinfochg_evt_bh(mrioc,
1318                     (struct mpi3_device_page0 *)fwevt->event_data);
1319                 break;
1320         }
1321         case MPI3_EVENT_DEVICE_STATUS_CHANGE:
1322         {
1323                 mpi3mr_devstatuschg_evt_bh(mrioc, fwevt);
1324                 break;
1325         }
1326         case MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
1327         {
1328                 mpi3mr_sastopochg_evt_bh(mrioc, fwevt);
1329                 break;
1330         }
1331         case MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
1332         {
1333                 mpi3mr_pcietopochg_evt_bh(mrioc, fwevt);
1334                 break;
1335         }
1336         default:
1337                 break;
1338         }
1339
1340 evt_ack:
1341         if (fwevt->send_ack)
1342                 mpi3mr_process_event_ack(mrioc, fwevt->event_id,
1343                     fwevt->evt_ctx);
1344 out:
1345         /* Put fwevt reference count to neutralize kref_init increment */
1346         mpi3mr_fwevt_put(fwevt);
1347         mrioc->current_event = NULL;
1348 }
1349
1350 /**
1351  * mpi3mr_fwevt_worker - Firmware event worker
1352  * @work: Work struct containing firmware event
1353  *
1354  * Extracts the firmware event and calls mpi3mr_fwevt_bh.
1355  *
1356  * Return: Nothing.
1357  */
1358 static void mpi3mr_fwevt_worker(struct work_struct *work)
1359 {
1360         struct mpi3mr_fwevt *fwevt = container_of(work, struct mpi3mr_fwevt,
1361             work);
1362         mpi3mr_fwevt_bh(fwevt->mrioc, fwevt);
1363         /*
1364          * Put fwevt reference count after
1365          * dequeuing it from worker queue
1366          */
1367         mpi3mr_fwevt_put(fwevt);
1368 }
1369
1370 /**
1371  * mpi3mr_create_tgtdev - Create and add a target device
1372  * @mrioc: Adapter instance reference
1373  * @dev_pg0: Device Page 0 data
1374  *
1375  * If the device specified by the device page 0 data is not
1376  * present in the driver's internal list, allocate the memory
1377  * for the device, populate the data and add to the list, else
1378  * update the device data.  The key is persistent ID.
1379  *
1380  * Return: 0 on success, -ENOMEM on memory allocation failure
1381  */
1382 static int mpi3mr_create_tgtdev(struct mpi3mr_ioc *mrioc,
1383         struct mpi3_device_page0 *dev_pg0)
1384 {
1385         int retval = 0;
1386         struct mpi3mr_tgt_dev *tgtdev = NULL;
1387         u16 perst_id = 0;
1388
1389         perst_id = le16_to_cpu(dev_pg0->persistent_id);
1390         tgtdev = mpi3mr_get_tgtdev_by_perst_id(mrioc, perst_id);
1391         if (tgtdev) {
1392                 mpi3mr_update_tgtdev(mrioc, tgtdev, dev_pg0);
1393                 mpi3mr_tgtdev_put(tgtdev);
1394         } else {
1395                 tgtdev = mpi3mr_alloc_tgtdev();
1396                 if (!tgtdev)
1397                         return -ENOMEM;
1398                 mpi3mr_update_tgtdev(mrioc, tgtdev, dev_pg0);
1399                 mpi3mr_tgtdev_add_to_list(mrioc, tgtdev);
1400         }
1401
1402         return retval;
1403 }
1404
1405 /**
1406  * mpi3mr_flush_delayed_cmd_lists - Flush pending commands
1407  * @mrioc: Adapter instance reference
1408  *
1409  * Flush pending commands in the delayed lists due to a
1410  * controller reset or driver removal as a cleanup.
1411  *
1412  * Return: Nothing
1413  */
1414 void mpi3mr_flush_delayed_cmd_lists(struct mpi3mr_ioc *mrioc)
1415 {
1416         struct delayed_dev_rmhs_node *_rmhs_node;
1417         struct delayed_evt_ack_node *_evtack_node;
1418
1419         dprint_reset(mrioc, "flushing delayed dev_remove_hs commands\n");
1420         while (!list_empty(&mrioc->delayed_rmhs_list)) {
1421                 _rmhs_node = list_entry(mrioc->delayed_rmhs_list.next,
1422                     struct delayed_dev_rmhs_node, list);
1423                 list_del(&_rmhs_node->list);
1424                 kfree(_rmhs_node);
1425         }
1426         dprint_reset(mrioc, "flushing delayed event ack commands\n");
1427         while (!list_empty(&mrioc->delayed_evtack_cmds_list)) {
1428                 _evtack_node = list_entry(mrioc->delayed_evtack_cmds_list.next,
1429                     struct delayed_evt_ack_node, list);
1430                 list_del(&_evtack_node->list);
1431                 kfree(_evtack_node);
1432         }
1433 }
1434
1435 /**
1436  * mpi3mr_dev_rmhs_complete_iou - Device removal IOUC completion
1437  * @mrioc: Adapter instance reference
1438  * @drv_cmd: Internal command tracker
1439  *
1440  * Issues a target reset TM to the firmware from the device
1441  * removal TM pend list or retry the removal handshake sequence
1442  * based on the IOU control request IOC status.
1443  *
1444  * Return: Nothing
1445  */
1446 static void mpi3mr_dev_rmhs_complete_iou(struct mpi3mr_ioc *mrioc,
1447         struct mpi3mr_drv_cmd *drv_cmd)
1448 {
1449         u16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
1450         struct delayed_dev_rmhs_node *delayed_dev_rmhs = NULL;
1451
1452         ioc_info(mrioc,
1453             "%s :dev_rmhs_iouctrl_complete:handle(0x%04x), ioc_status(0x%04x), loginfo(0x%08x)\n",
1454             __func__, drv_cmd->dev_handle, drv_cmd->ioc_status,
1455             drv_cmd->ioc_loginfo);
1456         if (drv_cmd->ioc_status != MPI3_IOCSTATUS_SUCCESS) {
1457                 if (drv_cmd->retry_count < MPI3MR_DEV_RMHS_RETRY_COUNT) {
1458                         drv_cmd->retry_count++;
1459                         ioc_info(mrioc,
1460                             "%s :dev_rmhs_iouctrl_complete: handle(0x%04x)retrying handshake retry=%d\n",
1461                             __func__, drv_cmd->dev_handle,
1462                             drv_cmd->retry_count);
1463                         mpi3mr_dev_rmhs_send_tm(mrioc, drv_cmd->dev_handle,
1464                             drv_cmd, drv_cmd->iou_rc);
1465                         return;
1466                 }
1467                 ioc_err(mrioc,
1468                     "%s :dev removal handshake failed after all retries: handle(0x%04x)\n",
1469                     __func__, drv_cmd->dev_handle);
1470         } else {
1471                 ioc_info(mrioc,
1472                     "%s :dev removal handshake completed successfully: handle(0x%04x)\n",
1473                     __func__, drv_cmd->dev_handle);
1474                 clear_bit(drv_cmd->dev_handle, mrioc->removepend_bitmap);
1475         }
1476
1477         if (!list_empty(&mrioc->delayed_rmhs_list)) {
1478                 delayed_dev_rmhs = list_entry(mrioc->delayed_rmhs_list.next,
1479                     struct delayed_dev_rmhs_node, list);
1480                 drv_cmd->dev_handle = delayed_dev_rmhs->handle;
1481                 drv_cmd->retry_count = 0;
1482                 drv_cmd->iou_rc = delayed_dev_rmhs->iou_rc;
1483                 ioc_info(mrioc,
1484                     "%s :dev_rmhs_iouctrl_complete: processing delayed TM: handle(0x%04x)\n",
1485                     __func__, drv_cmd->dev_handle);
1486                 mpi3mr_dev_rmhs_send_tm(mrioc, drv_cmd->dev_handle, drv_cmd,
1487                     drv_cmd->iou_rc);
1488                 list_del(&delayed_dev_rmhs->list);
1489                 kfree(delayed_dev_rmhs);
1490                 return;
1491         }
1492         drv_cmd->state = MPI3MR_CMD_NOTUSED;
1493         drv_cmd->callback = NULL;
1494         drv_cmd->retry_count = 0;
1495         drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
1496         clear_bit(cmd_idx, mrioc->devrem_bitmap);
1497 }
1498
1499 /**
1500  * mpi3mr_dev_rmhs_complete_tm - Device removal TM completion
1501  * @mrioc: Adapter instance reference
1502  * @drv_cmd: Internal command tracker
1503  *
1504  * Issues a target reset TM to the firmware from the device
1505  * removal TM pend list or issue IO unit control request as
1506  * part of device removal or hidden acknowledgment handshake.
1507  *
1508  * Return: Nothing
1509  */
1510 static void mpi3mr_dev_rmhs_complete_tm(struct mpi3mr_ioc *mrioc,
1511         struct mpi3mr_drv_cmd *drv_cmd)
1512 {
1513         struct mpi3_iounit_control_request iou_ctrl;
1514         u16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
1515         struct mpi3_scsi_task_mgmt_reply *tm_reply = NULL;
1516         int retval;
1517
1518         if (drv_cmd->state & MPI3MR_CMD_REPLY_VALID)
1519                 tm_reply = (struct mpi3_scsi_task_mgmt_reply *)drv_cmd->reply;
1520
1521         if (tm_reply)
1522                 pr_info(IOCNAME
1523                     "dev_rmhs_tr_complete:handle(0x%04x), ioc_status(0x%04x), loginfo(0x%08x), term_count(%d)\n",
1524                     mrioc->name, drv_cmd->dev_handle, drv_cmd->ioc_status,
1525                     drv_cmd->ioc_loginfo,
1526                     le32_to_cpu(tm_reply->termination_count));
1527
1528         pr_info(IOCNAME "Issuing IOU CTL: handle(0x%04x) dev_rmhs idx(%d)\n",
1529             mrioc->name, drv_cmd->dev_handle, cmd_idx);
1530
1531         memset(&iou_ctrl, 0, sizeof(iou_ctrl));
1532
1533         drv_cmd->state = MPI3MR_CMD_PENDING;
1534         drv_cmd->is_waiting = 0;
1535         drv_cmd->callback = mpi3mr_dev_rmhs_complete_iou;
1536         iou_ctrl.operation = drv_cmd->iou_rc;
1537         iou_ctrl.param16[0] = cpu_to_le16(drv_cmd->dev_handle);
1538         iou_ctrl.host_tag = cpu_to_le16(drv_cmd->host_tag);
1539         iou_ctrl.function = MPI3_FUNCTION_IO_UNIT_CONTROL;
1540
1541         retval = mpi3mr_admin_request_post(mrioc, &iou_ctrl, sizeof(iou_ctrl),
1542             1);
1543         if (retval) {
1544                 pr_err(IOCNAME "Issue DevRmHsTMIOUCTL: Admin post failed\n",
1545                     mrioc->name);
1546                 goto out_failed;
1547         }
1548
1549         return;
1550 out_failed:
1551         drv_cmd->state = MPI3MR_CMD_NOTUSED;
1552         drv_cmd->callback = NULL;
1553         drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
1554         drv_cmd->retry_count = 0;
1555         clear_bit(cmd_idx, mrioc->devrem_bitmap);
1556 }
1557
1558 /**
1559  * mpi3mr_dev_rmhs_send_tm - Issue TM for device removal
1560  * @mrioc: Adapter instance reference
1561  * @handle: Device handle
1562  * @cmdparam: Internal command tracker
1563  * @iou_rc: IO unit reason code
1564  *
1565  * Issues a target reset TM to the firmware or add it to a pend
1566  * list as part of device removal or hidden acknowledgment
1567  * handshake.
1568  *
1569  * Return: Nothing
1570  */
1571 static void mpi3mr_dev_rmhs_send_tm(struct mpi3mr_ioc *mrioc, u16 handle,
1572         struct mpi3mr_drv_cmd *cmdparam, u8 iou_rc)
1573 {
1574         struct mpi3_scsi_task_mgmt_request tm_req;
1575         int retval = 0;
1576         u16 cmd_idx = MPI3MR_NUM_DEVRMCMD;
1577         u8 retrycount = 5;
1578         struct mpi3mr_drv_cmd *drv_cmd = cmdparam;
1579         struct delayed_dev_rmhs_node *delayed_dev_rmhs = NULL;
1580
1581         if (drv_cmd)
1582                 goto issue_cmd;
1583         do {
1584                 cmd_idx = find_first_zero_bit(mrioc->devrem_bitmap,
1585                     MPI3MR_NUM_DEVRMCMD);
1586                 if (cmd_idx < MPI3MR_NUM_DEVRMCMD) {
1587                         if (!test_and_set_bit(cmd_idx, mrioc->devrem_bitmap))
1588                                 break;
1589                         cmd_idx = MPI3MR_NUM_DEVRMCMD;
1590                 }
1591         } while (retrycount--);
1592
1593         if (cmd_idx >= MPI3MR_NUM_DEVRMCMD) {
1594                 delayed_dev_rmhs = kzalloc(sizeof(*delayed_dev_rmhs),
1595                     GFP_ATOMIC);
1596                 if (!delayed_dev_rmhs)
1597                         return;
1598                 INIT_LIST_HEAD(&delayed_dev_rmhs->list);
1599                 delayed_dev_rmhs->handle = handle;
1600                 delayed_dev_rmhs->iou_rc = iou_rc;
1601                 list_add_tail(&delayed_dev_rmhs->list,
1602                     &mrioc->delayed_rmhs_list);
1603                 ioc_info(mrioc, "%s :DevRmHs: tr:handle(0x%04x) is postponed\n",
1604                     __func__, handle);
1605                 return;
1606         }
1607         drv_cmd = &mrioc->dev_rmhs_cmds[cmd_idx];
1608
1609 issue_cmd:
1610         cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
1611         ioc_info(mrioc,
1612             "%s :Issuing TR TM: for devhandle 0x%04x with dev_rmhs %d\n",
1613             __func__, handle, cmd_idx);
1614
1615         memset(&tm_req, 0, sizeof(tm_req));
1616         if (drv_cmd->state & MPI3MR_CMD_PENDING) {
1617                 ioc_err(mrioc, "%s :Issue TM: Command is in use\n", __func__);
1618                 goto out;
1619         }
1620         drv_cmd->state = MPI3MR_CMD_PENDING;
1621         drv_cmd->is_waiting = 0;
1622         drv_cmd->callback = mpi3mr_dev_rmhs_complete_tm;
1623         drv_cmd->dev_handle = handle;
1624         drv_cmd->iou_rc = iou_rc;
1625         tm_req.dev_handle = cpu_to_le16(handle);
1626         tm_req.task_type = MPI3_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
1627         tm_req.host_tag = cpu_to_le16(drv_cmd->host_tag);
1628         tm_req.task_host_tag = cpu_to_le16(MPI3MR_HOSTTAG_INVALID);
1629         tm_req.function = MPI3_FUNCTION_SCSI_TASK_MGMT;
1630
1631         set_bit(handle, mrioc->removepend_bitmap);
1632         retval = mpi3mr_admin_request_post(mrioc, &tm_req, sizeof(tm_req), 1);
1633         if (retval) {
1634                 ioc_err(mrioc, "%s :Issue DevRmHsTM: Admin Post failed\n",
1635                     __func__);
1636                 goto out_failed;
1637         }
1638 out:
1639         return;
1640 out_failed:
1641         drv_cmd->state = MPI3MR_CMD_NOTUSED;
1642         drv_cmd->callback = NULL;
1643         drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
1644         drv_cmd->retry_count = 0;
1645         clear_bit(cmd_idx, mrioc->devrem_bitmap);
1646 }
1647
1648 /**
1649  * mpi3mr_complete_evt_ack - event ack request completion
1650  * @mrioc: Adapter instance reference
1651  * @drv_cmd: Internal command tracker
1652  *
1653  * This is the completion handler for non blocking event
1654  * acknowledgment sent to the firmware and this will issue any
1655  * pending event acknowledgment request.
1656  *
1657  * Return: Nothing
1658  */
1659 static void mpi3mr_complete_evt_ack(struct mpi3mr_ioc *mrioc,
1660         struct mpi3mr_drv_cmd *drv_cmd)
1661 {
1662         u16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_EVTACKCMD_MIN;
1663         struct delayed_evt_ack_node *delayed_evtack = NULL;
1664
1665         if (drv_cmd->ioc_status != MPI3_IOCSTATUS_SUCCESS) {
1666                 dprint_event_th(mrioc,
1667                     "immediate event ack failed with ioc_status(0x%04x) log_info(0x%08x)\n",
1668                     (drv_cmd->ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
1669                     drv_cmd->ioc_loginfo);
1670         }
1671
1672         if (!list_empty(&mrioc->delayed_evtack_cmds_list)) {
1673                 delayed_evtack =
1674                         list_entry(mrioc->delayed_evtack_cmds_list.next,
1675                             struct delayed_evt_ack_node, list);
1676                 mpi3mr_send_event_ack(mrioc, delayed_evtack->event, drv_cmd,
1677                     delayed_evtack->event_ctx);
1678                 list_del(&delayed_evtack->list);
1679                 kfree(delayed_evtack);
1680                 return;
1681         }
1682         drv_cmd->state = MPI3MR_CMD_NOTUSED;
1683         drv_cmd->callback = NULL;
1684         clear_bit(cmd_idx, mrioc->evtack_cmds_bitmap);
1685 }
1686
1687 /**
1688  * mpi3mr_send_event_ack - Issue event acknwoledgment request
1689  * @mrioc: Adapter instance reference
1690  * @event: MPI3 event id
1691  * @cmdparam: Internal command tracker
1692  * @event_ctx: event context
1693  *
1694  * Issues event acknowledgment request to the firmware if there
1695  * is a free command to send the event ack else it to a pend
1696  * list so that it will be processed on a completion of a prior
1697  * event acknowledgment .
1698  *
1699  * Return: Nothing
1700  */
1701 static void mpi3mr_send_event_ack(struct mpi3mr_ioc *mrioc, u8 event,
1702         struct mpi3mr_drv_cmd *cmdparam, u32 event_ctx)
1703 {
1704         struct mpi3_event_ack_request evtack_req;
1705         int retval = 0;
1706         u8 retrycount = 5;
1707         u16 cmd_idx = MPI3MR_NUM_EVTACKCMD;
1708         struct mpi3mr_drv_cmd *drv_cmd = cmdparam;
1709         struct delayed_evt_ack_node *delayed_evtack = NULL;
1710
1711         if (drv_cmd) {
1712                 dprint_event_th(mrioc,
1713                     "sending delayed event ack in the top half for event(0x%02x), event_ctx(0x%08x)\n",
1714                     event, event_ctx);
1715                 goto issue_cmd;
1716         }
1717         dprint_event_th(mrioc,
1718             "sending event ack in the top half for event(0x%02x), event_ctx(0x%08x)\n",
1719             event, event_ctx);
1720         do {
1721                 cmd_idx = find_first_zero_bit(mrioc->evtack_cmds_bitmap,
1722                     MPI3MR_NUM_EVTACKCMD);
1723                 if (cmd_idx < MPI3MR_NUM_EVTACKCMD) {
1724                         if (!test_and_set_bit(cmd_idx,
1725                             mrioc->evtack_cmds_bitmap))
1726                                 break;
1727                         cmd_idx = MPI3MR_NUM_EVTACKCMD;
1728                 }
1729         } while (retrycount--);
1730
1731         if (cmd_idx >= MPI3MR_NUM_EVTACKCMD) {
1732                 delayed_evtack = kzalloc(sizeof(*delayed_evtack),
1733                     GFP_ATOMIC);
1734                 if (!delayed_evtack)
1735                         return;
1736                 INIT_LIST_HEAD(&delayed_evtack->list);
1737                 delayed_evtack->event = event;
1738                 delayed_evtack->event_ctx = event_ctx;
1739                 list_add_tail(&delayed_evtack->list,
1740                     &mrioc->delayed_evtack_cmds_list);
1741                 dprint_event_th(mrioc,
1742                     "event ack in the top half for event(0x%02x), event_ctx(0x%08x) is postponed\n",
1743                     event, event_ctx);
1744                 return;
1745         }
1746         drv_cmd = &mrioc->evtack_cmds[cmd_idx];
1747
1748 issue_cmd:
1749         cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_EVTACKCMD_MIN;
1750
1751         memset(&evtack_req, 0, sizeof(evtack_req));
1752         if (drv_cmd->state & MPI3MR_CMD_PENDING) {
1753                 dprint_event_th(mrioc,
1754                     "sending event ack failed due to command in use\n");
1755                 goto out;
1756         }
1757         drv_cmd->state = MPI3MR_CMD_PENDING;
1758         drv_cmd->is_waiting = 0;
1759         drv_cmd->callback = mpi3mr_complete_evt_ack;
1760         evtack_req.host_tag = cpu_to_le16(drv_cmd->host_tag);
1761         evtack_req.function = MPI3_FUNCTION_EVENT_ACK;
1762         evtack_req.event = event;
1763         evtack_req.event_context = cpu_to_le32(event_ctx);
1764         retval = mpi3mr_admin_request_post(mrioc, &evtack_req,
1765             sizeof(evtack_req), 1);
1766         if (retval) {
1767                 dprint_event_th(mrioc,
1768                     "posting event ack request is failed\n");
1769                 goto out_failed;
1770         }
1771
1772         dprint_event_th(mrioc,
1773             "event ack in the top half for event(0x%02x), event_ctx(0x%08x) is posted\n",
1774             event, event_ctx);
1775 out:
1776         return;
1777 out_failed:
1778         drv_cmd->state = MPI3MR_CMD_NOTUSED;
1779         drv_cmd->callback = NULL;
1780         clear_bit(cmd_idx, mrioc->evtack_cmds_bitmap);
1781 }
1782
1783 /**
1784  * mpi3mr_pcietopochg_evt_th - PCIETopologyChange evt tophalf
1785  * @mrioc: Adapter instance reference
1786  * @event_reply: event data
1787  *
1788  * Checks for the reason code and based on that either block I/O
1789  * to device, or unblock I/O to the device, or start the device
1790  * removal handshake with reason as remove with the firmware for
1791  * PCIe devices.
1792  *
1793  * Return: Nothing
1794  */
1795 static void mpi3mr_pcietopochg_evt_th(struct mpi3mr_ioc *mrioc,
1796         struct mpi3_event_notification_reply *event_reply)
1797 {
1798         struct mpi3_event_data_pcie_topology_change_list *topo_evt =
1799             (struct mpi3_event_data_pcie_topology_change_list *)event_reply->event_data;
1800         int i;
1801         u16 handle;
1802         u8 reason_code;
1803         struct mpi3mr_tgt_dev *tgtdev = NULL;
1804         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL;
1805
1806         for (i = 0; i < topo_evt->num_entries; i++) {
1807                 handle = le16_to_cpu(topo_evt->port_entry[i].attached_dev_handle);
1808                 if (!handle)
1809                         continue;
1810                 reason_code = topo_evt->port_entry[i].port_status;
1811                 scsi_tgt_priv_data =  NULL;
1812                 tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, handle);
1813                 if (tgtdev && tgtdev->starget && tgtdev->starget->hostdata)
1814                         scsi_tgt_priv_data = (struct mpi3mr_stgt_priv_data *)
1815                             tgtdev->starget->hostdata;
1816                 switch (reason_code) {
1817                 case MPI3_EVENT_PCIE_TOPO_PS_NOT_RESPONDING:
1818                         if (scsi_tgt_priv_data) {
1819                                 scsi_tgt_priv_data->dev_removed = 1;
1820                                 scsi_tgt_priv_data->dev_removedelay = 0;
1821                                 atomic_set(&scsi_tgt_priv_data->block_io, 0);
1822                         }
1823                         mpi3mr_dev_rmhs_send_tm(mrioc, handle, NULL,
1824                             MPI3_CTRL_OP_REMOVE_DEVICE);
1825                         break;
1826                 case MPI3_EVENT_PCIE_TOPO_PS_DELAY_NOT_RESPONDING:
1827                         if (scsi_tgt_priv_data) {
1828                                 scsi_tgt_priv_data->dev_removedelay = 1;
1829                                 atomic_inc(&scsi_tgt_priv_data->block_io);
1830                         }
1831                         break;
1832                 case MPI3_EVENT_PCIE_TOPO_PS_RESPONDING:
1833                         if (scsi_tgt_priv_data &&
1834                             scsi_tgt_priv_data->dev_removedelay) {
1835                                 scsi_tgt_priv_data->dev_removedelay = 0;
1836                                 atomic_dec_if_positive
1837                                     (&scsi_tgt_priv_data->block_io);
1838                         }
1839                         break;
1840                 case MPI3_EVENT_PCIE_TOPO_PS_PORT_CHANGED:
1841                 default:
1842                         break;
1843                 }
1844                 if (tgtdev)
1845                         mpi3mr_tgtdev_put(tgtdev);
1846         }
1847 }
1848
1849 /**
1850  * mpi3mr_sastopochg_evt_th - SASTopologyChange evt tophalf
1851  * @mrioc: Adapter instance reference
1852  * @event_reply: event data
1853  *
1854  * Checks for the reason code and based on that either block I/O
1855  * to device, or unblock I/O to the device, or start the device
1856  * removal handshake with reason as remove with the firmware for
1857  * SAS/SATA devices.
1858  *
1859  * Return: Nothing
1860  */
1861 static void mpi3mr_sastopochg_evt_th(struct mpi3mr_ioc *mrioc,
1862         struct mpi3_event_notification_reply *event_reply)
1863 {
1864         struct mpi3_event_data_sas_topology_change_list *topo_evt =
1865             (struct mpi3_event_data_sas_topology_change_list *)event_reply->event_data;
1866         int i;
1867         u16 handle;
1868         u8 reason_code;
1869         struct mpi3mr_tgt_dev *tgtdev = NULL;
1870         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL;
1871
1872         for (i = 0; i < topo_evt->num_entries; i++) {
1873                 handle = le16_to_cpu(topo_evt->phy_entry[i].attached_dev_handle);
1874                 if (!handle)
1875                         continue;
1876                 reason_code = topo_evt->phy_entry[i].status &
1877                     MPI3_EVENT_SAS_TOPO_PHY_RC_MASK;
1878                 scsi_tgt_priv_data =  NULL;
1879                 tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, handle);
1880                 if (tgtdev && tgtdev->starget && tgtdev->starget->hostdata)
1881                         scsi_tgt_priv_data = (struct mpi3mr_stgt_priv_data *)
1882                             tgtdev->starget->hostdata;
1883                 switch (reason_code) {
1884                 case MPI3_EVENT_SAS_TOPO_PHY_RC_TARG_NOT_RESPONDING:
1885                         if (scsi_tgt_priv_data) {
1886                                 scsi_tgt_priv_data->dev_removed = 1;
1887                                 scsi_tgt_priv_data->dev_removedelay = 0;
1888                                 atomic_set(&scsi_tgt_priv_data->block_io, 0);
1889                         }
1890                         mpi3mr_dev_rmhs_send_tm(mrioc, handle, NULL,
1891                             MPI3_CTRL_OP_REMOVE_DEVICE);
1892                         break;
1893                 case MPI3_EVENT_SAS_TOPO_PHY_RC_DELAY_NOT_RESPONDING:
1894                         if (scsi_tgt_priv_data) {
1895                                 scsi_tgt_priv_data->dev_removedelay = 1;
1896                                 atomic_inc(&scsi_tgt_priv_data->block_io);
1897                         }
1898                         break;
1899                 case MPI3_EVENT_SAS_TOPO_PHY_RC_RESPONDING:
1900                         if (scsi_tgt_priv_data &&
1901                             scsi_tgt_priv_data->dev_removedelay) {
1902                                 scsi_tgt_priv_data->dev_removedelay = 0;
1903                                 atomic_dec_if_positive
1904                                     (&scsi_tgt_priv_data->block_io);
1905                         }
1906                         break;
1907                 case MPI3_EVENT_SAS_TOPO_PHY_RC_PHY_CHANGED:
1908                 default:
1909                         break;
1910                 }
1911                 if (tgtdev)
1912                         mpi3mr_tgtdev_put(tgtdev);
1913         }
1914 }
1915
1916 /**
1917  * mpi3mr_devstatuschg_evt_th - DeviceStatusChange evt tophalf
1918  * @mrioc: Adapter instance reference
1919  * @event_reply: event data
1920  *
1921  * Checks for the reason code and based on that either block I/O
1922  * to device, or unblock I/O to the device, or start the device
1923  * removal handshake with reason as remove/hide acknowledgment
1924  * with the firmware.
1925  *
1926  * Return: Nothing
1927  */
1928 static void mpi3mr_devstatuschg_evt_th(struct mpi3mr_ioc *mrioc,
1929         struct mpi3_event_notification_reply *event_reply)
1930 {
1931         u16 dev_handle = 0;
1932         u8 ublock = 0, block = 0, hide = 0, delete = 0, remove = 0;
1933         struct mpi3mr_tgt_dev *tgtdev = NULL;
1934         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL;
1935         struct mpi3_event_data_device_status_change *evtdata =
1936             (struct mpi3_event_data_device_status_change *)event_reply->event_data;
1937
1938         if (mrioc->stop_drv_processing)
1939                 goto out;
1940
1941         dev_handle = le16_to_cpu(evtdata->dev_handle);
1942
1943         switch (evtdata->reason_code) {
1944         case MPI3_EVENT_DEV_STAT_RC_INT_DEVICE_RESET_STRT:
1945         case MPI3_EVENT_DEV_STAT_RC_INT_IT_NEXUS_RESET_STRT:
1946                 block = 1;
1947                 break;
1948         case MPI3_EVENT_DEV_STAT_RC_HIDDEN:
1949                 delete = 1;
1950                 hide = 1;
1951                 break;
1952         case MPI3_EVENT_DEV_STAT_RC_VD_NOT_RESPONDING:
1953                 delete = 1;
1954                 remove = 1;
1955                 break;
1956         case MPI3_EVENT_DEV_STAT_RC_INT_DEVICE_RESET_CMP:
1957         case MPI3_EVENT_DEV_STAT_RC_INT_IT_NEXUS_RESET_CMP:
1958                 ublock = 1;
1959                 break;
1960         default:
1961                 break;
1962         }
1963
1964         tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, dev_handle);
1965         if (!tgtdev)
1966                 goto out;
1967         if (hide)
1968                 tgtdev->is_hidden = hide;
1969         if (tgtdev->starget && tgtdev->starget->hostdata) {
1970                 scsi_tgt_priv_data = (struct mpi3mr_stgt_priv_data *)
1971                     tgtdev->starget->hostdata;
1972                 if (block)
1973                         atomic_inc(&scsi_tgt_priv_data->block_io);
1974                 if (delete)
1975                         scsi_tgt_priv_data->dev_removed = 1;
1976                 if (ublock)
1977                         atomic_dec_if_positive(&scsi_tgt_priv_data->block_io);
1978         }
1979         if (remove)
1980                 mpi3mr_dev_rmhs_send_tm(mrioc, dev_handle, NULL,
1981                     MPI3_CTRL_OP_REMOVE_DEVICE);
1982         if (hide)
1983                 mpi3mr_dev_rmhs_send_tm(mrioc, dev_handle, NULL,
1984                     MPI3_CTRL_OP_HIDDEN_ACK);
1985
1986 out:
1987         if (tgtdev)
1988                 mpi3mr_tgtdev_put(tgtdev);
1989 }
1990
1991 /**
1992  * mpi3mr_preparereset_evt_th - Prepare for reset event tophalf
1993  * @mrioc: Adapter instance reference
1994  * @event_reply: event data
1995  *
1996  * Blocks and unblocks host level I/O based on the reason code
1997  *
1998  * Return: Nothing
1999  */
2000 static void mpi3mr_preparereset_evt_th(struct mpi3mr_ioc *mrioc,
2001         struct mpi3_event_notification_reply *event_reply)
2002 {
2003         struct mpi3_event_data_prepare_for_reset *evtdata =
2004             (struct mpi3_event_data_prepare_for_reset *)event_reply->event_data;
2005
2006         if (evtdata->reason_code == MPI3_EVENT_PREPARE_RESET_RC_START) {
2007                 dprint_event_th(mrioc,
2008                     "prepare for reset event top half with rc=start\n");
2009                 if (mrioc->prepare_for_reset)
2010                         return;
2011                 mrioc->prepare_for_reset = 1;
2012                 mrioc->prepare_for_reset_timeout_counter = 0;
2013         } else if (evtdata->reason_code == MPI3_EVENT_PREPARE_RESET_RC_ABORT) {
2014                 dprint_event_th(mrioc,
2015                     "prepare for reset top half with rc=abort\n");
2016                 mrioc->prepare_for_reset = 0;
2017                 mrioc->prepare_for_reset_timeout_counter = 0;
2018         }
2019         if ((event_reply->msg_flags & MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_MASK)
2020             == MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_REQUIRED)
2021                 mpi3mr_send_event_ack(mrioc, event_reply->event, NULL,
2022                     le32_to_cpu(event_reply->event_context));
2023 }
2024
2025 /**
2026  * mpi3mr_energypackchg_evt_th - Energy pack change evt tophalf
2027  * @mrioc: Adapter instance reference
2028  * @event_reply: event data
2029  *
2030  * Identifies the new shutdown timeout value and update.
2031  *
2032  * Return: Nothing
2033  */
2034 static void mpi3mr_energypackchg_evt_th(struct mpi3mr_ioc *mrioc,
2035         struct mpi3_event_notification_reply *event_reply)
2036 {
2037         struct mpi3_event_data_energy_pack_change *evtdata =
2038             (struct mpi3_event_data_energy_pack_change *)event_reply->event_data;
2039         u16 shutdown_timeout = le16_to_cpu(evtdata->shutdown_timeout);
2040
2041         if (shutdown_timeout <= 0) {
2042                 ioc_warn(mrioc,
2043                     "%s :Invalid Shutdown Timeout received = %d\n",
2044                     __func__, shutdown_timeout);
2045                 return;
2046         }
2047
2048         ioc_info(mrioc,
2049             "%s :Previous Shutdown Timeout Value = %d New Shutdown Timeout Value = %d\n",
2050             __func__, mrioc->facts.shutdown_timeout, shutdown_timeout);
2051         mrioc->facts.shutdown_timeout = shutdown_timeout;
2052 }
2053
2054 /**
2055  * mpi3mr_tempthreshold_evt_th - Temp threshold event tophalf
2056  * @mrioc: Adapter instance reference
2057  * @event_reply: event data
2058  *
2059  * Displays temperature threshold event details and fault code
2060  * if any is hit due to temperature exceeding threshold.
2061  *
2062  * Return: Nothing
2063  */
2064 static void mpi3mr_tempthreshold_evt_th(struct mpi3mr_ioc *mrioc,
2065         struct mpi3_event_notification_reply *event_reply)
2066 {
2067         struct mpi3_event_data_temp_threshold *evtdata =
2068             (struct mpi3_event_data_temp_threshold *)event_reply->event_data;
2069
2070         ioc_err(mrioc, "Temperature threshold levels %s%s%s exceeded for sensor: %d !!! Current temperature in Celsius: %d\n",
2071             (le16_to_cpu(evtdata->status) & 0x1) ? "Warning " : " ",
2072             (le16_to_cpu(evtdata->status) & 0x2) ? "Critical " : " ",
2073             (le16_to_cpu(evtdata->status) & 0x4) ? "Fatal " : " ", evtdata->sensor_num,
2074             le16_to_cpu(evtdata->current_temperature));
2075         mpi3mr_print_fault_info(mrioc);
2076 }
2077
2078 /**
2079  * mpi3mr_cablemgmt_evt_th - Cable management event tophalf
2080  * @mrioc: Adapter instance reference
2081  * @event_reply: event data
2082  *
2083  * Displays Cable manegemt event details.
2084  *
2085  * Return: Nothing
2086  */
2087 static void mpi3mr_cablemgmt_evt_th(struct mpi3mr_ioc *mrioc,
2088         struct mpi3_event_notification_reply *event_reply)
2089 {
2090         struct mpi3_event_data_cable_management *evtdata =
2091             (struct mpi3_event_data_cable_management *)event_reply->event_data;
2092
2093         switch (evtdata->status) {
2094         case MPI3_EVENT_CABLE_MGMT_STATUS_INSUFFICIENT_POWER:
2095         {
2096                 ioc_info(mrioc, "An active cable with receptacle_id %d cannot be powered.\n"
2097                     "Devices connected to this cable are not detected.\n"
2098                     "This cable requires %d mW of power.\n",
2099                     evtdata->receptacle_id,
2100                     le32_to_cpu(evtdata->active_cable_power_requirement));
2101                 break;
2102         }
2103         case MPI3_EVENT_CABLE_MGMT_STATUS_DEGRADED:
2104         {
2105                 ioc_info(mrioc, "A cable with receptacle_id %d is not running at optimal speed\n",
2106                     evtdata->receptacle_id);
2107                 break;
2108         }
2109         default:
2110                 break;
2111         }
2112 }
2113
2114 /**
2115  * mpi3mr_os_handle_events - Firmware event handler
2116  * @mrioc: Adapter instance reference
2117  * @event_reply: event data
2118  *
2119  * Identify whteher the event has to handled and acknowledged
2120  * and either process the event in the tophalf and/or schedule a
2121  * bottom half through mpi3mr_fwevt_worker.
2122  *
2123  * Return: Nothing
2124  */
2125 void mpi3mr_os_handle_events(struct mpi3mr_ioc *mrioc,
2126         struct mpi3_event_notification_reply *event_reply)
2127 {
2128         u16 evt_type, sz;
2129         struct mpi3mr_fwevt *fwevt = NULL;
2130         bool ack_req = 0, process_evt_bh = 0;
2131
2132         if (mrioc->stop_drv_processing)
2133                 return;
2134
2135         if ((event_reply->msg_flags & MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_MASK)
2136             == MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_REQUIRED)
2137                 ack_req = 1;
2138
2139         evt_type = event_reply->event;
2140
2141         switch (evt_type) {
2142         case MPI3_EVENT_DEVICE_ADDED:
2143         {
2144                 struct mpi3_device_page0 *dev_pg0 =
2145                     (struct mpi3_device_page0 *)event_reply->event_data;
2146                 if (mpi3mr_create_tgtdev(mrioc, dev_pg0))
2147                         ioc_err(mrioc,
2148                             "%s :Failed to add device in the device add event\n",
2149                             __func__);
2150                 else
2151                         process_evt_bh = 1;
2152                 break;
2153         }
2154         case MPI3_EVENT_DEVICE_STATUS_CHANGE:
2155         {
2156                 process_evt_bh = 1;
2157                 mpi3mr_devstatuschg_evt_th(mrioc, event_reply);
2158                 break;
2159         }
2160         case MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
2161         {
2162                 process_evt_bh = 1;
2163                 mpi3mr_sastopochg_evt_th(mrioc, event_reply);
2164                 break;
2165         }
2166         case MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
2167         {
2168                 process_evt_bh = 1;
2169                 mpi3mr_pcietopochg_evt_th(mrioc, event_reply);
2170                 break;
2171         }
2172         case MPI3_EVENT_PREPARE_FOR_RESET:
2173         {
2174                 mpi3mr_preparereset_evt_th(mrioc, event_reply);
2175                 ack_req = 0;
2176                 break;
2177         }
2178         case MPI3_EVENT_DEVICE_INFO_CHANGED:
2179         {
2180                 process_evt_bh = 1;
2181                 break;
2182         }
2183         case MPI3_EVENT_ENERGY_PACK_CHANGE:
2184         {
2185                 mpi3mr_energypackchg_evt_th(mrioc, event_reply);
2186                 break;
2187         }
2188         case MPI3_EVENT_TEMP_THRESHOLD:
2189         {
2190                 mpi3mr_tempthreshold_evt_th(mrioc, event_reply);
2191                 break;
2192         }
2193         case MPI3_EVENT_CABLE_MGMT:
2194         {
2195                 mpi3mr_cablemgmt_evt_th(mrioc, event_reply);
2196                 break;
2197         }
2198         case MPI3_EVENT_ENCL_DEVICE_STATUS_CHANGE:
2199         case MPI3_EVENT_SAS_DISCOVERY:
2200         case MPI3_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
2201         case MPI3_EVENT_SAS_BROADCAST_PRIMITIVE:
2202         case MPI3_EVENT_PCIE_ENUMERATION:
2203                 break;
2204         default:
2205                 ioc_info(mrioc, "%s :event 0x%02x is not handled\n",
2206                     __func__, evt_type);
2207                 break;
2208         }
2209         if (process_evt_bh || ack_req) {
2210                 sz = event_reply->event_data_length * 4;
2211                 fwevt = mpi3mr_alloc_fwevt(sz);
2212                 if (!fwevt) {
2213                         ioc_info(mrioc, "%s :failure at %s:%d/%s()!\n",
2214                             __func__, __FILE__, __LINE__, __func__);
2215                         return;
2216                 }
2217
2218                 memcpy(fwevt->event_data, event_reply->event_data, sz);
2219                 fwevt->mrioc = mrioc;
2220                 fwevt->event_id = evt_type;
2221                 fwevt->send_ack = ack_req;
2222                 fwevt->process_evt = process_evt_bh;
2223                 fwevt->evt_ctx = le32_to_cpu(event_reply->event_context);
2224                 mpi3mr_fwevt_add_to_list(mrioc, fwevt);
2225         }
2226 }
2227
2228 /**
2229  * mpi3mr_setup_eedp - Setup EEDP information in MPI3 SCSI IO
2230  * @mrioc: Adapter instance reference
2231  * @scmd: SCSI command reference
2232  * @scsiio_req: MPI3 SCSI IO request
2233  *
2234  * Identifies the protection information flags from the SCSI
2235  * command and set appropriate flags in the MPI3 SCSI IO
2236  * request.
2237  *
2238  * Return: Nothing
2239  */
2240 static void mpi3mr_setup_eedp(struct mpi3mr_ioc *mrioc,
2241         struct scsi_cmnd *scmd, struct mpi3_scsi_io_request *scsiio_req)
2242 {
2243         u16 eedp_flags = 0;
2244         unsigned char prot_op = scsi_get_prot_op(scmd);
2245
2246         switch (prot_op) {
2247         case SCSI_PROT_NORMAL:
2248                 return;
2249         case SCSI_PROT_READ_STRIP:
2250                 eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_CHECK_REMOVE;
2251                 break;
2252         case SCSI_PROT_WRITE_INSERT:
2253                 eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_INSERT;
2254                 break;
2255         case SCSI_PROT_READ_INSERT:
2256                 eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_INSERT;
2257                 scsiio_req->msg_flags |= MPI3_SCSIIO_MSGFLAGS_METASGL_VALID;
2258                 break;
2259         case SCSI_PROT_WRITE_STRIP:
2260                 eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_CHECK_REMOVE;
2261                 scsiio_req->msg_flags |= MPI3_SCSIIO_MSGFLAGS_METASGL_VALID;
2262                 break;
2263         case SCSI_PROT_READ_PASS:
2264                 eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_CHECK;
2265                 scsiio_req->msg_flags |= MPI3_SCSIIO_MSGFLAGS_METASGL_VALID;
2266                 break;
2267         case SCSI_PROT_WRITE_PASS:
2268                 if (scmd->prot_flags & SCSI_PROT_IP_CHECKSUM) {
2269                         eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_CHECK_REGEN;
2270                         scsiio_req->sgl[0].eedp.application_tag_translation_mask =
2271                             0xffff;
2272                 } else
2273                         eedp_flags = MPI3_EEDPFLAGS_EEDP_OP_CHECK;
2274
2275                 scsiio_req->msg_flags |= MPI3_SCSIIO_MSGFLAGS_METASGL_VALID;
2276                 break;
2277         default:
2278                 return;
2279         }
2280
2281         if (scmd->prot_flags & SCSI_PROT_GUARD_CHECK)
2282                 eedp_flags |= MPI3_EEDPFLAGS_CHK_GUARD;
2283
2284         if (scmd->prot_flags & SCSI_PROT_IP_CHECKSUM)
2285                 eedp_flags |= MPI3_EEDPFLAGS_HOST_GUARD_IP_CHKSUM;
2286
2287         if (scmd->prot_flags & SCSI_PROT_REF_CHECK) {
2288                 eedp_flags |= MPI3_EEDPFLAGS_CHK_REF_TAG |
2289                         MPI3_EEDPFLAGS_INCR_PRI_REF_TAG;
2290                 scsiio_req->cdb.eedp32.primary_reference_tag =
2291                         cpu_to_be32(scsi_prot_ref_tag(scmd));
2292         }
2293
2294         if (scmd->prot_flags & SCSI_PROT_REF_INCREMENT)
2295                 eedp_flags |= MPI3_EEDPFLAGS_INCR_PRI_REF_TAG;
2296
2297         eedp_flags |= MPI3_EEDPFLAGS_ESC_MODE_APPTAG_DISABLE;
2298
2299         switch (scsi_prot_interval(scmd)) {
2300         case 512:
2301                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_512;
2302                 break;
2303         case 520:
2304                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_520;
2305                 break;
2306         case 4080:
2307                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_4080;
2308                 break;
2309         case 4088:
2310                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_4088;
2311                 break;
2312         case 4096:
2313                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_4096;
2314                 break;
2315         case 4104:
2316                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_4104;
2317                 break;
2318         case 4160:
2319                 scsiio_req->sgl[0].eedp.user_data_size = MPI3_EEDP_UDS_4160;
2320                 break;
2321         default:
2322                 break;
2323         }
2324
2325         scsiio_req->sgl[0].eedp.eedp_flags = cpu_to_le16(eedp_flags);
2326         scsiio_req->sgl[0].eedp.flags = MPI3_SGE_FLAGS_ELEMENT_TYPE_EXTENDED;
2327 }
2328
2329 /**
2330  * mpi3mr_build_sense_buffer - Map sense information
2331  * @desc: Sense type
2332  * @buf: Sense buffer to populate
2333  * @key: Sense key
2334  * @asc: Additional sense code
2335  * @ascq: Additional sense code qualifier
2336  *
2337  * Maps the given sense information into either descriptor or
2338  * fixed format sense data.
2339  *
2340  * Return: Nothing
2341  */
2342 static inline void mpi3mr_build_sense_buffer(int desc, u8 *buf, u8 key,
2343         u8 asc, u8 ascq)
2344 {
2345         if (desc) {
2346                 buf[0] = 0x72;  /* descriptor, current */
2347                 buf[1] = key;
2348                 buf[2] = asc;
2349                 buf[3] = ascq;
2350                 buf[7] = 0;
2351         } else {
2352                 buf[0] = 0x70;  /* fixed, current */
2353                 buf[2] = key;
2354                 buf[7] = 0xa;
2355                 buf[12] = asc;
2356                 buf[13] = ascq;
2357         }
2358 }
2359
2360 /**
2361  * mpi3mr_map_eedp_error - Map EEDP errors from IOC status
2362  * @scmd: SCSI command reference
2363  * @ioc_status: status of MPI3 request
2364  *
2365  * Maps the EEDP error status of the SCSI IO request to sense
2366  * data.
2367  *
2368  * Return: Nothing
2369  */
2370 static void mpi3mr_map_eedp_error(struct scsi_cmnd *scmd,
2371         u16 ioc_status)
2372 {
2373         u8 ascq = 0;
2374
2375         switch (ioc_status) {
2376         case MPI3_IOCSTATUS_EEDP_GUARD_ERROR:
2377                 ascq = 0x01;
2378                 break;
2379         case MPI3_IOCSTATUS_EEDP_APP_TAG_ERROR:
2380                 ascq = 0x02;
2381                 break;
2382         case MPI3_IOCSTATUS_EEDP_REF_TAG_ERROR:
2383                 ascq = 0x03;
2384                 break;
2385         default:
2386                 ascq = 0x00;
2387                 break;
2388         }
2389
2390         mpi3mr_build_sense_buffer(0, scmd->sense_buffer, ILLEGAL_REQUEST,
2391             0x10, ascq);
2392         scmd->result = (DID_ABORT << 16) | SAM_STAT_CHECK_CONDITION;
2393 }
2394
2395 /**
2396  * mpi3mr_process_op_reply_desc - reply descriptor handler
2397  * @mrioc: Adapter instance reference
2398  * @reply_desc: Operational reply descriptor
2399  * @reply_dma: place holder for reply DMA address
2400  * @qidx: Operational queue index
2401  *
2402  * Process the operational reply descriptor and identifies the
2403  * descriptor type. Based on the descriptor map the MPI3 request
2404  * status to a SCSI command status and calls scsi_done call
2405  * back.
2406  *
2407  * Return: Nothing
2408  */
2409 void mpi3mr_process_op_reply_desc(struct mpi3mr_ioc *mrioc,
2410         struct mpi3_default_reply_descriptor *reply_desc, u64 *reply_dma, u16 qidx)
2411 {
2412         u16 reply_desc_type, host_tag = 0;
2413         u16 ioc_status = MPI3_IOCSTATUS_SUCCESS;
2414         u32 ioc_loginfo = 0;
2415         struct mpi3_status_reply_descriptor *status_desc = NULL;
2416         struct mpi3_address_reply_descriptor *addr_desc = NULL;
2417         struct mpi3_success_reply_descriptor *success_desc = NULL;
2418         struct mpi3_scsi_io_reply *scsi_reply = NULL;
2419         struct scsi_cmnd *scmd = NULL;
2420         struct scmd_priv *priv = NULL;
2421         u8 *sense_buf = NULL;
2422         u8 scsi_state = 0, scsi_status = 0, sense_state = 0;
2423         u32 xfer_count = 0, sense_count = 0, resp_data = 0;
2424         u16 dev_handle = 0xFFFF;
2425         struct scsi_sense_hdr sshdr;
2426
2427         *reply_dma = 0;
2428         reply_desc_type = le16_to_cpu(reply_desc->reply_flags) &
2429             MPI3_REPLY_DESCRIPT_FLAGS_TYPE_MASK;
2430         switch (reply_desc_type) {
2431         case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_STATUS:
2432                 status_desc = (struct mpi3_status_reply_descriptor *)reply_desc;
2433                 host_tag = le16_to_cpu(status_desc->host_tag);
2434                 ioc_status = le16_to_cpu(status_desc->ioc_status);
2435                 if (ioc_status &
2436                     MPI3_REPLY_DESCRIPT_STATUS_IOCSTATUS_LOGINFOAVAIL)
2437                         ioc_loginfo = le32_to_cpu(status_desc->ioc_log_info);
2438                 ioc_status &= MPI3_REPLY_DESCRIPT_STATUS_IOCSTATUS_STATUS_MASK;
2439                 break;
2440         case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_ADDRESS_REPLY:
2441                 addr_desc = (struct mpi3_address_reply_descriptor *)reply_desc;
2442                 *reply_dma = le64_to_cpu(addr_desc->reply_frame_address);
2443                 scsi_reply = mpi3mr_get_reply_virt_addr(mrioc,
2444                     *reply_dma);
2445                 if (!scsi_reply) {
2446                         panic("%s: scsi_reply is NULL, this shouldn't happen\n",
2447                             mrioc->name);
2448                         goto out;
2449                 }
2450                 host_tag = le16_to_cpu(scsi_reply->host_tag);
2451                 ioc_status = le16_to_cpu(scsi_reply->ioc_status);
2452                 scsi_status = scsi_reply->scsi_status;
2453                 scsi_state = scsi_reply->scsi_state;
2454                 dev_handle = le16_to_cpu(scsi_reply->dev_handle);
2455                 sense_state = (scsi_state & MPI3_SCSI_STATE_SENSE_MASK);
2456                 xfer_count = le32_to_cpu(scsi_reply->transfer_count);
2457                 sense_count = le32_to_cpu(scsi_reply->sense_count);
2458                 resp_data = le32_to_cpu(scsi_reply->response_data);
2459                 sense_buf = mpi3mr_get_sensebuf_virt_addr(mrioc,
2460                     le64_to_cpu(scsi_reply->sense_data_buffer_address));
2461                 if (ioc_status &
2462                     MPI3_REPLY_DESCRIPT_STATUS_IOCSTATUS_LOGINFOAVAIL)
2463                         ioc_loginfo = le32_to_cpu(scsi_reply->ioc_log_info);
2464                 ioc_status &= MPI3_REPLY_DESCRIPT_STATUS_IOCSTATUS_STATUS_MASK;
2465                 if (sense_state == MPI3_SCSI_STATE_SENSE_BUFF_Q_EMPTY)
2466                         panic("%s: Ran out of sense buffers\n", mrioc->name);
2467                 break;
2468         case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_SUCCESS:
2469                 success_desc = (struct mpi3_success_reply_descriptor *)reply_desc;
2470                 host_tag = le16_to_cpu(success_desc->host_tag);
2471                 break;
2472         default:
2473                 break;
2474         }
2475         scmd = mpi3mr_scmd_from_host_tag(mrioc, host_tag, qidx);
2476         if (!scmd) {
2477                 panic("%s: Cannot Identify scmd for host_tag 0x%x\n",
2478                     mrioc->name, host_tag);
2479                 goto out;
2480         }
2481         priv = scsi_cmd_priv(scmd);
2482         if (success_desc) {
2483                 scmd->result = DID_OK << 16;
2484                 goto out_success;
2485         }
2486         if (ioc_status == MPI3_IOCSTATUS_SCSI_DATA_UNDERRUN &&
2487             xfer_count == 0 && (scsi_status == MPI3_SCSI_STATUS_BUSY ||
2488             scsi_status == MPI3_SCSI_STATUS_RESERVATION_CONFLICT ||
2489             scsi_status == MPI3_SCSI_STATUS_TASK_SET_FULL))
2490                 ioc_status = MPI3_IOCSTATUS_SUCCESS;
2491
2492         if ((sense_state == MPI3_SCSI_STATE_SENSE_VALID) && sense_count &&
2493             sense_buf) {
2494                 u32 sz = min_t(u32, SCSI_SENSE_BUFFERSIZE, sense_count);
2495
2496                 memcpy(scmd->sense_buffer, sense_buf, sz);
2497         }
2498
2499         switch (ioc_status) {
2500         case MPI3_IOCSTATUS_BUSY:
2501         case MPI3_IOCSTATUS_INSUFFICIENT_RESOURCES:
2502                 scmd->result = SAM_STAT_BUSY;
2503                 break;
2504         case MPI3_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
2505                 scmd->result = DID_NO_CONNECT << 16;
2506                 break;
2507         case MPI3_IOCSTATUS_SCSI_IOC_TERMINATED:
2508                 scmd->result = DID_SOFT_ERROR << 16;
2509                 break;
2510         case MPI3_IOCSTATUS_SCSI_TASK_TERMINATED:
2511         case MPI3_IOCSTATUS_SCSI_EXT_TERMINATED:
2512                 scmd->result = DID_RESET << 16;
2513                 break;
2514         case MPI3_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
2515                 if ((xfer_count == 0) || (scmd->underflow > xfer_count))
2516                         scmd->result = DID_SOFT_ERROR << 16;
2517                 else
2518                         scmd->result = (DID_OK << 16) | scsi_status;
2519                 break;
2520         case MPI3_IOCSTATUS_SCSI_DATA_UNDERRUN:
2521                 scmd->result = (DID_OK << 16) | scsi_status;
2522                 if (sense_state == MPI3_SCSI_STATE_SENSE_VALID)
2523                         break;
2524                 if (xfer_count < scmd->underflow) {
2525                         if (scsi_status == SAM_STAT_BUSY)
2526                                 scmd->result = SAM_STAT_BUSY;
2527                         else
2528                                 scmd->result = DID_SOFT_ERROR << 16;
2529                 } else if ((scsi_state & (MPI3_SCSI_STATE_NO_SCSI_STATUS)) ||
2530                     (sense_state != MPI3_SCSI_STATE_SENSE_NOT_AVAILABLE))
2531                         scmd->result = DID_SOFT_ERROR << 16;
2532                 else if (scsi_state & MPI3_SCSI_STATE_TERMINATED)
2533                         scmd->result = DID_RESET << 16;
2534                 break;
2535         case MPI3_IOCSTATUS_SCSI_DATA_OVERRUN:
2536                 scsi_set_resid(scmd, 0);
2537                 fallthrough;
2538         case MPI3_IOCSTATUS_SCSI_RECOVERED_ERROR:
2539         case MPI3_IOCSTATUS_SUCCESS:
2540                 scmd->result = (DID_OK << 16) | scsi_status;
2541                 if ((scsi_state & (MPI3_SCSI_STATE_NO_SCSI_STATUS)) ||
2542                     (sense_state == MPI3_SCSI_STATE_SENSE_FAILED) ||
2543                         (sense_state == MPI3_SCSI_STATE_SENSE_BUFF_Q_EMPTY))
2544                         scmd->result = DID_SOFT_ERROR << 16;
2545                 else if (scsi_state & MPI3_SCSI_STATE_TERMINATED)
2546                         scmd->result = DID_RESET << 16;
2547                 break;
2548         case MPI3_IOCSTATUS_EEDP_GUARD_ERROR:
2549         case MPI3_IOCSTATUS_EEDP_REF_TAG_ERROR:
2550         case MPI3_IOCSTATUS_EEDP_APP_TAG_ERROR:
2551                 mpi3mr_map_eedp_error(scmd, ioc_status);
2552                 break;
2553         case MPI3_IOCSTATUS_SCSI_PROTOCOL_ERROR:
2554         case MPI3_IOCSTATUS_INVALID_FUNCTION:
2555         case MPI3_IOCSTATUS_INVALID_SGL:
2556         case MPI3_IOCSTATUS_INTERNAL_ERROR:
2557         case MPI3_IOCSTATUS_INVALID_FIELD:
2558         case MPI3_IOCSTATUS_INVALID_STATE:
2559         case MPI3_IOCSTATUS_SCSI_IO_DATA_ERROR:
2560         case MPI3_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
2561         case MPI3_IOCSTATUS_INSUFFICIENT_POWER:
2562         default:
2563                 scmd->result = DID_SOFT_ERROR << 16;
2564                 break;
2565         }
2566
2567         if (scmd->result != (DID_OK << 16) && (scmd->cmnd[0] != ATA_12) &&
2568             (scmd->cmnd[0] != ATA_16)) {
2569                 ioc_info(mrioc, "%s :scmd->result 0x%x\n", __func__,
2570                     scmd->result);
2571                 scsi_print_command(scmd);
2572                 ioc_info(mrioc,
2573                     "%s :Command issued to handle 0x%02x returned with error 0x%04x loginfo 0x%08x, qid %d\n",
2574                     __func__, dev_handle, ioc_status, ioc_loginfo,
2575                     priv->req_q_idx + 1);
2576                 ioc_info(mrioc,
2577                     " host_tag %d scsi_state 0x%02x scsi_status 0x%02x, xfer_cnt %d resp_data 0x%x\n",
2578                     host_tag, scsi_state, scsi_status, xfer_count, resp_data);
2579                 if (sense_buf) {
2580                         scsi_normalize_sense(sense_buf, sense_count, &sshdr);
2581                         ioc_info(mrioc,
2582                             "%s :sense_count 0x%x, sense_key 0x%x ASC 0x%x, ASCQ 0x%x\n",
2583                             __func__, sense_count, sshdr.sense_key,
2584                             sshdr.asc, sshdr.ascq);
2585                 }
2586         }
2587 out_success:
2588         if (priv->meta_sg_valid) {
2589                 dma_unmap_sg(&mrioc->pdev->dev, scsi_prot_sglist(scmd),
2590                     scsi_prot_sg_count(scmd), scmd->sc_data_direction);
2591         }
2592         mpi3mr_clear_scmd_priv(mrioc, scmd);
2593         scsi_dma_unmap(scmd);
2594         scsi_done(scmd);
2595 out:
2596         if (sense_buf)
2597                 mpi3mr_repost_sense_buf(mrioc,
2598                     le64_to_cpu(scsi_reply->sense_data_buffer_address));
2599 }
2600
2601 /**
2602  * mpi3mr_get_chain_idx - get free chain buffer index
2603  * @mrioc: Adapter instance reference
2604  *
2605  * Try to get a free chain buffer index from the free pool.
2606  *
2607  * Return: -1 on failure or the free chain buffer index
2608  */
2609 static int mpi3mr_get_chain_idx(struct mpi3mr_ioc *mrioc)
2610 {
2611         u8 retry_count = 5;
2612         int cmd_idx = -1;
2613
2614         do {
2615                 spin_lock(&mrioc->chain_buf_lock);
2616                 cmd_idx = find_first_zero_bit(mrioc->chain_bitmap,
2617                     mrioc->chain_buf_count);
2618                 if (cmd_idx < mrioc->chain_buf_count) {
2619                         set_bit(cmd_idx, mrioc->chain_bitmap);
2620                         spin_unlock(&mrioc->chain_buf_lock);
2621                         break;
2622                 }
2623                 spin_unlock(&mrioc->chain_buf_lock);
2624                 cmd_idx = -1;
2625         } while (retry_count--);
2626         return cmd_idx;
2627 }
2628
2629 /**
2630  * mpi3mr_prepare_sg_scmd - build scatter gather list
2631  * @mrioc: Adapter instance reference
2632  * @scmd: SCSI command reference
2633  * @scsiio_req: MPI3 SCSI IO request
2634  *
2635  * This function maps SCSI command's data and protection SGEs to
2636  * MPI request SGEs. If required additional 4K chain buffer is
2637  * used to send the SGEs.
2638  *
2639  * Return: 0 on success, -ENOMEM on dma_map_sg failure
2640  */
2641 static int mpi3mr_prepare_sg_scmd(struct mpi3mr_ioc *mrioc,
2642         struct scsi_cmnd *scmd, struct mpi3_scsi_io_request *scsiio_req)
2643 {
2644         dma_addr_t chain_dma;
2645         struct scatterlist *sg_scmd;
2646         void *sg_local, *chain;
2647         u32 chain_length;
2648         int sges_left, chain_idx;
2649         u32 sges_in_segment;
2650         u8 simple_sgl_flags;
2651         u8 simple_sgl_flags_last;
2652         u8 last_chain_sgl_flags;
2653         struct chain_element *chain_req;
2654         struct scmd_priv *priv = NULL;
2655         u32 meta_sg = le32_to_cpu(scsiio_req->flags) &
2656             MPI3_SCSIIO_FLAGS_DMAOPERATION_HOST_PI;
2657
2658         priv = scsi_cmd_priv(scmd);
2659
2660         simple_sgl_flags = MPI3_SGE_FLAGS_ELEMENT_TYPE_SIMPLE |
2661             MPI3_SGE_FLAGS_DLAS_SYSTEM;
2662         simple_sgl_flags_last = simple_sgl_flags |
2663             MPI3_SGE_FLAGS_END_OF_LIST;
2664         last_chain_sgl_flags = MPI3_SGE_FLAGS_ELEMENT_TYPE_LAST_CHAIN |
2665             MPI3_SGE_FLAGS_DLAS_SYSTEM;
2666
2667         if (meta_sg)
2668                 sg_local = &scsiio_req->sgl[MPI3_SCSIIO_METASGL_INDEX];
2669         else
2670                 sg_local = &scsiio_req->sgl;
2671
2672         if (!scsiio_req->data_length && !meta_sg) {
2673                 mpi3mr_build_zero_len_sge(sg_local);
2674                 return 0;
2675         }
2676
2677         if (meta_sg) {
2678                 sg_scmd = scsi_prot_sglist(scmd);
2679                 sges_left = dma_map_sg(&mrioc->pdev->dev,
2680                     scsi_prot_sglist(scmd),
2681                     scsi_prot_sg_count(scmd),
2682                     scmd->sc_data_direction);
2683                 priv->meta_sg_valid = 1; /* To unmap meta sg DMA */
2684         } else {
2685                 sg_scmd = scsi_sglist(scmd);
2686                 sges_left = scsi_dma_map(scmd);
2687         }
2688
2689         if (sges_left < 0) {
2690                 sdev_printk(KERN_ERR, scmd->device,
2691                     "scsi_dma_map failed: request for %d bytes!\n",
2692                     scsi_bufflen(scmd));
2693                 return -ENOMEM;
2694         }
2695         if (sges_left > MPI3MR_SG_DEPTH) {
2696                 sdev_printk(KERN_ERR, scmd->device,
2697                     "scsi_dma_map returned unsupported sge count %d!\n",
2698                     sges_left);
2699                 return -ENOMEM;
2700         }
2701
2702         sges_in_segment = (mrioc->facts.op_req_sz -
2703             offsetof(struct mpi3_scsi_io_request, sgl)) / sizeof(struct mpi3_sge_common);
2704
2705         if (scsiio_req->sgl[0].eedp.flags ==
2706             MPI3_SGE_FLAGS_ELEMENT_TYPE_EXTENDED && !meta_sg) {
2707                 sg_local += sizeof(struct mpi3_sge_common);
2708                 sges_in_segment--;
2709                 /* Reserve 1st segment (scsiio_req->sgl[0]) for eedp */
2710         }
2711
2712         if (scsiio_req->msg_flags ==
2713             MPI3_SCSIIO_MSGFLAGS_METASGL_VALID && !meta_sg) {
2714                 sges_in_segment--;
2715                 /* Reserve last segment (scsiio_req->sgl[3]) for meta sg */
2716         }
2717
2718         if (meta_sg)
2719                 sges_in_segment = 1;
2720
2721         if (sges_left <= sges_in_segment)
2722                 goto fill_in_last_segment;
2723
2724         /* fill in main message segment when there is a chain following */
2725         while (sges_in_segment > 1) {
2726                 mpi3mr_add_sg_single(sg_local, simple_sgl_flags,
2727                     sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2728                 sg_scmd = sg_next(sg_scmd);
2729                 sg_local += sizeof(struct mpi3_sge_common);
2730                 sges_left--;
2731                 sges_in_segment--;
2732         }
2733
2734         chain_idx = mpi3mr_get_chain_idx(mrioc);
2735         if (chain_idx < 0)
2736                 return -1;
2737         chain_req = &mrioc->chain_sgl_list[chain_idx];
2738         if (meta_sg)
2739                 priv->meta_chain_idx = chain_idx;
2740         else
2741                 priv->chain_idx = chain_idx;
2742
2743         chain = chain_req->addr;
2744         chain_dma = chain_req->dma_addr;
2745         sges_in_segment = sges_left;
2746         chain_length = sges_in_segment * sizeof(struct mpi3_sge_common);
2747
2748         mpi3mr_add_sg_single(sg_local, last_chain_sgl_flags,
2749             chain_length, chain_dma);
2750
2751         sg_local = chain;
2752
2753 fill_in_last_segment:
2754         while (sges_left > 0) {
2755                 if (sges_left == 1)
2756                         mpi3mr_add_sg_single(sg_local,
2757                             simple_sgl_flags_last, sg_dma_len(sg_scmd),
2758                             sg_dma_address(sg_scmd));
2759                 else
2760                         mpi3mr_add_sg_single(sg_local, simple_sgl_flags,
2761                             sg_dma_len(sg_scmd), sg_dma_address(sg_scmd));
2762                 sg_scmd = sg_next(sg_scmd);
2763                 sg_local += sizeof(struct mpi3_sge_common);
2764                 sges_left--;
2765         }
2766
2767         return 0;
2768 }
2769
2770 /**
2771  * mpi3mr_build_sg_scmd - build scatter gather list for SCSI IO
2772  * @mrioc: Adapter instance reference
2773  * @scmd: SCSI command reference
2774  * @scsiio_req: MPI3 SCSI IO request
2775  *
2776  * This function calls mpi3mr_prepare_sg_scmd for constructing
2777  * both data SGEs and protection information SGEs in the MPI
2778  * format from the SCSI Command as appropriate .
2779  *
2780  * Return: return value of mpi3mr_prepare_sg_scmd.
2781  */
2782 static int mpi3mr_build_sg_scmd(struct mpi3mr_ioc *mrioc,
2783         struct scsi_cmnd *scmd, struct mpi3_scsi_io_request *scsiio_req)
2784 {
2785         int ret;
2786
2787         ret = mpi3mr_prepare_sg_scmd(mrioc, scmd, scsiio_req);
2788         if (ret)
2789                 return ret;
2790
2791         if (scsiio_req->msg_flags == MPI3_SCSIIO_MSGFLAGS_METASGL_VALID) {
2792                 /* There is a valid meta sg */
2793                 scsiio_req->flags |=
2794                     cpu_to_le32(MPI3_SCSIIO_FLAGS_DMAOPERATION_HOST_PI);
2795                 ret = mpi3mr_prepare_sg_scmd(mrioc, scmd, scsiio_req);
2796         }
2797
2798         return ret;
2799 }
2800
2801 /**
2802  * mpi3mr_print_response_code - print TM response as a string
2803  * @mrioc: Adapter instance reference
2804  * @resp_code: TM response code
2805  *
2806  * Print TM response code as a readable string.
2807  *
2808  * Return: Nothing.
2809  */
2810 static void mpi3mr_print_response_code(struct mpi3mr_ioc *mrioc, u8 resp_code)
2811 {
2812         char *desc;
2813
2814         switch (resp_code) {
2815         case MPI3MR_RSP_TM_COMPLETE:
2816                 desc = "task management request completed";
2817                 break;
2818         case MPI3MR_RSP_INVALID_FRAME:
2819                 desc = "invalid frame";
2820                 break;
2821         case MPI3MR_RSP_TM_NOT_SUPPORTED:
2822                 desc = "task management request not supported";
2823                 break;
2824         case MPI3MR_RSP_TM_FAILED:
2825                 desc = "task management request failed";
2826                 break;
2827         case MPI3MR_RSP_TM_SUCCEEDED:
2828                 desc = "task management request succeeded";
2829                 break;
2830         case MPI3MR_RSP_TM_INVALID_LUN:
2831                 desc = "invalid lun";
2832                 break;
2833         case MPI3MR_RSP_TM_OVERLAPPED_TAG:
2834                 desc = "overlapped tag attempted";
2835                 break;
2836         case MPI3MR_RSP_IO_QUEUED_ON_IOC:
2837                 desc = "task queued, however not sent to target";
2838                 break;
2839         default:
2840                 desc = "unknown";
2841                 break;
2842         }
2843         ioc_info(mrioc, "%s :response_code(0x%01x): %s\n", __func__,
2844             resp_code, desc);
2845 }
2846
2847 /**
2848  * mpi3mr_issue_tm - Issue Task Management request
2849  * @mrioc: Adapter instance reference
2850  * @tm_type: Task Management type
2851  * @handle: Device handle
2852  * @lun: lun ID
2853  * @htag: Host tag of the TM request
2854  * @drv_cmd: Internal command tracker
2855  * @resp_code: Response code place holder
2856  * @cmd_priv: SCSI command private data
2857  *
2858  * Issues a Task Management Request to the controller for a
2859  * specified target, lun and command and wait for its completion
2860  * and check TM response. Recover the TM if it timed out by
2861  * issuing controller reset.
2862  *
2863  * Return: 0 on success, non-zero on errors
2864  */
2865 static int mpi3mr_issue_tm(struct mpi3mr_ioc *mrioc, u8 tm_type,
2866         u16 handle, uint lun, u16 htag, ulong timeout,
2867         struct mpi3mr_drv_cmd *drv_cmd,
2868         u8 *resp_code, struct scmd_priv *cmd_priv)
2869 {
2870         struct mpi3_scsi_task_mgmt_request tm_req;
2871         struct mpi3_scsi_task_mgmt_reply *tm_reply = NULL;
2872         int retval = 0;
2873         struct mpi3mr_tgt_dev *tgtdev = NULL;
2874         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL;
2875         struct op_req_qinfo *op_req_q = NULL;
2876
2877         ioc_info(mrioc, "%s :Issue TM: TM type (0x%x) for devhandle 0x%04x\n",
2878              __func__, tm_type, handle);
2879         if (mrioc->unrecoverable) {
2880                 retval = -1;
2881                 ioc_err(mrioc, "%s :Issue TM: Unrecoverable controller\n",
2882                     __func__);
2883                 goto out;
2884         }
2885
2886         memset(&tm_req, 0, sizeof(tm_req));
2887         mutex_lock(&drv_cmd->mutex);
2888         if (drv_cmd->state & MPI3MR_CMD_PENDING) {
2889                 retval = -1;
2890                 ioc_err(mrioc, "%s :Issue TM: Command is in use\n", __func__);
2891                 mutex_unlock(&drv_cmd->mutex);
2892                 goto out;
2893         }
2894         if (mrioc->reset_in_progress) {
2895                 retval = -1;
2896                 ioc_err(mrioc, "%s :Issue TM: Reset in progress\n", __func__);
2897                 mutex_unlock(&drv_cmd->mutex);
2898                 goto out;
2899         }
2900
2901         drv_cmd->state = MPI3MR_CMD_PENDING;
2902         drv_cmd->is_waiting = 1;
2903         drv_cmd->callback = NULL;
2904         tm_req.dev_handle = cpu_to_le16(handle);
2905         tm_req.task_type = tm_type;
2906         tm_req.host_tag = cpu_to_le16(htag);
2907
2908         int_to_scsilun(lun, (struct scsi_lun *)tm_req.lun);
2909         tm_req.function = MPI3_FUNCTION_SCSI_TASK_MGMT;
2910
2911         tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, handle);
2912         if (tgtdev && tgtdev->starget && tgtdev->starget->hostdata) {
2913                 scsi_tgt_priv_data = (struct mpi3mr_stgt_priv_data *)
2914                     tgtdev->starget->hostdata;
2915                 atomic_inc(&scsi_tgt_priv_data->block_io);
2916         }
2917         if (cmd_priv) {
2918                 op_req_q = &mrioc->req_qinfo[cmd_priv->req_q_idx];
2919                 tm_req.task_host_tag = cpu_to_le16(cmd_priv->host_tag);
2920                 tm_req.task_request_queue_id = cpu_to_le16(op_req_q->qid);
2921         }
2922         if (tgtdev && (tgtdev->dev_type == MPI3_DEVICE_DEVFORM_PCIE)) {
2923                 if (cmd_priv && tgtdev->dev_spec.pcie_inf.abort_to)
2924                         timeout = tgtdev->dev_spec.pcie_inf.abort_to;
2925                 else if (!cmd_priv && tgtdev->dev_spec.pcie_inf.reset_to)
2926                         timeout = tgtdev->dev_spec.pcie_inf.reset_to;
2927         }
2928
2929         init_completion(&drv_cmd->done);
2930         retval = mpi3mr_admin_request_post(mrioc, &tm_req, sizeof(tm_req), 1);
2931         if (retval) {
2932                 ioc_err(mrioc, "%s :Issue TM: Admin Post failed\n", __func__);
2933                 goto out_unlock;
2934         }
2935         wait_for_completion_timeout(&drv_cmd->done, (timeout * HZ));
2936
2937         if (!(drv_cmd->state & MPI3MR_CMD_COMPLETE)) {
2938                 ioc_err(mrioc, "%s :Issue TM: command timed out\n", __func__);
2939                 drv_cmd->is_waiting = 0;
2940                 retval = -1;
2941                 if (!(drv_cmd->state & MPI3MR_CMD_RESET))
2942                         mpi3mr_soft_reset_handler(mrioc,
2943                             MPI3MR_RESET_FROM_TM_TIMEOUT, 1);
2944                 goto out_unlock;
2945         }
2946
2947         if (drv_cmd->state & MPI3MR_CMD_REPLY_VALID)
2948                 tm_reply = (struct mpi3_scsi_task_mgmt_reply *)drv_cmd->reply;
2949
2950         if (drv_cmd->ioc_status != MPI3_IOCSTATUS_SUCCESS) {
2951                 ioc_err(mrioc,
2952                     "%s :Issue TM: handle(0x%04x) Failed ioc_status(0x%04x) Loginfo(0x%08x)\n",
2953                     __func__, handle, drv_cmd->ioc_status,
2954                     drv_cmd->ioc_loginfo);
2955                 retval = -1;
2956                 goto out_unlock;
2957         }
2958
2959         if (!tm_reply) {
2960                 ioc_err(mrioc, "%s :Issue TM: No TM Reply message\n", __func__);
2961                 retval = -1;
2962                 goto out_unlock;
2963         }
2964
2965         *resp_code = le32_to_cpu(tm_reply->response_data) &
2966             MPI3MR_RI_MASK_RESPCODE;
2967         switch (*resp_code) {
2968         case MPI3MR_RSP_TM_SUCCEEDED:
2969         case MPI3MR_RSP_TM_COMPLETE:
2970                 break;
2971         case MPI3MR_RSP_IO_QUEUED_ON_IOC:
2972                 if (tm_type != MPI3_SCSITASKMGMT_TASKTYPE_QUERY_TASK)
2973                         retval = -1;
2974                 break;
2975         default:
2976                 retval = -1;
2977                 break;
2978         }
2979
2980         ioc_info(mrioc,
2981             "%s :Issue TM: Completed TM type (0x%x) handle(0x%04x) ",
2982             __func__, tm_type, handle);
2983         ioc_info(mrioc,
2984             "with ioc_status(0x%04x), loginfo(0x%08x), term_count(0x%08x)\n",
2985             drv_cmd->ioc_status, drv_cmd->ioc_loginfo,
2986             le32_to_cpu(tm_reply->termination_count));
2987         mpi3mr_print_response_code(mrioc, *resp_code);
2988
2989 out_unlock:
2990         drv_cmd->state = MPI3MR_CMD_NOTUSED;
2991         mutex_unlock(&drv_cmd->mutex);
2992         if (scsi_tgt_priv_data)
2993                 atomic_dec_if_positive(&scsi_tgt_priv_data->block_io);
2994         if (tgtdev)
2995                 mpi3mr_tgtdev_put(tgtdev);
2996         if (!retval) {
2997                 /*
2998                  * Flush all IRQ handlers by calling synchronize_irq().
2999                  * mpi3mr_ioc_disable_intr() takes care of it.
3000                  */
3001                 mpi3mr_ioc_disable_intr(mrioc);
3002                 mpi3mr_ioc_enable_intr(mrioc);
3003         }
3004 out:
3005         return retval;
3006 }
3007
3008 /**
3009  * mpi3mr_bios_param - BIOS param callback
3010  * @sdev: SCSI device reference
3011  * @bdev: Block device reference
3012  * @capacity: Capacity in logical sectors
3013  * @params: Parameter array
3014  *
3015  * Just the parameters with heads/secots/cylinders.
3016  *
3017  * Return: 0 always
3018  */
3019 static int mpi3mr_bios_param(struct scsi_device *sdev,
3020         struct block_device *bdev, sector_t capacity, int params[])
3021 {
3022         int heads;
3023         int sectors;
3024         sector_t cylinders;
3025         ulong dummy;
3026
3027         heads = 64;
3028         sectors = 32;
3029
3030         dummy = heads * sectors;
3031         cylinders = capacity;
3032         sector_div(cylinders, dummy);
3033
3034         if ((ulong)capacity >= 0x200000) {
3035                 heads = 255;
3036                 sectors = 63;
3037                 dummy = heads * sectors;
3038                 cylinders = capacity;
3039                 sector_div(cylinders, dummy);
3040         }
3041
3042         params[0] = heads;
3043         params[1] = sectors;
3044         params[2] = cylinders;
3045         return 0;
3046 }
3047
3048 /**
3049  * mpi3mr_map_queues - Map queues callback handler
3050  * @shost: SCSI host reference
3051  *
3052  * Call the blk_mq_pci_map_queues with from which operational
3053  * queue the mapping has to be done
3054  *
3055  * Return: return of blk_mq_pci_map_queues
3056  */
3057 static int mpi3mr_map_queues(struct Scsi_Host *shost)
3058 {
3059         struct mpi3mr_ioc *mrioc = shost_priv(shost);
3060
3061         return blk_mq_pci_map_queues(&shost->tag_set.map[HCTX_TYPE_DEFAULT],
3062             mrioc->pdev, mrioc->op_reply_q_offset);
3063 }
3064
3065 /**
3066  * mpi3mr_get_fw_pending_ios - Calculate pending I/O count
3067  * @mrioc: Adapter instance reference
3068  *
3069  * Calculate the pending I/Os for the controller and return.
3070  *
3071  * Return: Number of pending I/Os
3072  */
3073 static inline int mpi3mr_get_fw_pending_ios(struct mpi3mr_ioc *mrioc)
3074 {
3075         u16 i;
3076         uint pend_ios = 0;
3077
3078         for (i = 0; i < mrioc->num_op_reply_q; i++)
3079                 pend_ios += atomic_read(&mrioc->op_reply_qinfo[i].pend_ios);
3080         return pend_ios;
3081 }
3082
3083 /**
3084  * mpi3mr_print_pending_host_io - print pending I/Os
3085  * @mrioc: Adapter instance reference
3086  *
3087  * Print number of pending I/Os and each I/O details prior to
3088  * reset for debug purpose.
3089  *
3090  * Return: Nothing
3091  */
3092 static void mpi3mr_print_pending_host_io(struct mpi3mr_ioc *mrioc)
3093 {
3094         struct Scsi_Host *shost = mrioc->shost;
3095
3096         ioc_info(mrioc, "%s :Pending commands prior to reset: %d\n",
3097             __func__, mpi3mr_get_fw_pending_ios(mrioc));
3098         blk_mq_tagset_busy_iter(&shost->tag_set,
3099             mpi3mr_print_scmd, (void *)mrioc);
3100 }
3101
3102 /**
3103  * mpi3mr_wait_for_host_io - block for I/Os to complete
3104  * @mrioc: Adapter instance reference
3105  * @timeout: time out in seconds
3106  * Waits for pending I/Os for the given adapter to complete or
3107  * to hit the timeout.
3108  *
3109  * Return: Nothing
3110  */
3111 void mpi3mr_wait_for_host_io(struct mpi3mr_ioc *mrioc, u32 timeout)
3112 {
3113         enum mpi3mr_iocstate iocstate;
3114         int i = 0;
3115
3116         iocstate = mpi3mr_get_iocstate(mrioc);
3117         if (iocstate != MRIOC_STATE_READY)
3118                 return;
3119
3120         if (!mpi3mr_get_fw_pending_ios(mrioc))
3121                 return;
3122         ioc_info(mrioc,
3123             "%s :Waiting for %d seconds prior to reset for %d I/O\n",
3124             __func__, timeout, mpi3mr_get_fw_pending_ios(mrioc));
3125
3126         for (i = 0; i < timeout; i++) {
3127                 if (!mpi3mr_get_fw_pending_ios(mrioc))
3128                         break;
3129                 iocstate = mpi3mr_get_iocstate(mrioc);
3130                 if (iocstate != MRIOC_STATE_READY)
3131                         break;
3132                 msleep(1000);
3133         }
3134
3135         ioc_info(mrioc, "%s :Pending I/Os after wait is: %d\n", __func__,
3136             mpi3mr_get_fw_pending_ios(mrioc));
3137 }
3138
3139 /**
3140  * mpi3mr_eh_host_reset - Host reset error handling callback
3141  * @scmd: SCSI command reference
3142  *
3143  * Issue controller reset if the scmd is for a Physical Device,
3144  * if the scmd is for RAID volume, then wait for
3145  * MPI3MR_RAID_ERRREC_RESET_TIMEOUT and checke whether any
3146  * pending I/Os prior to issuing reset to the controller.
3147  *
3148  * Return: SUCCESS of successful reset else FAILED
3149  */
3150 static int mpi3mr_eh_host_reset(struct scsi_cmnd *scmd)
3151 {
3152         struct mpi3mr_ioc *mrioc = shost_priv(scmd->device->host);
3153         struct mpi3mr_stgt_priv_data *stgt_priv_data;
3154         struct mpi3mr_sdev_priv_data *sdev_priv_data;
3155         u8 dev_type = MPI3_DEVICE_DEVFORM_VD;
3156         int retval = FAILED, ret;
3157
3158         sdev_priv_data = scmd->device->hostdata;
3159         if (sdev_priv_data && sdev_priv_data->tgt_priv_data) {
3160                 stgt_priv_data = sdev_priv_data->tgt_priv_data;
3161                 dev_type = stgt_priv_data->dev_type;
3162         }
3163
3164         if (dev_type == MPI3_DEVICE_DEVFORM_VD) {
3165                 mpi3mr_wait_for_host_io(mrioc,
3166                     MPI3MR_RAID_ERRREC_RESET_TIMEOUT);
3167                 if (!mpi3mr_get_fw_pending_ios(mrioc)) {
3168                         retval = SUCCESS;
3169                         goto out;
3170                 }
3171         }
3172
3173         mpi3mr_print_pending_host_io(mrioc);
3174         ret = mpi3mr_soft_reset_handler(mrioc,
3175             MPI3MR_RESET_FROM_EH_HOS, 1);
3176         if (ret)
3177                 goto out;
3178
3179         retval = SUCCESS;
3180 out:
3181         sdev_printk(KERN_INFO, scmd->device,
3182             "Host reset is %s for scmd(%p)\n",
3183             ((retval == SUCCESS) ? "SUCCESS" : "FAILED"), scmd);
3184
3185         return retval;
3186 }
3187
3188 /**
3189  * mpi3mr_eh_target_reset - Target reset error handling callback
3190  * @scmd: SCSI command reference
3191  *
3192  * Issue Target reset Task Management and verify the scmd is
3193  * terminated successfully and return status accordingly.
3194  *
3195  * Return: SUCCESS of successful termination of the scmd else
3196  *         FAILED
3197  */
3198 static int mpi3mr_eh_target_reset(struct scsi_cmnd *scmd)
3199 {
3200         struct mpi3mr_ioc *mrioc = shost_priv(scmd->device->host);
3201         struct mpi3mr_stgt_priv_data *stgt_priv_data;
3202         struct mpi3mr_sdev_priv_data *sdev_priv_data;
3203         u16 dev_handle;
3204         u8 resp_code = 0;
3205         int retval = FAILED, ret = 0;
3206
3207         sdev_printk(KERN_INFO, scmd->device,
3208             "Attempting Target Reset! scmd(%p)\n", scmd);
3209         scsi_print_command(scmd);
3210
3211         sdev_priv_data = scmd->device->hostdata;
3212         if (!sdev_priv_data || !sdev_priv_data->tgt_priv_data) {
3213                 sdev_printk(KERN_INFO, scmd->device,
3214                     "SCSI device is not available\n");
3215                 retval = SUCCESS;
3216                 goto out;
3217         }
3218
3219         stgt_priv_data = sdev_priv_data->tgt_priv_data;
3220         dev_handle = stgt_priv_data->dev_handle;
3221         sdev_printk(KERN_INFO, scmd->device,
3222             "Target Reset is issued to handle(0x%04x)\n",
3223             dev_handle);
3224
3225         ret = mpi3mr_issue_tm(mrioc,
3226             MPI3_SCSITASKMGMT_TASKTYPE_TARGET_RESET, dev_handle,
3227             sdev_priv_data->lun_id, MPI3MR_HOSTTAG_BLK_TMS,
3228             MPI3MR_RESETTM_TIMEOUT, &mrioc->host_tm_cmds, &resp_code, NULL);
3229
3230         if (ret)
3231                 goto out;
3232
3233         retval = SUCCESS;
3234 out:
3235         sdev_printk(KERN_INFO, scmd->device,
3236             "Target reset is %s for scmd(%p)\n",
3237             ((retval == SUCCESS) ? "SUCCESS" : "FAILED"), scmd);
3238
3239         return retval;
3240 }
3241
3242 /**
3243  * mpi3mr_eh_dev_reset- Device reset error handling callback
3244  * @scmd: SCSI command reference
3245  *
3246  * Issue lun reset Task Management and verify the scmd is
3247  * terminated successfully and return status accordingly.
3248  *
3249  * Return: SUCCESS of successful termination of the scmd else
3250  *         FAILED
3251  */
3252 static int mpi3mr_eh_dev_reset(struct scsi_cmnd *scmd)
3253 {
3254         struct mpi3mr_ioc *mrioc = shost_priv(scmd->device->host);
3255         struct mpi3mr_stgt_priv_data *stgt_priv_data;
3256         struct mpi3mr_sdev_priv_data *sdev_priv_data;
3257         u16 dev_handle;
3258         u8 resp_code = 0;
3259         int retval = FAILED, ret = 0;
3260
3261         sdev_printk(KERN_INFO, scmd->device,
3262             "Attempting Device(lun) Reset! scmd(%p)\n", scmd);
3263         scsi_print_command(scmd);
3264
3265         sdev_priv_data = scmd->device->hostdata;
3266         if (!sdev_priv_data || !sdev_priv_data->tgt_priv_data) {
3267                 sdev_printk(KERN_INFO, scmd->device,
3268                     "SCSI device is not available\n");
3269                 retval = SUCCESS;
3270                 goto out;
3271         }
3272
3273         stgt_priv_data = sdev_priv_data->tgt_priv_data;
3274         dev_handle = stgt_priv_data->dev_handle;
3275         sdev_printk(KERN_INFO, scmd->device,
3276             "Device(lun) Reset is issued to handle(0x%04x)\n", dev_handle);
3277
3278         ret = mpi3mr_issue_tm(mrioc,
3279             MPI3_SCSITASKMGMT_TASKTYPE_LOGICAL_UNIT_RESET, dev_handle,
3280             sdev_priv_data->lun_id, MPI3MR_HOSTTAG_BLK_TMS,
3281             MPI3MR_RESETTM_TIMEOUT, &mrioc->host_tm_cmds, &resp_code, NULL);
3282
3283         if (ret)
3284                 goto out;
3285
3286         retval = SUCCESS;
3287 out:
3288         sdev_printk(KERN_INFO, scmd->device,
3289             "Device(lun) reset is %s for scmd(%p)\n",
3290             ((retval == SUCCESS) ? "SUCCESS" : "FAILED"), scmd);
3291
3292         return retval;
3293 }
3294
3295 /**
3296  * mpi3mr_scan_start - Scan start callback handler
3297  * @shost: SCSI host reference
3298  *
3299  * Issue port enable request asynchronously.
3300  *
3301  * Return: Nothing
3302  */
3303 static void mpi3mr_scan_start(struct Scsi_Host *shost)
3304 {
3305         struct mpi3mr_ioc *mrioc = shost_priv(shost);
3306
3307         mrioc->scan_started = 1;
3308         ioc_info(mrioc, "%s :Issuing Port Enable\n", __func__);
3309         if (mpi3mr_issue_port_enable(mrioc, 1)) {
3310                 ioc_err(mrioc, "%s :Issuing port enable failed\n", __func__);
3311                 mrioc->scan_started = 0;
3312                 mrioc->scan_failed = MPI3_IOCSTATUS_INTERNAL_ERROR;
3313         }
3314 }
3315
3316 /**
3317  * mpi3mr_scan_finished - Scan finished callback handler
3318  * @shost: SCSI host reference
3319  * @time: Jiffies from the scan start
3320  *
3321  * Checks whether the port enable is completed or timedout or
3322  * failed and set the scan status accordingly after taking any
3323  * recovery if required.
3324  *
3325  * Return: 1 on scan finished or timed out, 0 for in progress
3326  */
3327 static int mpi3mr_scan_finished(struct Scsi_Host *shost,
3328         unsigned long time)
3329 {
3330         struct mpi3mr_ioc *mrioc = shost_priv(shost);
3331         u32 pe_timeout = MPI3MR_PORTENABLE_TIMEOUT;
3332         u32 ioc_status = readl(&mrioc->sysif_regs->ioc_status);
3333
3334         if ((ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY) ||
3335             (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT)) {
3336                 ioc_err(mrioc, "port enable failed due to fault or reset\n");
3337                 mpi3mr_print_fault_info(mrioc);
3338                 mrioc->scan_failed = MPI3_IOCSTATUS_INTERNAL_ERROR;
3339                 mrioc->scan_started = 0;
3340                 mrioc->init_cmds.is_waiting = 0;
3341                 mrioc->init_cmds.callback = NULL;
3342                 mrioc->init_cmds.state = MPI3MR_CMD_NOTUSED;
3343         }
3344
3345         if (time >= (pe_timeout * HZ)) {
3346                 ioc_err(mrioc, "port enable failed due to time out\n");
3347                 mpi3mr_check_rh_fault_ioc(mrioc,
3348                     MPI3MR_RESET_FROM_PE_TIMEOUT);
3349                 mrioc->scan_failed = MPI3_IOCSTATUS_INTERNAL_ERROR;
3350                 mrioc->scan_started = 0;
3351                 mrioc->init_cmds.is_waiting = 0;
3352                 mrioc->init_cmds.callback = NULL;
3353                 mrioc->init_cmds.state = MPI3MR_CMD_NOTUSED;
3354         }
3355
3356         if (mrioc->scan_started)
3357                 return 0;
3358
3359         if (mrioc->scan_failed) {
3360                 ioc_err(mrioc,
3361                     "port enable failed with status=0x%04x\n",
3362                     mrioc->scan_failed);
3363         } else
3364                 ioc_info(mrioc, "port enable is successfully completed\n");
3365
3366         mpi3mr_start_watchdog(mrioc);
3367         mrioc->is_driver_loading = 0;
3368         return 1;
3369 }
3370
3371 /**
3372  * mpi3mr_slave_destroy - Slave destroy callback handler
3373  * @sdev: SCSI device reference
3374  *
3375  * Cleanup and free per device(lun) private data.
3376  *
3377  * Return: Nothing.
3378  */
3379 static void mpi3mr_slave_destroy(struct scsi_device *sdev)
3380 {
3381         struct Scsi_Host *shost;
3382         struct mpi3mr_ioc *mrioc;
3383         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data;
3384         struct mpi3mr_tgt_dev *tgt_dev;
3385         unsigned long flags;
3386         struct scsi_target *starget;
3387
3388         if (!sdev->hostdata)
3389                 return;
3390
3391         starget = scsi_target(sdev);
3392         shost = dev_to_shost(&starget->dev);
3393         mrioc = shost_priv(shost);
3394         scsi_tgt_priv_data = starget->hostdata;
3395
3396         scsi_tgt_priv_data->num_luns--;
3397
3398         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
3399         tgt_dev = __mpi3mr_get_tgtdev_by_perst_id(mrioc, starget->id);
3400         if (tgt_dev && (!scsi_tgt_priv_data->num_luns))
3401                 tgt_dev->starget = NULL;
3402         if (tgt_dev)
3403                 mpi3mr_tgtdev_put(tgt_dev);
3404         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3405
3406         kfree(sdev->hostdata);
3407         sdev->hostdata = NULL;
3408 }
3409
3410 /**
3411  * mpi3mr_target_destroy - Target destroy callback handler
3412  * @starget: SCSI target reference
3413  *
3414  * Cleanup and free per target private data.
3415  *
3416  * Return: Nothing.
3417  */
3418 static void mpi3mr_target_destroy(struct scsi_target *starget)
3419 {
3420         struct Scsi_Host *shost;
3421         struct mpi3mr_ioc *mrioc;
3422         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data;
3423         struct mpi3mr_tgt_dev *tgt_dev;
3424         unsigned long flags;
3425
3426         if (!starget->hostdata)
3427                 return;
3428
3429         shost = dev_to_shost(&starget->dev);
3430         mrioc = shost_priv(shost);
3431         scsi_tgt_priv_data = starget->hostdata;
3432
3433         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
3434         tgt_dev = __mpi3mr_get_tgtdev_from_tgtpriv(mrioc, scsi_tgt_priv_data);
3435         if (tgt_dev && (tgt_dev->starget == starget) &&
3436             (tgt_dev->perst_id == starget->id))
3437                 tgt_dev->starget = NULL;
3438         if (tgt_dev) {
3439                 scsi_tgt_priv_data->tgt_dev = NULL;
3440                 scsi_tgt_priv_data->perst_id = 0;
3441                 mpi3mr_tgtdev_put(tgt_dev);
3442                 mpi3mr_tgtdev_put(tgt_dev);
3443         }
3444         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3445
3446         kfree(starget->hostdata);
3447         starget->hostdata = NULL;
3448 }
3449
3450 /**
3451  * mpi3mr_slave_configure - Slave configure callback handler
3452  * @sdev: SCSI device reference
3453  *
3454  * Configure queue depth, max hardware sectors and virt boundary
3455  * as required
3456  *
3457  * Return: 0 always.
3458  */
3459 static int mpi3mr_slave_configure(struct scsi_device *sdev)
3460 {
3461         struct scsi_target *starget;
3462         struct Scsi_Host *shost;
3463         struct mpi3mr_ioc *mrioc;
3464         struct mpi3mr_tgt_dev *tgt_dev;
3465         unsigned long flags;
3466         int retval = 0;
3467
3468         starget = scsi_target(sdev);
3469         shost = dev_to_shost(&starget->dev);
3470         mrioc = shost_priv(shost);
3471
3472         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
3473         tgt_dev = __mpi3mr_get_tgtdev_by_perst_id(mrioc, starget->id);
3474         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3475         if (!tgt_dev)
3476                 return -ENXIO;
3477
3478         mpi3mr_change_queue_depth(sdev, tgt_dev->q_depth);
3479         switch (tgt_dev->dev_type) {
3480         case MPI3_DEVICE_DEVFORM_PCIE:
3481                 /*The block layer hw sector size = 512*/
3482                 if ((tgt_dev->dev_spec.pcie_inf.dev_info &
3483                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) ==
3484                     MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_NVME_DEVICE) {
3485                         blk_queue_max_hw_sectors(sdev->request_queue,
3486                             tgt_dev->dev_spec.pcie_inf.mdts / 512);
3487                         if (tgt_dev->dev_spec.pcie_inf.pgsz == 0)
3488                                 blk_queue_virt_boundary(sdev->request_queue,
3489                                     ((1 << MPI3MR_DEFAULT_PGSZEXP) - 1));
3490                         else
3491                                 blk_queue_virt_boundary(sdev->request_queue,
3492                                     ((1 << tgt_dev->dev_spec.pcie_inf.pgsz) - 1));
3493                 }
3494                 break;
3495         default:
3496                 break;
3497         }
3498
3499         mpi3mr_tgtdev_put(tgt_dev);
3500
3501         return retval;
3502 }
3503
3504 /**
3505  * mpi3mr_slave_alloc -Slave alloc callback handler
3506  * @sdev: SCSI device reference
3507  *
3508  * Allocate per device(lun) private data and initialize it.
3509  *
3510  * Return: 0 on success -ENOMEM on memory allocation failure.
3511  */
3512 static int mpi3mr_slave_alloc(struct scsi_device *sdev)
3513 {
3514         struct Scsi_Host *shost;
3515         struct mpi3mr_ioc *mrioc;
3516         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data;
3517         struct mpi3mr_tgt_dev *tgt_dev;
3518         struct mpi3mr_sdev_priv_data *scsi_dev_priv_data;
3519         unsigned long flags;
3520         struct scsi_target *starget;
3521         int retval = 0;
3522
3523         starget = scsi_target(sdev);
3524         shost = dev_to_shost(&starget->dev);
3525         mrioc = shost_priv(shost);
3526         scsi_tgt_priv_data = starget->hostdata;
3527
3528         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
3529         tgt_dev = __mpi3mr_get_tgtdev_by_perst_id(mrioc, starget->id);
3530
3531         if (tgt_dev) {
3532                 if (tgt_dev->starget == NULL)
3533                         tgt_dev->starget = starget;
3534                 mpi3mr_tgtdev_put(tgt_dev);
3535                 retval = 0;
3536         } else {
3537                 spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3538                 return -ENXIO;
3539         }
3540
3541         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3542
3543         scsi_dev_priv_data = kzalloc(sizeof(*scsi_dev_priv_data), GFP_KERNEL);
3544         if (!scsi_dev_priv_data)
3545                 return -ENOMEM;
3546
3547         scsi_dev_priv_data->lun_id = sdev->lun;
3548         scsi_dev_priv_data->tgt_priv_data = scsi_tgt_priv_data;
3549         sdev->hostdata = scsi_dev_priv_data;
3550
3551         scsi_tgt_priv_data->num_luns++;
3552
3553         return retval;
3554 }
3555
3556 /**
3557  * mpi3mr_target_alloc - Target alloc callback handler
3558  * @starget: SCSI target reference
3559  *
3560  * Allocate per target private data and initialize it.
3561  *
3562  * Return: 0 on success -ENOMEM on memory allocation failure.
3563  */
3564 static int mpi3mr_target_alloc(struct scsi_target *starget)
3565 {
3566         struct Scsi_Host *shost = dev_to_shost(&starget->dev);
3567         struct mpi3mr_ioc *mrioc = shost_priv(shost);
3568         struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data;
3569         struct mpi3mr_tgt_dev *tgt_dev;
3570         unsigned long flags;
3571         int retval = 0;
3572
3573         scsi_tgt_priv_data = kzalloc(sizeof(*scsi_tgt_priv_data), GFP_KERNEL);
3574         if (!scsi_tgt_priv_data)
3575                 return -ENOMEM;
3576
3577         starget->hostdata = scsi_tgt_priv_data;
3578
3579         spin_lock_irqsave(&mrioc->tgtdev_lock, flags);
3580         tgt_dev = __mpi3mr_get_tgtdev_by_perst_id(mrioc, starget->id);
3581         if (tgt_dev && !tgt_dev->is_hidden) {
3582                 scsi_tgt_priv_data->starget = starget;
3583                 scsi_tgt_priv_data->dev_handle = tgt_dev->dev_handle;
3584                 scsi_tgt_priv_data->perst_id = tgt_dev->perst_id;
3585                 scsi_tgt_priv_data->dev_type = tgt_dev->dev_type;
3586                 scsi_tgt_priv_data->tgt_dev = tgt_dev;
3587                 tgt_dev->starget = starget;
3588                 atomic_set(&scsi_tgt_priv_data->block_io, 0);
3589                 retval = 0;
3590         } else
3591                 retval = -ENXIO;
3592         spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags);
3593
3594         return retval;
3595 }
3596
3597 /**
3598  * mpi3mr_check_return_unmap - Whether an unmap is allowed
3599  * @mrioc: Adapter instance reference
3600  * @scmd: SCSI Command reference
3601  *
3602  * The controller hardware cannot handle certain unmap commands
3603  * for NVMe drives, this routine checks those and return true
3604  * and completes the SCSI command with proper status and sense
3605  * data.
3606  *
3607  * Return: TRUE for not  allowed unmap, FALSE otherwise.
3608  */
3609 static bool mpi3mr_check_return_unmap(struct mpi3mr_ioc *mrioc,
3610         struct scsi_cmnd *scmd)
3611 {
3612         unsigned char *buf;
3613         u16 param_len, desc_len, trunc_param_len;
3614
3615         trunc_param_len = param_len = get_unaligned_be16(scmd->cmnd + 7);
3616
3617         if (mrioc->pdev->revision) {
3618                 if ((param_len > 24) && ((param_len - 8) & 0xF)) {
3619                         trunc_param_len -= (param_len - 8) & 0xF;
3620                         dprint_scsi_command(mrioc, scmd, MPI3_DEBUG_SCSI_ERROR);
3621                         dprint_scsi_err(mrioc,
3622                             "truncating param_len from (%d) to (%d)\n",
3623                             param_len, trunc_param_len);
3624                         put_unaligned_be16(trunc_param_len, scmd->cmnd + 7);
3625                         dprint_scsi_command(mrioc, scmd, MPI3_DEBUG_SCSI_ERROR);
3626                 }
3627                 return false;
3628         }
3629
3630         if (!param_len) {
3631                 ioc_warn(mrioc,
3632                     "%s: cdb received with zero parameter length\n",
3633                     __func__);
3634                 scsi_print_command(scmd);
3635                 scmd->result = DID_OK << 16;
3636                 scsi_done(scmd);
3637                 return true;
3638         }
3639
3640         if (param_len < 24) {
3641                 ioc_warn(mrioc,
3642                     "%s: cdb received with invalid param_len: %d\n",
3643                     __func__, param_len);
3644                 scsi_print_command(scmd);
3645                 scmd->result = SAM_STAT_CHECK_CONDITION;
3646                 scsi_build_sense_buffer(0, scmd->sense_buffer, ILLEGAL_REQUEST,
3647                     0x1A, 0);
3648                 scsi_done(scmd);
3649                 return true;
3650         }
3651         if (param_len != scsi_bufflen(scmd)) {
3652                 ioc_warn(mrioc,
3653                     "%s: cdb received with param_len: %d bufflen: %d\n",
3654                     __func__, param_len, scsi_bufflen(scmd));
3655                 scsi_print_command(scmd);
3656                 scmd->result = SAM_STAT_CHECK_CONDITION;
3657                 scsi_build_sense_buffer(0, scmd->sense_buffer, ILLEGAL_REQUEST,
3658                     0x1A, 0);
3659                 scsi_done(scmd);
3660                 return true;
3661         }
3662         buf = kzalloc(scsi_bufflen(scmd), GFP_ATOMIC);
3663         if (!buf) {
3664                 scsi_print_command(scmd);
3665                 scmd->result = SAM_STAT_CHECK_CONDITION;
3666                 scsi_build_sense_buffer(0, scmd->sense_buffer, ILLEGAL_REQUEST,
3667                     0x55, 0x03);
3668                 scsi_done(scmd);
3669                 return true;
3670         }
3671         scsi_sg_copy_to_buffer(scmd, buf, scsi_bufflen(scmd));
3672         desc_len = get_unaligned_be16(&buf[2]);
3673
3674         if (desc_len < 16) {
3675                 ioc_warn(mrioc,
3676                     "%s: Invalid descriptor length in param list: %d\n",
3677                     __func__, desc_len);
3678                 scsi_print_command(scmd);
3679                 scmd->result = SAM_STAT_CHECK_CONDITION;
3680                 scsi_build_sense_buffer(0, scmd->sense_buffer, ILLEGAL_REQUEST,
3681                     0x26, 0);
3682                 scsi_done(scmd);
3683                 kfree(buf);
3684                 return true;
3685         }
3686
3687         if (param_len > (desc_len + 8)) {
3688                 trunc_param_len = desc_len + 8;
3689                 scsi_print_command(scmd);
3690                 dprint_scsi_err(mrioc,
3691                     "truncating param_len(%d) to desc_len+8(%d)\n",
3692                     param_len, trunc_param_len);
3693                 put_unaligned_be16(trunc_param_len, scmd->cmnd + 7);
3694                 scsi_print_command(scmd);
3695         }
3696
3697         kfree(buf);
3698         return false;
3699 }
3700
3701 /**
3702  * mpi3mr_allow_scmd_to_fw - Command is allowed during shutdown
3703  * @scmd: SCSI Command reference
3704  *
3705  * Checks whether a cdb is allowed during shutdown or not.
3706  *
3707  * Return: TRUE for allowed commands, FALSE otherwise.
3708  */
3709
3710 inline bool mpi3mr_allow_scmd_to_fw(struct scsi_cmnd *scmd)
3711 {
3712         switch (scmd->cmnd[0]) {
3713         case SYNCHRONIZE_CACHE:
3714         case START_STOP:
3715                 return true;
3716         default:
3717                 return false;
3718         }
3719 }
3720
3721 /**
3722  * mpi3mr_qcmd - I/O request despatcher
3723  * @shost: SCSI Host reference
3724  * @scmd: SCSI Command reference
3725  *
3726  * Issues the SCSI Command as an MPI3 request.
3727  *
3728  * Return: 0 on successful queueing of the request or if the
3729  *         request is completed with failure.
3730  *         SCSI_MLQUEUE_DEVICE_BUSY when the device is busy.
3731  *         SCSI_MLQUEUE_HOST_BUSY when the host queue is full.
3732  */
3733 static int mpi3mr_qcmd(struct Scsi_Host *shost,
3734         struct scsi_cmnd *scmd)
3735 {
3736         struct mpi3mr_ioc *mrioc = shost_priv(shost);
3737         struct mpi3mr_stgt_priv_data *stgt_priv_data;
3738         struct mpi3mr_sdev_priv_data *sdev_priv_data;
3739         struct scmd_priv *scmd_priv_data = NULL;
3740         struct mpi3_scsi_io_request *scsiio_req = NULL;
3741         struct op_req_qinfo *op_req_q = NULL;
3742         int retval = 0;
3743         u16 dev_handle;
3744         u16 host_tag;
3745         u32 scsiio_flags = 0;
3746         struct request *rq = scsi_cmd_to_rq(scmd);
3747         int iprio_class;
3748         u8 is_pcie_dev = 0;
3749
3750         sdev_priv_data = scmd->device->hostdata;
3751         if (!sdev_priv_data || !sdev_priv_data->tgt_priv_data) {
3752                 scmd->result = DID_NO_CONNECT << 16;
3753                 scsi_done(scmd);
3754                 goto out;
3755         }
3756
3757         if (mrioc->stop_drv_processing &&
3758             !(mpi3mr_allow_scmd_to_fw(scmd))) {
3759                 scmd->result = DID_NO_CONNECT << 16;
3760                 scsi_done(scmd);
3761                 goto out;
3762         }
3763
3764         if (mrioc->reset_in_progress) {
3765                 retval = SCSI_MLQUEUE_HOST_BUSY;
3766                 goto out;
3767         }
3768
3769         stgt_priv_data = sdev_priv_data->tgt_priv_data;
3770
3771         dev_handle = stgt_priv_data->dev_handle;
3772         if (dev_handle == MPI3MR_INVALID_DEV_HANDLE) {
3773                 scmd->result = DID_NO_CONNECT << 16;
3774                 scsi_done(scmd);
3775                 goto out;
3776         }
3777         if (stgt_priv_data->dev_removed) {
3778                 scmd->result = DID_NO_CONNECT << 16;
3779                 scsi_done(scmd);
3780                 goto out;
3781         }
3782
3783         if (atomic_read(&stgt_priv_data->block_io)) {
3784                 if (mrioc->stop_drv_processing) {
3785                         scmd->result = DID_NO_CONNECT << 16;
3786                         scsi_done(scmd);
3787                         goto out;
3788                 }
3789                 retval = SCSI_MLQUEUE_DEVICE_BUSY;
3790                 goto out;
3791         }
3792
3793         if (stgt_priv_data->dev_type == MPI3_DEVICE_DEVFORM_PCIE)
3794                 is_pcie_dev = 1;
3795         if ((scmd->cmnd[0] == UNMAP) && is_pcie_dev &&
3796             (mrioc->pdev->device == MPI3_MFGPAGE_DEVID_SAS4116) &&
3797             mpi3mr_check_return_unmap(mrioc, scmd))
3798                 goto out;
3799
3800         host_tag = mpi3mr_host_tag_for_scmd(mrioc, scmd);
3801         if (host_tag == MPI3MR_HOSTTAG_INVALID) {
3802                 scmd->result = DID_ERROR << 16;
3803                 scsi_done(scmd);
3804                 goto out;
3805         }
3806
3807         if (scmd->sc_data_direction == DMA_FROM_DEVICE)
3808                 scsiio_flags = MPI3_SCSIIO_FLAGS_DATADIRECTION_READ;
3809         else if (scmd->sc_data_direction == DMA_TO_DEVICE)
3810                 scsiio_flags = MPI3_SCSIIO_FLAGS_DATADIRECTION_WRITE;
3811         else
3812                 scsiio_flags = MPI3_SCSIIO_FLAGS_DATADIRECTION_NO_DATA_TRANSFER;
3813
3814         scsiio_flags |= MPI3_SCSIIO_FLAGS_TASKATTRIBUTE_SIMPLEQ;
3815
3816         if (sdev_priv_data->ncq_prio_enable) {
3817                 iprio_class = IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
3818                 if (iprio_class == IOPRIO_CLASS_RT)
3819                         scsiio_flags |= 1 << MPI3_SCSIIO_FLAGS_CMDPRI_SHIFT;
3820         }
3821
3822         if (scmd->cmd_len > 16)
3823                 scsiio_flags |= MPI3_SCSIIO_FLAGS_CDB_GREATER_THAN_16;
3824
3825         scmd_priv_data = scsi_cmd_priv(scmd);
3826         memset(scmd_priv_data->mpi3mr_scsiio_req, 0, MPI3MR_ADMIN_REQ_FRAME_SZ);
3827         scsiio_req = (struct mpi3_scsi_io_request *)scmd_priv_data->mpi3mr_scsiio_req;
3828         scsiio_req->function = MPI3_FUNCTION_SCSI_IO;
3829         scsiio_req->host_tag = cpu_to_le16(host_tag);
3830
3831         mpi3mr_setup_eedp(mrioc, scmd, scsiio_req);
3832
3833         memcpy(scsiio_req->cdb.cdb32, scmd->cmnd, scmd->cmd_len);
3834         scsiio_req->data_length = cpu_to_le32(scsi_bufflen(scmd));
3835         scsiio_req->dev_handle = cpu_to_le16(dev_handle);
3836         scsiio_req->flags = cpu_to_le32(scsiio_flags);
3837         int_to_scsilun(sdev_priv_data->lun_id,
3838             (struct scsi_lun *)scsiio_req->lun);
3839
3840         if (mpi3mr_build_sg_scmd(mrioc, scmd, scsiio_req)) {
3841                 mpi3mr_clear_scmd_priv(mrioc, scmd);
3842                 retval = SCSI_MLQUEUE_HOST_BUSY;
3843                 goto out;
3844         }
3845         op_req_q = &mrioc->req_qinfo[scmd_priv_data->req_q_idx];
3846
3847         if (mpi3mr_op_request_post(mrioc, op_req_q,
3848             scmd_priv_data->mpi3mr_scsiio_req)) {
3849                 mpi3mr_clear_scmd_priv(mrioc, scmd);
3850                 retval = SCSI_MLQUEUE_HOST_BUSY;
3851                 goto out;
3852         }
3853
3854 out:
3855         return retval;
3856 }
3857
3858 static struct scsi_host_template mpi3mr_driver_template = {
3859         .module                         = THIS_MODULE,
3860         .name                           = "MPI3 Storage Controller",
3861         .proc_name                      = MPI3MR_DRIVER_NAME,
3862         .queuecommand                   = mpi3mr_qcmd,
3863         .target_alloc                   = mpi3mr_target_alloc,
3864         .slave_alloc                    = mpi3mr_slave_alloc,
3865         .slave_configure                = mpi3mr_slave_configure,
3866         .target_destroy                 = mpi3mr_target_destroy,
3867         .slave_destroy                  = mpi3mr_slave_destroy,
3868         .scan_finished                  = mpi3mr_scan_finished,
3869         .scan_start                     = mpi3mr_scan_start,
3870         .change_queue_depth             = mpi3mr_change_queue_depth,
3871         .eh_device_reset_handler        = mpi3mr_eh_dev_reset,
3872         .eh_target_reset_handler        = mpi3mr_eh_target_reset,
3873         .eh_host_reset_handler          = mpi3mr_eh_host_reset,
3874         .bios_param                     = mpi3mr_bios_param,
3875         .map_queues                     = mpi3mr_map_queues,
3876         .no_write_same                  = 1,
3877         .can_queue                      = 1,
3878         .this_id                        = -1,
3879         .sg_tablesize                   = MPI3MR_SG_DEPTH,
3880         /* max xfer supported is 1M (2K in 512 byte sized sectors)
3881          */
3882         .max_sectors                    = 2048,
3883         .cmd_per_lun                    = MPI3MR_MAX_CMDS_LUN,
3884         .max_segment_size               = 0xffffffff,
3885         .track_queue_depth              = 1,
3886         .cmd_size                       = sizeof(struct scmd_priv),
3887 };
3888
3889 /**
3890  * mpi3mr_init_drv_cmd - Initialize internal command tracker
3891  * @cmdptr: Internal command tracker
3892  * @host_tag: Host tag used for the specific command
3893  *
3894  * Initialize the internal command tracker structure with
3895  * specified host tag.
3896  *
3897  * Return: Nothing.
3898  */
3899 static inline void mpi3mr_init_drv_cmd(struct mpi3mr_drv_cmd *cmdptr,
3900         u16 host_tag)
3901 {
3902         mutex_init(&cmdptr->mutex);
3903         cmdptr->reply = NULL;
3904         cmdptr->state = MPI3MR_CMD_NOTUSED;
3905         cmdptr->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
3906         cmdptr->host_tag = host_tag;
3907 }
3908
3909 /**
3910  * osintfc_mrioc_security_status -Check controller secure status
3911  * @pdev: PCI device instance
3912  *
3913  * Read the Device Serial Number capability from PCI config
3914  * space and decide whether the controller is secure or not.
3915  *
3916  * Return: 0 on success, non-zero on failure.
3917  */
3918 static int
3919 osintfc_mrioc_security_status(struct pci_dev *pdev)
3920 {
3921         u32 cap_data;
3922         int base;
3923         u32 ctlr_status;
3924         u32 debug_status;
3925         int retval = 0;
3926
3927         base = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_DSN);
3928         if (!base) {
3929                 dev_err(&pdev->dev,
3930                     "%s: PCI_EXT_CAP_ID_DSN is not supported\n", __func__);
3931                 return -1;
3932         }
3933
3934         pci_read_config_dword(pdev, base + 4, &cap_data);
3935
3936         debug_status = cap_data & MPI3MR_CTLR_SECURE_DBG_STATUS_MASK;
3937         ctlr_status = cap_data & MPI3MR_CTLR_SECURITY_STATUS_MASK;
3938
3939         switch (ctlr_status) {
3940         case MPI3MR_INVALID_DEVICE:
3941                 dev_err(&pdev->dev,
3942                     "%s: Non secure ctlr (Invalid) is detected: DID: 0x%x: SVID: 0x%x: SDID: 0x%x\n",
3943                     __func__, pdev->device, pdev->subsystem_vendor,
3944                     pdev->subsystem_device);
3945                 retval = -1;
3946                 break;
3947         case MPI3MR_CONFIG_SECURE_DEVICE:
3948                 if (!debug_status)
3949                         dev_info(&pdev->dev,
3950                             "%s: Config secure ctlr is detected\n",
3951                             __func__);
3952                 break;
3953         case MPI3MR_HARD_SECURE_DEVICE:
3954                 break;
3955         case MPI3MR_TAMPERED_DEVICE:
3956                 dev_err(&pdev->dev,
3957                     "%s: Non secure ctlr (Tampered) is detected: DID: 0x%x: SVID: 0x%x: SDID: 0x%x\n",
3958                     __func__, pdev->device, pdev->subsystem_vendor,
3959                     pdev->subsystem_device);
3960                 retval = -1;
3961                 break;
3962         default:
3963                 retval = -1;
3964                         break;
3965         }
3966
3967         if (!retval && debug_status) {
3968                 dev_err(&pdev->dev,
3969                     "%s: Non secure ctlr (Secure Dbg) is detected: DID: 0x%x: SVID: 0x%x: SDID: 0x%x\n",
3970                     __func__, pdev->device, pdev->subsystem_vendor,
3971                     pdev->subsystem_device);
3972                 retval = -1;
3973         }
3974
3975         return retval;
3976 }
3977
3978 /**
3979  * mpi3mr_probe - PCI probe callback
3980  * @pdev: PCI device instance
3981  * @id: PCI device ID details
3982  *
3983  * controller initialization routine. Checks the security status
3984  * of the controller and if it is invalid or tampered return the
3985  * probe without initializing the controller. Otherwise,
3986  * allocate per adapter instance through shost_priv and
3987  * initialize controller specific data structures, initializae
3988  * the controller hardware, add shost to the SCSI subsystem.
3989  *
3990  * Return: 0 on success, non-zero on failure.
3991  */
3992
3993 static int
3994 mpi3mr_probe(struct pci_dev *pdev, const struct pci_device_id *id)
3995 {
3996         struct mpi3mr_ioc *mrioc = NULL;
3997         struct Scsi_Host *shost = NULL;
3998         int retval = 0, i;
3999
4000         if (osintfc_mrioc_security_status(pdev)) {
4001                 warn_non_secure_ctlr = 1;
4002                 return 1; /* For Invalid and Tampered device */
4003         }
4004
4005         shost = scsi_host_alloc(&mpi3mr_driver_template,
4006             sizeof(struct mpi3mr_ioc));
4007         if (!shost) {
4008                 retval = -ENODEV;
4009                 goto shost_failed;
4010         }
4011
4012         mrioc = shost_priv(shost);
4013         mrioc->id = mrioc_ids++;
4014         sprintf(mrioc->driver_name, "%s", MPI3MR_DRIVER_NAME);
4015         sprintf(mrioc->name, "%s%d", mrioc->driver_name, mrioc->id);
4016         INIT_LIST_HEAD(&mrioc->list);
4017         spin_lock(&mrioc_list_lock);
4018         list_add_tail(&mrioc->list, &mrioc_list);
4019         spin_unlock(&mrioc_list_lock);
4020
4021         spin_lock_init(&mrioc->admin_req_lock);
4022         spin_lock_init(&mrioc->reply_free_queue_lock);
4023         spin_lock_init(&mrioc->sbq_lock);
4024         spin_lock_init(&mrioc->fwevt_lock);
4025         spin_lock_init(&mrioc->tgtdev_lock);
4026         spin_lock_init(&mrioc->watchdog_lock);
4027         spin_lock_init(&mrioc->chain_buf_lock);
4028
4029         INIT_LIST_HEAD(&mrioc->fwevt_list);
4030         INIT_LIST_HEAD(&mrioc->tgtdev_list);
4031         INIT_LIST_HEAD(&mrioc->delayed_rmhs_list);
4032         INIT_LIST_HEAD(&mrioc->delayed_evtack_cmds_list);
4033
4034         mutex_init(&mrioc->reset_mutex);
4035         mpi3mr_init_drv_cmd(&mrioc->init_cmds, MPI3MR_HOSTTAG_INITCMDS);
4036         mpi3mr_init_drv_cmd(&mrioc->host_tm_cmds, MPI3MR_HOSTTAG_BLK_TMS);
4037
4038         for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++)
4039                 mpi3mr_init_drv_cmd(&mrioc->dev_rmhs_cmds[i],
4040                     MPI3MR_HOSTTAG_DEVRMCMD_MIN + i);
4041
4042         if (pdev->revision)
4043                 mrioc->enable_segqueue = true;
4044
4045         init_waitqueue_head(&mrioc->reset_waitq);
4046         mrioc->logging_level = logging_level;
4047         mrioc->shost = shost;
4048         mrioc->pdev = pdev;
4049
4050         /* init shost parameters */
4051         shost->max_cmd_len = MPI3MR_MAX_CDB_LENGTH;
4052         shost->max_lun = -1;
4053         shost->unique_id = mrioc->id;
4054
4055         shost->max_channel = 0;
4056         shost->max_id = 0xFFFFFFFF;
4057
4058         if (prot_mask >= 0)
4059                 scsi_host_set_prot(shost, prot_mask);
4060         else {
4061                 prot_mask = SHOST_DIF_TYPE1_PROTECTION
4062                     | SHOST_DIF_TYPE2_PROTECTION
4063                     | SHOST_DIF_TYPE3_PROTECTION;
4064                 scsi_host_set_prot(shost, prot_mask);
4065         }
4066
4067         ioc_info(mrioc,
4068             "%s :host protection capabilities enabled %s%s%s%s%s%s%s\n",
4069             __func__,
4070             (prot_mask & SHOST_DIF_TYPE1_PROTECTION) ? " DIF1" : "",
4071             (prot_mask & SHOST_DIF_TYPE2_PROTECTION) ? " DIF2" : "",
4072             (prot_mask & SHOST_DIF_TYPE3_PROTECTION) ? " DIF3" : "",
4073             (prot_mask & SHOST_DIX_TYPE0_PROTECTION) ? " DIX0" : "",
4074             (prot_mask & SHOST_DIX_TYPE1_PROTECTION) ? " DIX1" : "",
4075             (prot_mask & SHOST_DIX_TYPE2_PROTECTION) ? " DIX2" : "",
4076             (prot_mask & SHOST_DIX_TYPE3_PROTECTION) ? " DIX3" : "");
4077
4078         if (prot_guard_mask)
4079                 scsi_host_set_guard(shost, (prot_guard_mask & 3));
4080         else
4081                 scsi_host_set_guard(shost, SHOST_DIX_GUARD_CRC);
4082
4083         snprintf(mrioc->fwevt_worker_name, sizeof(mrioc->fwevt_worker_name),
4084             "%s%d_fwevt_wrkr", mrioc->driver_name, mrioc->id);
4085         mrioc->fwevt_worker_thread = alloc_ordered_workqueue(
4086             mrioc->fwevt_worker_name, WQ_MEM_RECLAIM);
4087         if (!mrioc->fwevt_worker_thread) {
4088                 ioc_err(mrioc, "failure at %s:%d/%s()!\n",
4089                     __FILE__, __LINE__, __func__);
4090                 retval = -ENODEV;
4091                 goto fwevtthread_failed;
4092         }
4093
4094         mrioc->is_driver_loading = 1;
4095         mrioc->cpu_count = num_online_cpus();
4096         if (mpi3mr_setup_resources(mrioc)) {
4097                 ioc_err(mrioc, "setup resources failed\n");
4098                 retval = -ENODEV;
4099                 goto resource_alloc_failed;
4100         }
4101         if (mpi3mr_init_ioc(mrioc)) {
4102                 ioc_err(mrioc, "initializing IOC failed\n");
4103                 retval = -ENODEV;
4104                 goto init_ioc_failed;
4105         }
4106
4107         shost->nr_hw_queues = mrioc->num_op_reply_q;
4108         shost->can_queue = mrioc->max_host_ios;
4109         shost->sg_tablesize = MPI3MR_SG_DEPTH;
4110         shost->max_id = mrioc->facts.max_perids + 1;
4111
4112         retval = scsi_add_host(shost, &pdev->dev);
4113         if (retval) {
4114                 ioc_err(mrioc, "failure at %s:%d/%s()!\n",
4115                     __FILE__, __LINE__, __func__);
4116                 goto addhost_failed;
4117         }
4118
4119         scsi_scan_host(shost);
4120         return retval;
4121
4122 addhost_failed:
4123         mpi3mr_stop_watchdog(mrioc);
4124         mpi3mr_cleanup_ioc(mrioc);
4125 init_ioc_failed:
4126         mpi3mr_free_mem(mrioc);
4127         mpi3mr_cleanup_resources(mrioc);
4128 resource_alloc_failed:
4129         destroy_workqueue(mrioc->fwevt_worker_thread);
4130 fwevtthread_failed:
4131         spin_lock(&mrioc_list_lock);
4132         list_del(&mrioc->list);
4133         spin_unlock(&mrioc_list_lock);
4134         scsi_host_put(shost);
4135 shost_failed:
4136         return retval;
4137 }
4138
4139 /**
4140  * mpi3mr_remove - PCI remove callback
4141  * @pdev: PCI device instance
4142  *
4143  * Cleanup the IOC by issuing MUR and shutdown notification.
4144  * Free up all memory and resources associated with the
4145  * controllerand target devices, unregister the shost.
4146  *
4147  * Return: Nothing.
4148  */
4149 static void mpi3mr_remove(struct pci_dev *pdev)
4150 {
4151         struct Scsi_Host *shost = pci_get_drvdata(pdev);
4152         struct mpi3mr_ioc *mrioc;
4153         struct workqueue_struct *wq;
4154         unsigned long flags;
4155         struct mpi3mr_tgt_dev *tgtdev, *tgtdev_next;
4156
4157         if (!shost)
4158                 return;
4159
4160         mrioc = shost_priv(shost);
4161         while (mrioc->reset_in_progress || mrioc->is_driver_loading)
4162                 ssleep(1);
4163
4164         mrioc->stop_drv_processing = 1;
4165         mpi3mr_cleanup_fwevt_list(mrioc);
4166         spin_lock_irqsave(&mrioc->fwevt_lock, flags);
4167         wq = mrioc->fwevt_worker_thread;
4168         mrioc->fwevt_worker_thread = NULL;
4169         spin_unlock_irqrestore(&mrioc->fwevt_lock, flags);
4170         if (wq)
4171                 destroy_workqueue(wq);
4172         scsi_remove_host(shost);
4173
4174         list_for_each_entry_safe(tgtdev, tgtdev_next, &mrioc->tgtdev_list,
4175             list) {
4176                 mpi3mr_remove_tgtdev_from_host(mrioc, tgtdev);
4177                 mpi3mr_tgtdev_del_from_list(mrioc, tgtdev);
4178                 mpi3mr_tgtdev_put(tgtdev);
4179         }
4180         mpi3mr_stop_watchdog(mrioc);
4181         mpi3mr_cleanup_ioc(mrioc);
4182         mpi3mr_free_mem(mrioc);
4183         mpi3mr_cleanup_resources(mrioc);
4184
4185         spin_lock(&mrioc_list_lock);
4186         list_del(&mrioc->list);
4187         spin_unlock(&mrioc_list_lock);
4188
4189         scsi_host_put(shost);
4190 }
4191
4192 /**
4193  * mpi3mr_shutdown - PCI shutdown callback
4194  * @pdev: PCI device instance
4195  *
4196  * Free up all memory and resources associated with the
4197  * controller
4198  *
4199  * Return: Nothing.
4200  */
4201 static void mpi3mr_shutdown(struct pci_dev *pdev)
4202 {
4203         struct Scsi_Host *shost = pci_get_drvdata(pdev);
4204         struct mpi3mr_ioc *mrioc;
4205         struct workqueue_struct *wq;
4206         unsigned long flags;
4207
4208         if (!shost)
4209                 return;
4210
4211         mrioc = shost_priv(shost);
4212         while (mrioc->reset_in_progress || mrioc->is_driver_loading)
4213                 ssleep(1);
4214
4215         mrioc->stop_drv_processing = 1;
4216         mpi3mr_cleanup_fwevt_list(mrioc);
4217         spin_lock_irqsave(&mrioc->fwevt_lock, flags);
4218         wq = mrioc->fwevt_worker_thread;
4219         mrioc->fwevt_worker_thread = NULL;
4220         spin_unlock_irqrestore(&mrioc->fwevt_lock, flags);
4221         if (wq)
4222                 destroy_workqueue(wq);
4223
4224         mpi3mr_stop_watchdog(mrioc);
4225         mpi3mr_cleanup_ioc(mrioc);
4226         mpi3mr_cleanup_resources(mrioc);
4227 }
4228
4229 #ifdef CONFIG_PM
4230 /**
4231  * mpi3mr_suspend - PCI power management suspend callback
4232  * @pdev: PCI device instance
4233  * @state: New power state
4234  *
4235  * Change the power state to the given value and cleanup the IOC
4236  * by issuing MUR and shutdown notification
4237  *
4238  * Return: 0 always.
4239  */
4240 static int mpi3mr_suspend(struct pci_dev *pdev, pm_message_t state)
4241 {
4242         struct Scsi_Host *shost = pci_get_drvdata(pdev);
4243         struct mpi3mr_ioc *mrioc;
4244         pci_power_t device_state;
4245
4246         if (!shost)
4247                 return 0;
4248
4249         mrioc = shost_priv(shost);
4250         while (mrioc->reset_in_progress || mrioc->is_driver_loading)
4251                 ssleep(1);
4252         mrioc->stop_drv_processing = 1;
4253         mpi3mr_cleanup_fwevt_list(mrioc);
4254         scsi_block_requests(shost);
4255         mpi3mr_stop_watchdog(mrioc);
4256         mpi3mr_cleanup_ioc(mrioc);
4257
4258         device_state = pci_choose_state(pdev, state);
4259         ioc_info(mrioc, "pdev=0x%p, slot=%s, entering operating state [D%d]\n",
4260             pdev, pci_name(pdev), device_state);
4261         pci_save_state(pdev);
4262         pci_set_power_state(pdev, device_state);
4263         mpi3mr_cleanup_resources(mrioc);
4264
4265         return 0;
4266 }
4267
4268 /**
4269  * mpi3mr_resume - PCI power management resume callback
4270  * @pdev: PCI device instance
4271  *
4272  * Restore the power state to D0 and reinitialize the controller
4273  * and resume I/O operations to the target devices
4274  *
4275  * Return: 0 on success, non-zero on failure
4276  */
4277 static int mpi3mr_resume(struct pci_dev *pdev)
4278 {
4279         struct Scsi_Host *shost = pci_get_drvdata(pdev);
4280         struct mpi3mr_ioc *mrioc;
4281         pci_power_t device_state = pdev->current_state;
4282         int r;
4283
4284         if (!shost)
4285                 return 0;
4286
4287         mrioc = shost_priv(shost);
4288
4289         ioc_info(mrioc, "pdev=0x%p, slot=%s, previous operating state [D%d]\n",
4290             pdev, pci_name(pdev), device_state);
4291         pci_set_power_state(pdev, PCI_D0);
4292         pci_enable_wake(pdev, PCI_D0, 0);
4293         pci_restore_state(pdev);
4294         mrioc->pdev = pdev;
4295         mrioc->cpu_count = num_online_cpus();
4296         r = mpi3mr_setup_resources(mrioc);
4297         if (r) {
4298                 ioc_info(mrioc, "%s: Setup resources failed[%d]\n",
4299                     __func__, r);
4300                 return r;
4301         }
4302
4303         mrioc->stop_drv_processing = 0;
4304         mpi3mr_memset_buffers(mrioc);
4305         r = mpi3mr_reinit_ioc(mrioc, 1);
4306         if (r) {
4307                 ioc_err(mrioc, "resuming controller failed[%d]\n", r);
4308                 return r;
4309         }
4310         scsi_unblock_requests(shost);
4311         mpi3mr_start_watchdog(mrioc);
4312
4313         return 0;
4314 }
4315 #endif
4316
4317 static const struct pci_device_id mpi3mr_pci_id_table[] = {
4318         {
4319                 PCI_DEVICE_SUB(MPI3_MFGPAGE_VENDORID_BROADCOM,
4320                     MPI3_MFGPAGE_DEVID_SAS4116, PCI_ANY_ID, PCI_ANY_ID)
4321         },
4322         { 0 }
4323 };
4324 MODULE_DEVICE_TABLE(pci, mpi3mr_pci_id_table);
4325
4326 static struct pci_driver mpi3mr_pci_driver = {
4327         .name = MPI3MR_DRIVER_NAME,
4328         .id_table = mpi3mr_pci_id_table,
4329         .probe = mpi3mr_probe,
4330         .remove = mpi3mr_remove,
4331         .shutdown = mpi3mr_shutdown,
4332 #ifdef CONFIG_PM
4333         .suspend = mpi3mr_suspend,
4334         .resume = mpi3mr_resume,
4335 #endif
4336 };
4337
4338 static int __init mpi3mr_init(void)
4339 {
4340         int ret_val;
4341
4342         pr_info("Loading %s version %s\n", MPI3MR_DRIVER_NAME,
4343             MPI3MR_DRIVER_VERSION);
4344
4345         ret_val = pci_register_driver(&mpi3mr_pci_driver);
4346
4347         return ret_val;
4348 }
4349
4350 static void __exit mpi3mr_exit(void)
4351 {
4352         if (warn_non_secure_ctlr)
4353                 pr_warn(
4354                     "Unloading %s version %s while managing a non secure controller\n",
4355                     MPI3MR_DRIVER_NAME, MPI3MR_DRIVER_VERSION);
4356         else
4357                 pr_info("Unloading %s version %s\n", MPI3MR_DRIVER_NAME,
4358                     MPI3MR_DRIVER_VERSION);
4359
4360         pci_unregister_driver(&mpi3mr_pci_driver);
4361 }
4362
4363 module_init(mpi3mr_init);
4364 module_exit(mpi3mr_exit);