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