xref: /freebsd/sys/dev/mpi3mr/mpi3mr.c (revision baabb919345f05e9892c4048a1521e5da1403060)
1 /*
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2016-2023, Broadcom Inc. All rights reserved.
5  * Support: <fbsd-storage-driver.pdl@broadcom.com>
6  *
7  * Authors: Sumit Saxena <sumit.saxena@broadcom.com>
8  *	    Chandrakanth Patil <chandrakanth.patil@broadcom.com>
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions are
12  * met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation and/or other
18  *    materials provided with the distribution.
19  * 3. Neither the name of the Broadcom Inc. nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software without
21  *    specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  *
35  * The views and conclusions contained in the software and documentation are
36  * those of the authors and should not be interpreted as representing
37  * official policies,either expressed or implied, of the FreeBSD Project.
38  *
39  * Mail to: Broadcom Inc 1320 Ridder Park Dr, San Jose, CA 95131
40  *
41  * Broadcom Inc. (Broadcom) MPI3MR Adapter FreeBSD
42  */
43 
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/module.h>
49 #include <sys/bus.h>
50 #include <sys/conf.h>
51 #include <sys/malloc.h>
52 #include <sys/sysctl.h>
53 #include <sys/uio.h>
54 
55 #include <machine/bus.h>
56 #include <machine/resource.h>
57 #include <sys/rman.h>
58 
59 #include <dev/pci/pcireg.h>
60 #include <dev/pci/pcivar.h>
61 #include <dev/pci/pci_private.h>
62 
63 #include <cam/cam.h>
64 #include <cam/cam_ccb.h>
65 #include <cam/cam_debug.h>
66 #include <cam/cam_sim.h>
67 #include <cam/cam_xpt_sim.h>
68 #include <cam/cam_xpt_periph.h>
69 #include <cam/cam_periph.h>
70 #include <cam/scsi/scsi_all.h>
71 #include <cam/scsi/scsi_message.h>
72 #include <cam/scsi/smp_all.h>
73 #include <sys/queue.h>
74 #include <sys/kthread.h>
75 #include "mpi3mr.h"
76 #include "mpi3mr_cam.h"
77 #include "mpi3mr_app.h"
78 
79 static void mpi3mr_repost_reply_buf(struct mpi3mr_softc *sc,
80 	U64 reply_dma);
81 static int mpi3mr_complete_admin_cmd(struct mpi3mr_softc *sc);
82 static void mpi3mr_port_enable_complete(struct mpi3mr_softc *sc,
83 	struct mpi3mr_drvr_cmd *drvrcmd);
84 static void mpi3mr_flush_io(struct mpi3mr_softc *sc);
85 static int mpi3mr_issue_reset(struct mpi3mr_softc *sc, U16 reset_type,
86 	U16 reset_reason);
87 static void mpi3mr_dev_rmhs_send_tm(struct mpi3mr_softc *sc, U16 handle,
88 	struct mpi3mr_drvr_cmd *cmdparam, U8 iou_rc);
89 static void mpi3mr_dev_rmhs_complete_iou(struct mpi3mr_softc *sc,
90 	struct mpi3mr_drvr_cmd *drv_cmd);
91 static void mpi3mr_dev_rmhs_complete_tm(struct mpi3mr_softc *sc,
92 	struct mpi3mr_drvr_cmd *drv_cmd);
93 static void mpi3mr_send_evt_ack(struct mpi3mr_softc *sc, U8 event,
94 	struct mpi3mr_drvr_cmd *cmdparam, U32 event_ctx);
95 static void mpi3mr_print_fault_info(struct mpi3mr_softc *sc);
96 static inline void mpi3mr_set_diagsave(struct mpi3mr_softc *sc);
97 static const char *mpi3mr_reset_rc_name(enum mpi3mr_reset_reason reason_code);
98 
99 void
100 mpi3mr_hexdump(void *buf, int sz, int format)
101 {
102         int i;
103         U32 *buf_loc = (U32 *)buf;
104 
105         for (i = 0; i < (sz / sizeof(U32)); i++) {
106                 if ((i % format) == 0) {
107                         if (i != 0)
108                                 printf("\n");
109                         printf("%08x: ", (i * 4));
110                 }
111                 printf("%08x ", buf_loc[i]);
112         }
113         printf("\n");
114 }
115 
116 void
117 init_completion(struct completion *completion)
118 {
119 	completion->done = 0;
120 }
121 
122 void
123 complete(struct completion *completion)
124 {
125 	completion->done = 1;
126 	wakeup(complete);
127 }
128 
129 void wait_for_completion_timeout(struct completion *completion,
130 	    U32 timeout)
131 {
132 	U32 count = timeout * 1000;
133 
134 	while ((completion->done == 0) && count) {
135                 DELAY(1000);
136 		count--;
137 	}
138 
139 	if (completion->done == 0) {
140 		printf("%s: Command is timedout\n", __func__);
141 		completion->done = 1;
142 	}
143 }
144 void wait_for_completion_timeout_tm(struct completion *completion,
145 	    U32 timeout, struct mpi3mr_softc *sc)
146 {
147 	U32 count = timeout * 1000;
148 
149 	while ((completion->done == 0) && count) {
150 		msleep(&sc->tm_chan, &sc->mpi3mr_mtx, PRIBIO,
151 		       "TM command", 1 * hz);
152 		count--;
153 	}
154 
155 	if (completion->done == 0) {
156 		printf("%s: Command is timedout\n", __func__);
157 		completion->done = 1;
158 	}
159 }
160 
161 
162 void
163 poll_for_command_completion(struct mpi3mr_softc *sc,
164        struct mpi3mr_drvr_cmd *cmd, U16 wait)
165 {
166 	int wait_time = wait * 1000;
167        while (wait_time) {
168                mpi3mr_complete_admin_cmd(sc);
169                if (cmd->state & MPI3MR_CMD_COMPLETE)
170                        break;
171 	       DELAY(1000);
172                wait_time--;
173        }
174 }
175 
176 /**
177  * mpi3mr_trigger_snapdump - triggers firmware snapdump
178  * @sc: Adapter instance reference
179  * @reason_code: reason code for the fault.
180  *
181  * This routine will trigger the snapdump and wait for it to
182  * complete or timeout before it returns.
183  * This will be called during initilaization time faults/resets/timeouts
184  * before soft reset invocation.
185  *
186  * Return:  None.
187  */
188 static void
189 mpi3mr_trigger_snapdump(struct mpi3mr_softc *sc, U16 reason_code)
190 {
191 	U32 host_diagnostic, timeout = MPI3_SYSIF_DIAG_SAVE_TIMEOUT * 10;
192 
193 	mpi3mr_dprint(sc, MPI3MR_INFO, "snapdump triggered: reason code: %s\n",
194 	    mpi3mr_reset_rc_name(reason_code));
195 
196 	mpi3mr_set_diagsave(sc);
197 	mpi3mr_issue_reset(sc, MPI3_SYSIF_HOST_DIAG_RESET_ACTION_DIAG_FAULT,
198 			   reason_code);
199 
200 	do {
201 		host_diagnostic = mpi3mr_regread(sc, MPI3_SYSIF_HOST_DIAG_OFFSET);
202 		if (!(host_diagnostic & MPI3_SYSIF_HOST_DIAG_SAVE_IN_PROGRESS))
203 			break;
204                 DELAY(100 * 1000);
205 	} while (--timeout);
206 
207 	return;
208 }
209 
210 /**
211  * mpi3mr_check_rh_fault_ioc - check reset history and fault
212  * controller
213  * @sc: Adapter instance reference
214  * @reason_code, reason code for the fault.
215  *
216  * This routine will fault the controller with
217  * the given reason code if it is not already in the fault or
218  * not asynchronosuly reset. This will be used to handle
219  * initilaization time faults/resets/timeout as in those cases
220  * immediate soft reset invocation is not required.
221  *
222  * Return:  None.
223  */
224 static void mpi3mr_check_rh_fault_ioc(struct mpi3mr_softc *sc, U16 reason_code)
225 {
226 	U32 ioc_status;
227 
228 	if (sc->unrecoverable) {
229 		mpi3mr_dprint(sc, MPI3MR_ERROR, "controller is unrecoverable\n");
230 		return;
231 	}
232 
233 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
234 	if ((ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY) ||
235 	    (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT)) {
236 		mpi3mr_print_fault_info(sc);
237 		return;
238 	}
239 
240 	mpi3mr_trigger_snapdump(sc, reason_code);
241 
242 	return;
243 }
244 
245 static void * mpi3mr_get_reply_virt_addr(struct mpi3mr_softc *sc,
246     bus_addr_t phys_addr)
247 {
248 	if (!phys_addr)
249 		return NULL;
250 	if ((phys_addr < sc->reply_buf_dma_min_address) ||
251 	    (phys_addr > sc->reply_buf_dma_max_address))
252 		return NULL;
253 
254 	return sc->reply_buf + (phys_addr - sc->reply_buf_phys);
255 }
256 
257 static void * mpi3mr_get_sensebuf_virt_addr(struct mpi3mr_softc *sc,
258     bus_addr_t phys_addr)
259 {
260 	if (!phys_addr)
261 		return NULL;
262 	return sc->sense_buf + (phys_addr - sc->sense_buf_phys);
263 }
264 
265 static void mpi3mr_repost_reply_buf(struct mpi3mr_softc *sc,
266     U64 reply_dma)
267 {
268 	U32 old_idx = 0;
269 
270 	mtx_lock_spin(&sc->reply_free_q_lock);
271 	old_idx  =  sc->reply_free_q_host_index;
272 	sc->reply_free_q_host_index = ((sc->reply_free_q_host_index ==
273 	    (sc->reply_free_q_sz - 1)) ? 0 :
274 	    (sc->reply_free_q_host_index + 1));
275 	sc->reply_free_q[old_idx] = reply_dma;
276 	mpi3mr_regwrite(sc, MPI3_SYSIF_REPLY_FREE_HOST_INDEX_OFFSET,
277 		sc->reply_free_q_host_index);
278 	mtx_unlock_spin(&sc->reply_free_q_lock);
279 }
280 
281 static void mpi3mr_repost_sense_buf(struct mpi3mr_softc *sc,
282     U64 sense_buf_phys)
283 {
284 	U32 old_idx = 0;
285 
286 	mtx_lock_spin(&sc->sense_buf_q_lock);
287 	old_idx  =  sc->sense_buf_q_host_index;
288 	sc->sense_buf_q_host_index = ((sc->sense_buf_q_host_index ==
289 	    (sc->sense_buf_q_sz - 1)) ? 0 :
290 	    (sc->sense_buf_q_host_index + 1));
291 	sc->sense_buf_q[old_idx] = sense_buf_phys;
292 	mpi3mr_regwrite(sc, MPI3_SYSIF_SENSE_BUF_FREE_HOST_INDEX_OFFSET,
293 		sc->sense_buf_q_host_index);
294 	mtx_unlock_spin(&sc->sense_buf_q_lock);
295 
296 }
297 
298 void mpi3mr_set_io_divert_for_all_vd_in_tg(struct mpi3mr_softc *sc,
299 	struct mpi3mr_throttle_group_info *tg, U8 divert_value)
300 {
301 	struct mpi3mr_target *target;
302 
303 	mtx_lock_spin(&sc->target_lock);
304 	TAILQ_FOREACH(target, &sc->cam_sc->tgt_list, tgt_next) {
305 		if (target->throttle_group == tg)
306 			target->io_divert = divert_value;
307 	}
308 	mtx_unlock_spin(&sc->target_lock);
309 }
310 
311 /**
312  * mpi3mr_submit_admin_cmd - Submit request to admin queue
313  * @mrioc: Adapter reference
314  * @admin_req: MPI3 request
315  * @admin_req_sz: Request size
316  *
317  * Post the MPI3 request into admin request queue and
318  * inform the controller, if the queue is full return
319  * appropriate error.
320  *
321  * Return: 0 on success, non-zero on failure.
322  */
323 int mpi3mr_submit_admin_cmd(struct mpi3mr_softc *sc, void *admin_req,
324     U16 admin_req_sz)
325 {
326 	U16 areq_pi = 0, areq_ci = 0, max_entries = 0;
327 	int retval = 0;
328 	U8 *areq_entry;
329 
330 	mtx_lock_spin(&sc->admin_req_lock);
331 	areq_pi = sc->admin_req_pi;
332 	areq_ci = sc->admin_req_ci;
333 	max_entries = sc->num_admin_reqs;
334 
335 	if (sc->unrecoverable)
336 		return -EFAULT;
337 
338 	if ((areq_ci == (areq_pi + 1)) || ((!areq_ci) &&
339 					   (areq_pi == (max_entries - 1)))) {
340 		printf(IOCNAME "AdminReqQ full condition detected\n",
341 		    sc->name);
342 		retval = -EAGAIN;
343 		goto out;
344 	}
345 	areq_entry = (U8 *)sc->admin_req + (areq_pi *
346 						     MPI3MR_AREQ_FRAME_SZ);
347 	memset(areq_entry, 0, MPI3MR_AREQ_FRAME_SZ);
348 	memcpy(areq_entry, (U8 *)admin_req, admin_req_sz);
349 
350 	if (++areq_pi == max_entries)
351 		areq_pi = 0;
352 	sc->admin_req_pi = areq_pi;
353 
354 	mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_REQ_Q_PI_OFFSET, sc->admin_req_pi);
355 
356 out:
357 	mtx_unlock_spin(&sc->admin_req_lock);
358 	return retval;
359 }
360 
361 /**
362  * mpi3mr_check_req_qfull - Check request queue is full or not
363  * @op_req_q: Operational reply queue info
364  *
365  * Return: true when queue full, false otherwise.
366  */
367 static inline bool
368 mpi3mr_check_req_qfull(struct mpi3mr_op_req_queue *op_req_q)
369 {
370 	U16 pi, ci, max_entries;
371 	bool is_qfull = false;
372 
373 	pi = op_req_q->pi;
374 	ci = op_req_q->ci;
375 	max_entries = op_req_q->num_reqs;
376 
377 	if ((ci == (pi + 1)) || ((!ci) && (pi == (max_entries - 1))))
378 		is_qfull = true;
379 
380 	return is_qfull;
381 }
382 
383 /**
384  * mpi3mr_submit_io - Post IO command to firmware
385  * @sc:		      Adapter instance reference
386  * @op_req_q:	      Operational Request queue reference
387  * @req:	      MPT request data
388  *
389  * This function submits IO command to firmware.
390  *
391  * Return: Nothing
392  */
393 int mpi3mr_submit_io(struct mpi3mr_softc *sc,
394     struct mpi3mr_op_req_queue *op_req_q, U8 *req)
395 {
396 	U16 pi, max_entries;
397 	int retval = 0;
398 	U8 *req_entry;
399 	U16 req_sz = sc->facts.op_req_sz;
400 	struct mpi3mr_irq_context *irq_ctx;
401 
402 	mtx_lock_spin(&op_req_q->q_lock);
403 
404 	pi = op_req_q->pi;
405 	max_entries = op_req_q->num_reqs;
406 	if (mpi3mr_check_req_qfull(op_req_q)) {
407 		irq_ctx = &sc->irq_ctx[op_req_q->reply_qid - 1];
408 		mpi3mr_complete_io_cmd(sc, irq_ctx);
409 
410 		if (mpi3mr_check_req_qfull(op_req_q)) {
411 			printf(IOCNAME "OpReqQ full condition detected\n",
412 				sc->name);
413 			retval = -EBUSY;
414 			goto out;
415 		}
416 	}
417 
418 	req_entry = (U8 *)op_req_q->q_base + (pi * req_sz);
419 	memset(req_entry, 0, req_sz);
420 	memcpy(req_entry, req, MPI3MR_AREQ_FRAME_SZ);
421 	if (++pi == max_entries)
422 		pi = 0;
423 	op_req_q->pi = pi;
424 
425 	mpi3mr_atomic_inc(&sc->op_reply_q[op_req_q->reply_qid - 1].pend_ios);
426 
427 	mpi3mr_regwrite(sc, MPI3_SYSIF_OPER_REQ_Q_N_PI_OFFSET(op_req_q->qid), op_req_q->pi);
428 	if (sc->mpi3mr_debug & MPI3MR_TRACE) {
429 		device_printf(sc->mpi3mr_dev, "IO submission: QID:%d PI:0x%x\n", op_req_q->qid, op_req_q->pi);
430 		mpi3mr_hexdump(req_entry, MPI3MR_AREQ_FRAME_SZ, 8);
431 	}
432 
433 out:
434 	mtx_unlock_spin(&op_req_q->q_lock);
435 	return retval;
436 }
437 
438 inline void
439 mpi3mr_add_sg_single(void *paddr, U8 flags, U32 length,
440 		     bus_addr_t dma_addr)
441 {
442 	Mpi3SGESimple_t *sgel = paddr;
443 
444 	sgel->Flags = flags;
445 	sgel->Length = (length);
446 	sgel->Address = (U64)dma_addr;
447 }
448 
449 void mpi3mr_build_zero_len_sge(void *paddr)
450 {
451 	U8 sgl_flags = (MPI3_SGE_FLAGS_ELEMENT_TYPE_SIMPLE |
452 		MPI3_SGE_FLAGS_DLAS_SYSTEM | MPI3_SGE_FLAGS_END_OF_LIST);
453 
454 	mpi3mr_add_sg_single(paddr, sgl_flags, 0, -1);
455 
456 }
457 
458 void mpi3mr_enable_interrupts(struct mpi3mr_softc *sc)
459 {
460 	sc->intr_enabled = 1;
461 }
462 
463 void mpi3mr_disable_interrupts(struct mpi3mr_softc *sc)
464 {
465 	sc->intr_enabled = 0;
466 }
467 
468 void
469 mpi3mr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
470 {
471 	bus_addr_t *addr;
472 
473 	addr = arg;
474 	*addr = segs[0].ds_addr;
475 }
476 
477 static int mpi3mr_delete_op_reply_queue(struct mpi3mr_softc *sc, U16 qid)
478 {
479 	Mpi3DeleteReplyQueueRequest_t delq_req;
480 	struct mpi3mr_op_reply_queue *op_reply_q;
481 	int retval = 0;
482 
483 
484 	op_reply_q = &sc->op_reply_q[qid - 1];
485 
486 	if (!op_reply_q->qid)
487 	{
488 		retval = -1;
489 		printf(IOCNAME "Issue DelRepQ: called with invalid Reply QID\n",
490 		    sc->name);
491 		goto out;
492 	}
493 
494 	memset(&delq_req, 0, sizeof(delq_req));
495 
496 	mtx_lock(&sc->init_cmds.completion.lock);
497 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
498 		retval = -1;
499 		printf(IOCNAME "Issue DelRepQ: Init command is in use\n",
500 		    sc->name);
501 		mtx_unlock(&sc->init_cmds.completion.lock);
502 		goto out;
503 	}
504 
505 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
506 		retval = -1;
507 		printf(IOCNAME "Issue DelRepQ: Init command is in use\n",
508 		    sc->name);
509 		goto out;
510 	}
511 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
512 	sc->init_cmds.is_waiting = 1;
513 	sc->init_cmds.callback = NULL;
514 	delq_req.HostTag = MPI3MR_HOSTTAG_INITCMDS;
515 	delq_req.Function = MPI3_FUNCTION_DELETE_REPLY_QUEUE;
516 	delq_req.QueueID = qid;
517 
518 	init_completion(&sc->init_cmds.completion);
519 	retval = mpi3mr_submit_admin_cmd(sc, &delq_req, sizeof(delq_req));
520 	if (retval) {
521 		printf(IOCNAME "Issue DelRepQ: Admin Post failed\n",
522 		    sc->name);
523 		goto out_unlock;
524 	}
525 	wait_for_completion_timeout(&sc->init_cmds.completion,
526 	    (MPI3MR_INTADMCMD_TIMEOUT));
527 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
528 		printf(IOCNAME "Issue DelRepQ: command timed out\n",
529 		    sc->name);
530 		mpi3mr_check_rh_fault_ioc(sc,
531 		    MPI3MR_RESET_FROM_DELREPQ_TIMEOUT);
532 		sc->unrecoverable = 1;
533 
534 		retval = -1;
535 		goto out_unlock;
536 	}
537 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
538 	     != MPI3_IOCSTATUS_SUCCESS ) {
539 		printf(IOCNAME "Issue DelRepQ: Failed IOCStatus(0x%04x) "
540 		    " Loginfo(0x%08x) \n" , sc->name,
541 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
542 		    sc->init_cmds.ioc_loginfo);
543 		retval = -1;
544 		goto out_unlock;
545 	}
546 	sc->irq_ctx[qid - 1].op_reply_q = NULL;
547 
548 	if (sc->op_reply_q[qid - 1].q_base_phys != 0)
549 		bus_dmamap_unload(sc->op_reply_q[qid - 1].q_base_tag, sc->op_reply_q[qid - 1].q_base_dmamap);
550 	if (sc->op_reply_q[qid - 1].q_base != NULL)
551 		bus_dmamem_free(sc->op_reply_q[qid - 1].q_base_tag, sc->op_reply_q[qid - 1].q_base, sc->op_reply_q[qid - 1].q_base_dmamap);
552 	if (sc->op_reply_q[qid - 1].q_base_tag != NULL)
553 		bus_dma_tag_destroy(sc->op_reply_q[qid - 1].q_base_tag);
554 
555 	sc->op_reply_q[qid - 1].q_base = NULL;
556 	sc->op_reply_q[qid - 1].qid = 0;
557 out_unlock:
558 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
559 	mtx_unlock(&sc->init_cmds.completion.lock);
560 out:
561 	return retval;
562 }
563 
564 /**
565  * mpi3mr_create_op_reply_queue - create operational reply queue
566  * @sc: Adapter instance reference
567  * @qid: operational reply queue id
568  *
569  * Create operatinal reply queue by issuing MPI request
570  * through admin queue.
571  *
572  * Return:  0 on success, non-zero on failure.
573  */
574 static int mpi3mr_create_op_reply_queue(struct mpi3mr_softc *sc, U16 qid)
575 {
576 	Mpi3CreateReplyQueueRequest_t create_req;
577 	struct mpi3mr_op_reply_queue *op_reply_q;
578 	int retval = 0;
579 	char q_lock_name[32];
580 
581 	op_reply_q = &sc->op_reply_q[qid - 1];
582 
583 	if (op_reply_q->qid)
584 	{
585 		retval = -1;
586 		printf(IOCNAME "CreateRepQ: called for duplicate qid %d\n",
587 		    sc->name, op_reply_q->qid);
588 		return retval;
589 	}
590 
591 	op_reply_q->ci = 0;
592 	if (pci_get_revid(sc->mpi3mr_dev) == SAS4116_CHIP_REV_A0)
593 		op_reply_q->num_replies = MPI3MR_OP_REP_Q_QD_A0;
594 	else
595 		op_reply_q->num_replies = MPI3MR_OP_REP_Q_QD;
596 
597 	op_reply_q->qsz = op_reply_q->num_replies * sc->op_reply_sz;
598 	op_reply_q->ephase = 1;
599 
600         if (!op_reply_q->q_base) {
601 		snprintf(q_lock_name, 32, "Reply Queue Lock[%d]", qid);
602 		mtx_init(&op_reply_q->q_lock, q_lock_name, NULL, MTX_SPIN);
603 
604 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
605 					4, 0,			/* algnmnt, boundary */
606 					sc->dma_loaddr,		/* lowaddr */
607 					BUS_SPACE_MAXADDR,	/* highaddr */
608 					NULL, NULL,		/* filter, filterarg */
609 					op_reply_q->qsz,		/* maxsize */
610 					1,			/* nsegments */
611 					op_reply_q->qsz,		/* maxsegsize */
612 					0,			/* flags */
613 					NULL, NULL,		/* lockfunc, lockarg */
614 					&op_reply_q->q_base_tag)) {
615 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate Operational reply DMA tag\n");
616 			return (ENOMEM);
617 		}
618 
619 		if (bus_dmamem_alloc(op_reply_q->q_base_tag, (void **)&op_reply_q->q_base,
620 		    BUS_DMA_NOWAIT, &op_reply_q->q_base_dmamap)) {
621 			mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
622 			return (ENOMEM);
623 		}
624 		bzero(op_reply_q->q_base, op_reply_q->qsz);
625 		bus_dmamap_load(op_reply_q->q_base_tag, op_reply_q->q_base_dmamap, op_reply_q->q_base, op_reply_q->qsz,
626 		    mpi3mr_memaddr_cb, &op_reply_q->q_base_phys, BUS_DMA_NOWAIT);
627 		mpi3mr_dprint(sc, MPI3MR_XINFO, "Operational Reply queue ID: %d phys addr= %#016jx virt_addr: %pa size= %d\n",
628 		    qid, (uintmax_t)op_reply_q->q_base_phys, op_reply_q->q_base, op_reply_q->qsz);
629 
630 		if (!op_reply_q->q_base)
631 		{
632 			retval = -1;
633 			printf(IOCNAME "CreateRepQ: memory alloc failed for qid %d\n",
634 			    sc->name, qid);
635 			goto out;
636 		}
637 	}
638 
639 	memset(&create_req, 0, sizeof(create_req));
640 
641 	mtx_lock(&sc->init_cmds.completion.lock);
642 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
643 		retval = -1;
644 		printf(IOCNAME "CreateRepQ: Init command is in use\n",
645 		    sc->name);
646 		mtx_unlock(&sc->init_cmds.completion.lock);
647 		goto out;
648 	}
649 
650 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
651 	sc->init_cmds.is_waiting = 1;
652 	sc->init_cmds.callback = NULL;
653 	create_req.HostTag = MPI3MR_HOSTTAG_INITCMDS;
654 	create_req.Function = MPI3_FUNCTION_CREATE_REPLY_QUEUE;
655 	create_req.QueueID = qid;
656 	create_req.Flags = MPI3_CREATE_REPLY_QUEUE_FLAGS_INT_ENABLE_ENABLE;
657 	create_req.MSIxIndex = sc->irq_ctx[qid - 1].msix_index;
658 	create_req.BaseAddress = (U64)op_reply_q->q_base_phys;
659 	create_req.Size = op_reply_q->num_replies;
660 
661 	init_completion(&sc->init_cmds.completion);
662 	retval = mpi3mr_submit_admin_cmd(sc, &create_req,
663 	    sizeof(create_req));
664 	if (retval) {
665 		printf(IOCNAME "CreateRepQ: Admin Post failed\n",
666 		    sc->name);
667 		goto out_unlock;
668 	}
669 
670 	wait_for_completion_timeout(&sc->init_cmds.completion,
671 	  	MPI3MR_INTADMCMD_TIMEOUT);
672 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
673 		printf(IOCNAME "CreateRepQ: command timed out\n",
674 		    sc->name);
675 		mpi3mr_check_rh_fault_ioc(sc,
676 		    MPI3MR_RESET_FROM_CREATEREPQ_TIMEOUT);
677 		sc->unrecoverable = 1;
678 		retval = -1;
679 		goto out_unlock;
680 	}
681 
682 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
683 	     != MPI3_IOCSTATUS_SUCCESS ) {
684 		printf(IOCNAME "CreateRepQ: Failed IOCStatus(0x%04x) "
685 		    " Loginfo(0x%08x) \n" , sc->name,
686 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
687 		    sc->init_cmds.ioc_loginfo);
688 		retval = -1;
689 		goto out_unlock;
690 	}
691 	op_reply_q->qid = qid;
692 	sc->irq_ctx[qid - 1].op_reply_q = op_reply_q;
693 
694 out_unlock:
695 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
696 	mtx_unlock(&sc->init_cmds.completion.lock);
697 out:
698 	if (retval) {
699 		if (op_reply_q->q_base_phys != 0)
700 			bus_dmamap_unload(op_reply_q->q_base_tag, op_reply_q->q_base_dmamap);
701 		if (op_reply_q->q_base != NULL)
702 			bus_dmamem_free(op_reply_q->q_base_tag, op_reply_q->q_base, op_reply_q->q_base_dmamap);
703 		if (op_reply_q->q_base_tag != NULL)
704 			bus_dma_tag_destroy(op_reply_q->q_base_tag);
705 		op_reply_q->q_base = NULL;
706 		op_reply_q->qid = 0;
707 	}
708 
709 	return retval;
710 }
711 
712 /**
713  * mpi3mr_create_op_req_queue - create operational request queue
714  * @sc: Adapter instance reference
715  * @req_qid: operational request queue id
716  * @reply_qid: Reply queue ID
717  *
718  * Create operatinal request queue by issuing MPI request
719  * through admin queue.
720  *
721  * Return:  0 on success, non-zero on failure.
722  */
723 static int mpi3mr_create_op_req_queue(struct mpi3mr_softc *sc, U16 req_qid, U8 reply_qid)
724 {
725 	Mpi3CreateRequestQueueRequest_t create_req;
726 	struct mpi3mr_op_req_queue *op_req_q;
727 	int retval = 0;
728 	char q_lock_name[32];
729 
730 	op_req_q = &sc->op_req_q[req_qid - 1];
731 
732 	if (op_req_q->qid)
733 	{
734 		retval = -1;
735 		printf(IOCNAME "CreateReqQ: called for duplicate qid %d\n",
736 		    sc->name, op_req_q->qid);
737 		return retval;
738 	}
739 
740 	op_req_q->ci = 0;
741 	op_req_q->pi = 0;
742 	op_req_q->num_reqs = MPI3MR_OP_REQ_Q_QD;
743 	op_req_q->qsz = op_req_q->num_reqs * sc->facts.op_req_sz;
744 	op_req_q->reply_qid = reply_qid;
745 
746 	if (!op_req_q->q_base) {
747 		snprintf(q_lock_name, 32, "Request Queue Lock[%d]", req_qid);
748 		mtx_init(&op_req_q->q_lock, q_lock_name, NULL, MTX_SPIN);
749 
750 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
751 					4, 0,			/* algnmnt, boundary */
752 					sc->dma_loaddr,		/* lowaddr */
753 					BUS_SPACE_MAXADDR,	/* highaddr */
754 					NULL, NULL,		/* filter, filterarg */
755 					op_req_q->qsz,		/* maxsize */
756 					1,			/* nsegments */
757 					op_req_q->qsz,		/* maxsegsize */
758 					0,			/* flags */
759 					NULL, NULL,		/* lockfunc, lockarg */
760 					&op_req_q->q_base_tag)) {
761 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
762 			return (ENOMEM);
763 		}
764 
765 		if (bus_dmamem_alloc(op_req_q->q_base_tag, (void **)&op_req_q->q_base,
766 		    BUS_DMA_NOWAIT, &op_req_q->q_base_dmamap)) {
767 			mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
768 			return (ENOMEM);
769 		}
770 
771 		bzero(op_req_q->q_base, op_req_q->qsz);
772 
773 		bus_dmamap_load(op_req_q->q_base_tag, op_req_q->q_base_dmamap, op_req_q->q_base, op_req_q->qsz,
774 		    mpi3mr_memaddr_cb, &op_req_q->q_base_phys, BUS_DMA_NOWAIT);
775 
776 		mpi3mr_dprint(sc, MPI3MR_XINFO, "Operational Request QID: %d phys addr= %#016jx virt addr= %pa size= %d associated Reply QID: %d\n",
777 		    req_qid, (uintmax_t)op_req_q->q_base_phys, op_req_q->q_base, op_req_q->qsz, reply_qid);
778 
779 		if (!op_req_q->q_base) {
780 			retval = -1;
781 			printf(IOCNAME "CreateReqQ: memory alloc failed for qid %d\n",
782 			    sc->name, req_qid);
783 			goto out;
784 		}
785 	}
786 
787 	memset(&create_req, 0, sizeof(create_req));
788 
789 	mtx_lock(&sc->init_cmds.completion.lock);
790 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
791 		retval = -1;
792 		printf(IOCNAME "CreateReqQ: Init command is in use\n",
793 		    sc->name);
794 		mtx_unlock(&sc->init_cmds.completion.lock);
795 		goto out;
796 	}
797 
798 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
799 	sc->init_cmds.is_waiting = 1;
800 	sc->init_cmds.callback = NULL;
801 	create_req.HostTag = MPI3MR_HOSTTAG_INITCMDS;
802 	create_req.Function = MPI3_FUNCTION_CREATE_REQUEST_QUEUE;
803 	create_req.QueueID = req_qid;
804 	create_req.Flags = 0;
805 	create_req.ReplyQueueID = reply_qid;
806 	create_req.BaseAddress = (U64)op_req_q->q_base_phys;
807 	create_req.Size = op_req_q->num_reqs;
808 
809 	init_completion(&sc->init_cmds.completion);
810 	retval = mpi3mr_submit_admin_cmd(sc, &create_req,
811 	    sizeof(create_req));
812 	if (retval) {
813 		printf(IOCNAME "CreateReqQ: Admin Post failed\n",
814 		    sc->name);
815 		goto out_unlock;
816 	}
817 
818 	wait_for_completion_timeout(&sc->init_cmds.completion,
819 	    (MPI3MR_INTADMCMD_TIMEOUT));
820 
821 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
822 		printf(IOCNAME "CreateReqQ: command timed out\n",
823 		    sc->name);
824 		mpi3mr_check_rh_fault_ioc(sc,
825 			MPI3MR_RESET_FROM_CREATEREQQ_TIMEOUT);
826 		sc->unrecoverable = 1;
827 		retval = -1;
828 		goto out_unlock;
829 	}
830 
831 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
832 	     != MPI3_IOCSTATUS_SUCCESS ) {
833 		printf(IOCNAME "CreateReqQ: Failed IOCStatus(0x%04x) "
834 		    " Loginfo(0x%08x) \n" , sc->name,
835 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
836 		    sc->init_cmds.ioc_loginfo);
837 		retval = -1;
838 		goto out_unlock;
839 	}
840 	op_req_q->qid = req_qid;
841 
842 out_unlock:
843 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
844 	mtx_unlock(&sc->init_cmds.completion.lock);
845 out:
846 	if (retval) {
847 		if (op_req_q->q_base_phys != 0)
848 			bus_dmamap_unload(op_req_q->q_base_tag, op_req_q->q_base_dmamap);
849 		if (op_req_q->q_base != NULL)
850 			bus_dmamem_free(op_req_q->q_base_tag, op_req_q->q_base, op_req_q->q_base_dmamap);
851 		if (op_req_q->q_base_tag != NULL)
852 			bus_dma_tag_destroy(op_req_q->q_base_tag);
853 		op_req_q->q_base = NULL;
854 		op_req_q->qid = 0;
855 	}
856 	return retval;
857 }
858 
859 /**
860  * mpi3mr_create_op_queues - create operational queues
861  * @sc: Adapter instance reference
862  *
863  * Create operatinal queues(request queues and reply queues).
864  * Return:  0 on success, non-zero on failure.
865  */
866 static int mpi3mr_create_op_queues(struct mpi3mr_softc *sc)
867 {
868 	int retval = 0;
869 	U16 num_queues = 0, i = 0, qid;
870 
871 	num_queues = min(sc->facts.max_op_reply_q,
872 	    sc->facts.max_op_req_q);
873 	num_queues = min(num_queues, sc->msix_count);
874 
875 	/*
876 	 * During reset set the num_queues to the number of queues
877 	 * that was set before the reset.
878 	 */
879 	if (sc->num_queues)
880 		num_queues = sc->num_queues;
881 
882 	mpi3mr_dprint(sc, MPI3MR_XINFO, "Trying to create %d Operational Q pairs\n",
883 	    num_queues);
884 
885 	if (!sc->op_req_q) {
886 		sc->op_req_q = malloc(sizeof(struct mpi3mr_op_req_queue) *
887 		    num_queues, M_MPI3MR, M_NOWAIT | M_ZERO);
888 
889 		if (!sc->op_req_q) {
890 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to alloc memory for Request queue info\n");
891 			retval = -1;
892 			goto out_failed;
893 		}
894 	}
895 
896 	if (!sc->op_reply_q) {
897 		sc->op_reply_q = malloc(sizeof(struct mpi3mr_op_reply_queue) * num_queues,
898 			M_MPI3MR, M_NOWAIT | M_ZERO);
899 
900 		if (!sc->op_reply_q) {
901 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to alloc memory for Reply queue info\n");
902 			retval = -1;
903 			goto out_failed;
904 		}
905 	}
906 
907 	sc->num_hosttag_op_req_q = (sc->max_host_ios + 1) / num_queues;
908 
909 	/*Operational Request and reply queue ID starts with 1*/
910 	for (i = 0; i < num_queues; i++) {
911 		qid = i + 1;
912 		if (mpi3mr_create_op_reply_queue(sc, qid)) {
913 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to create Reply queue %d\n",
914 			    qid);
915 			break;
916 		}
917 		if (mpi3mr_create_op_req_queue(sc, qid,
918 		    sc->op_reply_q[qid - 1].qid)) {
919 			mpi3mr_delete_op_reply_queue(sc, qid);
920 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to create Request queue %d\n",
921 			    qid);
922 			break;
923 		}
924 
925 	}
926 
927 	/* Not even one queue is created successfully*/
928         if (i == 0) {
929                 retval = -1;
930                 goto out_failed;
931         }
932 
933 	if (!sc->num_queues) {
934 		sc->num_queues = i;
935 	} else {
936 		if (num_queues != i) {
937 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Number of queues (%d) post reset are not same as"
938 					"queues allocated (%d) during driver init\n", i, num_queues);
939 			goto out_failed;
940 		}
941 	}
942 
943 	mpi3mr_dprint(sc, MPI3MR_INFO, "Successfully created %d Operational Queue pairs\n",
944 	    sc->num_queues);
945 	mpi3mr_dprint(sc, MPI3MR_INFO, "Request Queue QD: %d Reply queue QD: %d\n",
946 	    sc->op_req_q[0].num_reqs, sc->op_reply_q[0].num_replies);
947 
948 	return retval;
949 out_failed:
950 	if (sc->op_req_q) {
951 		free(sc->op_req_q, M_MPI3MR);
952 		sc->op_req_q = NULL;
953 	}
954 	if (sc->op_reply_q) {
955 		free(sc->op_reply_q, M_MPI3MR);
956 		sc->op_reply_q = NULL;
957 	}
958 	return retval;
959 }
960 
961 /**
962  * mpi3mr_setup_admin_qpair - Setup admin queue pairs
963  * @sc: Adapter instance reference
964  *
965  * Allocation and setup admin queues(request queues and reply queues).
966  * Return:  0 on success, non-zero on failure.
967  */
968 static int mpi3mr_setup_admin_qpair(struct mpi3mr_softc *sc)
969 {
970 	int retval = 0;
971 	U32 num_adm_entries = 0;
972 
973 	sc->admin_req_q_sz = MPI3MR_AREQQ_SIZE;
974 	sc->num_admin_reqs = sc->admin_req_q_sz / MPI3MR_AREQ_FRAME_SZ;
975 	sc->admin_req_ci = sc->admin_req_pi = 0;
976 
977 	sc->admin_reply_q_sz = MPI3MR_AREPQ_SIZE;
978 	sc->num_admin_replies = sc->admin_reply_q_sz/ MPI3MR_AREP_FRAME_SZ;
979 	sc->admin_reply_ci = 0;
980 	sc->admin_reply_ephase = 1;
981 
982 	if (!sc->admin_req) {
983 		/*
984 		 * We need to create the tag for the admin queue to get the
985 		 * iofacts to see how many bits the controller decodes.  Solve
986 		 * this chicken and egg problem by only doing lower 4GB DMA.
987 		 */
988 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
989 					4, 0,			/* algnmnt, boundary */
990 					BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
991 					BUS_SPACE_MAXADDR,	/* highaddr */
992 					NULL, NULL,		/* filter, filterarg */
993 					sc->admin_req_q_sz,	/* maxsize */
994 					1,			/* nsegments */
995 					sc->admin_req_q_sz,	/* maxsegsize */
996 					0,			/* flags */
997 					NULL, NULL,		/* lockfunc, lockarg */
998 					&sc->admin_req_tag)) {
999 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
1000 			return (ENOMEM);
1001 		}
1002 
1003 		if (bus_dmamem_alloc(sc->admin_req_tag, (void **)&sc->admin_req,
1004 		    BUS_DMA_NOWAIT, &sc->admin_req_dmamap)) {
1005 			mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
1006 			return (ENOMEM);
1007 		}
1008 		bzero(sc->admin_req, sc->admin_req_q_sz);
1009 		bus_dmamap_load(sc->admin_req_tag, sc->admin_req_dmamap, sc->admin_req, sc->admin_req_q_sz,
1010 		    mpi3mr_memaddr_cb, &sc->admin_req_phys, BUS_DMA_NOWAIT);
1011 		mpi3mr_dprint(sc, MPI3MR_XINFO, "Admin Req queue phys addr= %#016jx size= %d\n",
1012 		    (uintmax_t)sc->admin_req_phys, sc->admin_req_q_sz);
1013 
1014 		if (!sc->admin_req)
1015 		{
1016 			retval = -1;
1017 			printf(IOCNAME "Memory alloc for AdminReqQ: failed\n",
1018 			    sc->name);
1019 			goto out_failed;
1020 		}
1021 	}
1022 
1023 	if (!sc->admin_reply) {
1024 		mtx_init(&sc->admin_reply_lock, "Admin Reply Queue Lock", NULL, MTX_SPIN);
1025 
1026 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
1027 					4, 0,			/* algnmnt, boundary */
1028 					BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1029 					BUS_SPACE_MAXADDR,	/* highaddr */
1030 					NULL, NULL,		/* filter, filterarg */
1031 					sc->admin_reply_q_sz,	/* maxsize */
1032 					1,			/* nsegments */
1033 					sc->admin_reply_q_sz,	/* maxsegsize */
1034 					0,			/* flags */
1035 					NULL, NULL,		/* lockfunc, lockarg */
1036 					&sc->admin_reply_tag)) {
1037 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate reply DMA tag\n");
1038 			return (ENOMEM);
1039 		}
1040 
1041 		if (bus_dmamem_alloc(sc->admin_reply_tag, (void **)&sc->admin_reply,
1042 		    BUS_DMA_NOWAIT, &sc->admin_reply_dmamap)) {
1043 			mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
1044 			return (ENOMEM);
1045 		}
1046 		bzero(sc->admin_reply, sc->admin_reply_q_sz);
1047 		bus_dmamap_load(sc->admin_reply_tag, sc->admin_reply_dmamap, sc->admin_reply, sc->admin_reply_q_sz,
1048 		    mpi3mr_memaddr_cb, &sc->admin_reply_phys, BUS_DMA_NOWAIT);
1049 		mpi3mr_dprint(sc, MPI3MR_XINFO, "Admin Reply queue phys addr= %#016jx size= %d\n",
1050 		    (uintmax_t)sc->admin_reply_phys, sc->admin_req_q_sz);
1051 
1052 
1053 		if (!sc->admin_reply)
1054 		{
1055 			retval = -1;
1056 			printf(IOCNAME "Memory alloc for AdminRepQ: failed\n",
1057 			    sc->name);
1058 			goto out_failed;
1059 		}
1060 	}
1061 
1062 	num_adm_entries = (sc->num_admin_replies << 16) |
1063 				(sc->num_admin_reqs);
1064 	mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_Q_NUM_ENTRIES_OFFSET, num_adm_entries);
1065 	mpi3mr_regwrite64(sc, MPI3_SYSIF_ADMIN_REQ_Q_ADDR_LOW_OFFSET, sc->admin_req_phys);
1066 	mpi3mr_regwrite64(sc, MPI3_SYSIF_ADMIN_REPLY_Q_ADDR_LOW_OFFSET, sc->admin_reply_phys);
1067 	mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_REQ_Q_PI_OFFSET, sc->admin_req_pi);
1068 	mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_REPLY_Q_CI_OFFSET, sc->admin_reply_ci);
1069 
1070 	return retval;
1071 
1072 out_failed:
1073 	/* Free Admin reply*/
1074 	if (sc->admin_reply_phys)
1075 		bus_dmamap_unload(sc->admin_reply_tag, sc->admin_reply_dmamap);
1076 
1077 	if (sc->admin_reply != NULL)
1078 		bus_dmamem_free(sc->admin_reply_tag, sc->admin_reply,
1079 		    sc->admin_reply_dmamap);
1080 
1081 	if (sc->admin_reply_tag != NULL)
1082 		bus_dma_tag_destroy(sc->admin_reply_tag);
1083 
1084 	/* Free Admin request*/
1085 	if (sc->admin_req_phys)
1086 		bus_dmamap_unload(sc->admin_req_tag, sc->admin_req_dmamap);
1087 
1088 	if (sc->admin_req != NULL)
1089 		bus_dmamem_free(sc->admin_req_tag, sc->admin_req,
1090 		    sc->admin_req_dmamap);
1091 
1092 	if (sc->admin_req_tag != NULL)
1093 		bus_dma_tag_destroy(sc->admin_req_tag);
1094 
1095 	return retval;
1096 }
1097 
1098 /**
1099  * mpi3mr_print_fault_info - Display fault information
1100  * @sc: Adapter instance reference
1101  *
1102  * Display the controller fault information if there is a
1103  * controller fault.
1104  *
1105  * Return: Nothing.
1106  */
1107 static void mpi3mr_print_fault_info(struct mpi3mr_softc *sc)
1108 {
1109 	U32 ioc_status, code, code1, code2, code3;
1110 
1111 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
1112 
1113 	if (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT) {
1114 		code = mpi3mr_regread(sc, MPI3_SYSIF_FAULT_OFFSET) &
1115 			MPI3_SYSIF_FAULT_CODE_MASK;
1116 		code1 = mpi3mr_regread(sc, MPI3_SYSIF_FAULT_INFO0_OFFSET);
1117 		code2 = mpi3mr_regread(sc, MPI3_SYSIF_FAULT_INFO1_OFFSET);
1118 		code3 = mpi3mr_regread(sc, MPI3_SYSIF_FAULT_INFO2_OFFSET);
1119 		printf(IOCNAME "fault codes 0x%04x:0x%04x:0x%04x:0x%04x\n",
1120 		    sc->name, code, code1, code2, code3);
1121 	}
1122 }
1123 
1124 enum mpi3mr_iocstate mpi3mr_get_iocstate(struct mpi3mr_softc *sc)
1125 {
1126 	U32 ioc_status, ioc_control;
1127 	U8 ready, enabled;
1128 
1129 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
1130 	ioc_control = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1131 
1132 	if(sc->unrecoverable)
1133 		return MRIOC_STATE_UNRECOVERABLE;
1134 	if (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT)
1135 		return MRIOC_STATE_FAULT;
1136 
1137 	ready = (ioc_status & MPI3_SYSIF_IOC_STATUS_READY);
1138 	enabled = (ioc_control & MPI3_SYSIF_IOC_CONFIG_ENABLE_IOC);
1139 
1140 	if (ready && enabled)
1141 		return MRIOC_STATE_READY;
1142 	if ((!ready) && (!enabled))
1143 		return MRIOC_STATE_RESET;
1144 	if ((!ready) && (enabled))
1145 		return MRIOC_STATE_BECOMING_READY;
1146 
1147 	return MRIOC_STATE_RESET_REQUESTED;
1148 }
1149 
1150 static inline void mpi3mr_clear_resethistory(struct mpi3mr_softc *sc)
1151 {
1152         U32 ioc_status;
1153 
1154 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
1155         if (ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY)
1156 		mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_STATUS_OFFSET, ioc_status);
1157 
1158 }
1159 
1160 /**
1161  * mpi3mr_mur_ioc - Message unit Reset handler
1162  * @sc: Adapter instance reference
1163  * @reset_reason: Reset reason code
1164  *
1165  * Issue Message unit Reset to the controller and wait for it to
1166  * be complete.
1167  *
1168  * Return: 0 on success, -1 on failure.
1169  */
1170 static int mpi3mr_mur_ioc(struct mpi3mr_softc *sc, U16 reset_reason)
1171 {
1172 	U32 ioc_config, timeout, ioc_status, scratch_pad0;
1173         int retval = -1;
1174 
1175         mpi3mr_dprint(sc, MPI3MR_INFO, "Issuing Message Unit Reset(MUR)\n");
1176         if (sc->unrecoverable) {
1177                 mpi3mr_dprint(sc, MPI3MR_ERROR, "IOC is unrecoverable MUR not issued\n");
1178                 return retval;
1179         }
1180         mpi3mr_clear_resethistory(sc);
1181 
1182 	scratch_pad0 = ((MPI3MR_RESET_REASON_OSTYPE_FREEBSD <<
1183 			MPI3MR_RESET_REASON_OSTYPE_SHIFT) |
1184 			(sc->facts.ioc_num <<
1185 			MPI3MR_RESET_REASON_IOCNUM_SHIFT) | reset_reason);
1186 	mpi3mr_regwrite(sc, MPI3_SYSIF_SCRATCHPAD0_OFFSET, scratch_pad0);
1187 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1188         ioc_config &= ~MPI3_SYSIF_IOC_CONFIG_ENABLE_IOC;
1189 	mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET, ioc_config);
1190 
1191         timeout = MPI3MR_MUR_TIMEOUT * 10;
1192         do {
1193 		ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
1194                 if ((ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY)) {
1195                         mpi3mr_clear_resethistory(sc);
1196 			ioc_config =
1197 				mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1198                         if (!((ioc_status & MPI3_SYSIF_IOC_STATUS_READY) ||
1199                             (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT) ||
1200                             (ioc_config & MPI3_SYSIF_IOC_CONFIG_ENABLE_IOC))) {
1201                                 retval = 0;
1202                                 break;
1203                         }
1204                 }
1205                 DELAY(100 * 1000);
1206         } while (--timeout);
1207 
1208 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
1209 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1210 
1211         mpi3mr_dprint(sc, MPI3MR_INFO, "IOC Status/Config after %s MUR is (0x%x)/(0x%x)\n",
1212                 !retval ? "successful":"failed", ioc_status, ioc_config);
1213         return retval;
1214 }
1215 
1216 /**
1217  * mpi3mr_bring_ioc_ready - Bring controller to ready state
1218  * @sc: Adapter instance reference
1219  *
1220  * Set Enable IOC bit in IOC configuration register and wait for
1221  * the controller to become ready.
1222  *
1223  * Return: 0 on success, appropriate error on failure.
1224  */
1225 static int mpi3mr_bring_ioc_ready(struct mpi3mr_softc *sc)
1226 {
1227         U32 ioc_config, timeout;
1228         enum mpi3mr_iocstate current_state;
1229 
1230 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1231         ioc_config |= MPI3_SYSIF_IOC_CONFIG_ENABLE_IOC;
1232 	mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET, ioc_config);
1233 
1234         timeout = sc->ready_timeout * 10;
1235         do {
1236                 current_state = mpi3mr_get_iocstate(sc);
1237                 if (current_state == MRIOC_STATE_READY)
1238                         return 0;
1239                 DELAY(100 * 1000);
1240         } while (--timeout);
1241 
1242         return -1;
1243 }
1244 
1245 static const struct {
1246 	enum mpi3mr_iocstate value;
1247 	char *name;
1248 } mrioc_states[] = {
1249 	{ MRIOC_STATE_READY, "ready" },
1250 	{ MRIOC_STATE_FAULT, "fault" },
1251 	{ MRIOC_STATE_RESET, "reset" },
1252 	{ MRIOC_STATE_BECOMING_READY, "becoming ready" },
1253 	{ MRIOC_STATE_RESET_REQUESTED, "reset requested" },
1254 	{ MRIOC_STATE_COUNT, "Count" },
1255 };
1256 
1257 static const char *mpi3mr_iocstate_name(enum mpi3mr_iocstate mrioc_state)
1258 {
1259 	int i;
1260 	char *name = NULL;
1261 
1262 	for (i = 0; i < MRIOC_STATE_COUNT; i++) {
1263 		if (mrioc_states[i].value == mrioc_state){
1264 			name = mrioc_states[i].name;
1265 			break;
1266 		}
1267 	}
1268 	return name;
1269 }
1270 
1271 /* Reset reason to name mapper structure*/
1272 static const struct {
1273 	enum mpi3mr_reset_reason value;
1274 	char *name;
1275 } mpi3mr_reset_reason_codes[] = {
1276 	{ MPI3MR_RESET_FROM_BRINGUP, "timeout in bringup" },
1277 	{ MPI3MR_RESET_FROM_FAULT_WATCH, "fault" },
1278 	{ MPI3MR_RESET_FROM_IOCTL, "application" },
1279 	{ MPI3MR_RESET_FROM_EH_HOS, "error handling" },
1280 	{ MPI3MR_RESET_FROM_TM_TIMEOUT, "TM timeout" },
1281 	{ MPI3MR_RESET_FROM_IOCTL_TIMEOUT, "IOCTL timeout" },
1282 	{ MPI3MR_RESET_FROM_SCSIIO_TIMEOUT, "SCSIIO timeout" },
1283 	{ MPI3MR_RESET_FROM_MUR_FAILURE, "MUR failure" },
1284 	{ MPI3MR_RESET_FROM_CTLR_CLEANUP, "timeout in controller cleanup" },
1285 	{ MPI3MR_RESET_FROM_CIACTIV_FAULT, "component image activation fault" },
1286 	{ MPI3MR_RESET_FROM_PE_TIMEOUT, "port enable timeout" },
1287 	{ MPI3MR_RESET_FROM_TSU_TIMEOUT, "time stamp update timeout" },
1288 	{ MPI3MR_RESET_FROM_DELREQQ_TIMEOUT, "delete request queue timeout" },
1289 	{ MPI3MR_RESET_FROM_DELREPQ_TIMEOUT, "delete reply queue timeout" },
1290 	{
1291 		MPI3MR_RESET_FROM_CREATEREPQ_TIMEOUT,
1292 		"create request queue timeout"
1293 	},
1294 	{
1295 		MPI3MR_RESET_FROM_CREATEREQQ_TIMEOUT,
1296 		"create reply queue timeout"
1297 	},
1298 	{ MPI3MR_RESET_FROM_IOCFACTS_TIMEOUT, "IOC facts timeout" },
1299 	{ MPI3MR_RESET_FROM_IOCINIT_TIMEOUT, "IOC init timeout" },
1300 	{ MPI3MR_RESET_FROM_EVTNOTIFY_TIMEOUT, "event notify timeout" },
1301 	{ MPI3MR_RESET_FROM_EVTACK_TIMEOUT, "event acknowledgment timeout" },
1302 	{
1303 		MPI3MR_RESET_FROM_CIACTVRST_TIMER,
1304 		"component image activation timeout"
1305 	},
1306 	{
1307 		MPI3MR_RESET_FROM_GETPKGVER_TIMEOUT,
1308 		"get package version timeout"
1309 	},
1310 	{
1311 		MPI3MR_RESET_FROM_PELABORT_TIMEOUT,
1312 		"persistent event log abort timeout"
1313 	},
1314 	{ MPI3MR_RESET_FROM_SYSFS, "sysfs invocation" },
1315 	{ MPI3MR_RESET_FROM_SYSFS_TIMEOUT, "sysfs TM timeout" },
1316 	{
1317 		MPI3MR_RESET_FROM_DIAG_BUFFER_POST_TIMEOUT,
1318 		"diagnostic buffer post timeout"
1319 	},
1320 	{ MPI3MR_RESET_FROM_FIRMWARE, "firmware asynchronus reset" },
1321 	{ MPI3MR_RESET_REASON_COUNT, "Reset reason count" },
1322 };
1323 
1324 /**
1325  * mpi3mr_reset_rc_name - get reset reason code name
1326  * @reason_code: reset reason code value
1327  *
1328  * Map reset reason to an NULL terminated ASCII string
1329  *
1330  * Return: Name corresponding to reset reason value or NULL.
1331  */
1332 static const char *mpi3mr_reset_rc_name(enum mpi3mr_reset_reason reason_code)
1333 {
1334 	int i;
1335 	char *name = NULL;
1336 
1337 	for (i = 0; i < MPI3MR_RESET_REASON_COUNT; i++) {
1338 		if (mpi3mr_reset_reason_codes[i].value == reason_code) {
1339 			name = mpi3mr_reset_reason_codes[i].name;
1340 			break;
1341 		}
1342 	}
1343 	return name;
1344 }
1345 
1346 #define MAX_RESET_TYPE 3
1347 /* Reset type to name mapper structure*/
1348 static const struct {
1349 	U16 reset_type;
1350 	char *name;
1351 } mpi3mr_reset_types[] = {
1352 	{ MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET, "soft" },
1353 	{ MPI3_SYSIF_HOST_DIAG_RESET_ACTION_DIAG_FAULT, "diag fault" },
1354 	{ MAX_RESET_TYPE, "count"}
1355 };
1356 
1357 /**
1358  * mpi3mr_reset_type_name - get reset type name
1359  * @reset_type: reset type value
1360  *
1361  * Map reset type to an NULL terminated ASCII string
1362  *
1363  * Return: Name corresponding to reset type value or NULL.
1364  */
1365 static const char *mpi3mr_reset_type_name(U16 reset_type)
1366 {
1367 	int i;
1368 	char *name = NULL;
1369 
1370 	for (i = 0; i < MAX_RESET_TYPE; i++) {
1371 		if (mpi3mr_reset_types[i].reset_type == reset_type) {
1372 			name = mpi3mr_reset_types[i].name;
1373 			break;
1374 		}
1375 	}
1376 	return name;
1377 }
1378 
1379 /**
1380  * mpi3mr_soft_reset_success - Check softreset is success or not
1381  * @ioc_status: IOC status register value
1382  * @ioc_config: IOC config register value
1383  *
1384  * Check whether the soft reset is successful or not based on
1385  * IOC status and IOC config register values.
1386  *
1387  * Return: True when the soft reset is success, false otherwise.
1388  */
1389 static inline bool
1390 mpi3mr_soft_reset_success(U32 ioc_status, U32 ioc_config)
1391 {
1392 	if (!((ioc_status & MPI3_SYSIF_IOC_STATUS_READY) ||
1393 	    (ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT) ||
1394 	    (ioc_config & MPI3_SYSIF_IOC_CONFIG_ENABLE_IOC)))
1395 		return true;
1396 	return false;
1397 }
1398 
1399 /**
1400  * mpi3mr_diagfault_success - Check diag fault is success or not
1401  * @sc: Adapter reference
1402  * @ioc_status: IOC status register value
1403  *
1404  * Check whether the controller hit diag reset fault code.
1405  *
1406  * Return: True when there is diag fault, false otherwise.
1407  */
1408 static inline bool mpi3mr_diagfault_success(struct mpi3mr_softc *sc,
1409 	U32 ioc_status)
1410 {
1411 	if (!(ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT))
1412 		return false;
1413 	mpi3mr_print_fault_info(sc);
1414 	return true;
1415 }
1416 
1417 /**
1418  * mpi3mr_issue_iocfacts - Send IOC Facts
1419  * @sc: Adapter instance reference
1420  * @facts_data: Cached IOC facts data
1421  *
1422  * Issue IOC Facts MPI request through admin queue and wait for
1423  * the completion of it or time out.
1424  *
1425  * Return: 0 on success, non-zero on failures.
1426  */
1427 static int mpi3mr_issue_iocfacts(struct mpi3mr_softc *sc,
1428     Mpi3IOCFactsData_t *facts_data)
1429 {
1430 	Mpi3IOCFactsRequest_t iocfacts_req;
1431 	bus_dma_tag_t data_tag = NULL;
1432 	bus_dmamap_t data_map = NULL;
1433 	bus_addr_t data_phys = 0;
1434 	void *data = NULL;
1435 	U32 data_len = sizeof(*facts_data);
1436 	int retval = 0;
1437 
1438 	U8 sgl_flags = (MPI3_SGE_FLAGS_ELEMENT_TYPE_SIMPLE |
1439                 	MPI3_SGE_FLAGS_DLAS_SYSTEM |
1440 			MPI3_SGE_FLAGS_END_OF_LIST);
1441 
1442 
1443 	/*
1444 	 * We can't use sc->dma_loaddr here.  We set those only after we get the
1445 	 * iocfacts.  So allocate in the lower 4GB.  The amount of data is tiny
1446 	 * and we don't do this that often, so any bouncing we might have to do
1447 	 * isn't a cause for concern.
1448 	 */
1449         if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
1450 				4, 0,			/* algnmnt, boundary */
1451 				BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1452 				BUS_SPACE_MAXADDR,	/* highaddr */
1453 				NULL, NULL,		/* filter, filterarg */
1454                                 data_len,		/* maxsize */
1455                                 1,			/* nsegments */
1456                                 data_len,		/* maxsegsize */
1457                                 0,			/* flags */
1458                                 NULL, NULL,		/* lockfunc, lockarg */
1459                                 &data_tag)) {
1460 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
1461 		return (ENOMEM);
1462         }
1463 
1464         if (bus_dmamem_alloc(data_tag, (void **)&data,
1465 	    BUS_DMA_NOWAIT, &data_map)) {
1466 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d Data  DMA mem alloc failed\n",
1467 			__func__, __LINE__);
1468 		return (ENOMEM);
1469         }
1470 
1471         bzero(data, data_len);
1472         bus_dmamap_load(data_tag, data_map, data, data_len,
1473 	    mpi3mr_memaddr_cb, &data_phys, BUS_DMA_NOWAIT);
1474 	mpi3mr_dprint(sc, MPI3MR_XINFO, "Func: %s line: %d IOCfacts data phys addr= %#016jx size= %d\n",
1475 	    __func__, __LINE__, (uintmax_t)data_phys, data_len);
1476 
1477 	if (!data)
1478 	{
1479 		retval = -1;
1480 		printf(IOCNAME "Memory alloc for IOCFactsData: failed\n",
1481 		    sc->name);
1482 		goto out;
1483 	}
1484 
1485 	mtx_lock(&sc->init_cmds.completion.lock);
1486 	memset(&iocfacts_req, 0, sizeof(iocfacts_req));
1487 
1488 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
1489 		retval = -1;
1490 		printf(IOCNAME "Issue IOCFacts: Init command is in use\n",
1491 		    sc->name);
1492 		mtx_unlock(&sc->init_cmds.completion.lock);
1493 		goto out;
1494 	}
1495 
1496 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
1497 	sc->init_cmds.is_waiting = 1;
1498 	sc->init_cmds.callback = NULL;
1499 	iocfacts_req.HostTag = (MPI3MR_HOSTTAG_INITCMDS);
1500 	iocfacts_req.Function = MPI3_FUNCTION_IOC_FACTS;
1501 
1502 	mpi3mr_add_sg_single(&iocfacts_req.SGL, sgl_flags, data_len,
1503 	    data_phys);
1504 
1505 	init_completion(&sc->init_cmds.completion);
1506 
1507 	retval = mpi3mr_submit_admin_cmd(sc, &iocfacts_req,
1508 	    sizeof(iocfacts_req));
1509 
1510 	if (retval) {
1511 		printf(IOCNAME "Issue IOCFacts: Admin Post failed\n",
1512 		    sc->name);
1513 		goto out_unlock;
1514 	}
1515 
1516 	wait_for_completion_timeout(&sc->init_cmds.completion,
1517 	    (MPI3MR_INTADMCMD_TIMEOUT));
1518 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
1519 		printf(IOCNAME "Issue IOCFacts: command timed out\n",
1520 		    sc->name);
1521 		mpi3mr_check_rh_fault_ioc(sc,
1522 		    MPI3MR_RESET_FROM_IOCFACTS_TIMEOUT);
1523 		sc->unrecoverable = 1;
1524 		retval = -1;
1525 		goto out_unlock;
1526 	}
1527 
1528 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
1529 	     != MPI3_IOCSTATUS_SUCCESS ) {
1530 		printf(IOCNAME "Issue IOCFacts: Failed IOCStatus(0x%04x) "
1531 		    " Loginfo(0x%08x) \n" , sc->name,
1532 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
1533 		    sc->init_cmds.ioc_loginfo);
1534 		retval = -1;
1535 		goto out_unlock;
1536 	}
1537 
1538 	memcpy(facts_data, (U8 *)data, data_len);
1539 out_unlock:
1540 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
1541 	mtx_unlock(&sc->init_cmds.completion.lock);
1542 
1543 out:
1544 	if (data_phys != 0)
1545 		bus_dmamap_unload(data_tag, data_map);
1546 	if (data != NULL)
1547 		bus_dmamem_free(data_tag, data, data_map);
1548 	if (data_tag != NULL)
1549 		bus_dma_tag_destroy(data_tag);
1550 	return retval;
1551 }
1552 
1553 /**
1554  * mpi3mr_process_factsdata - Process IOC facts data
1555  * @sc: Adapter instance reference
1556  * @facts_data: Cached IOC facts data
1557  *
1558  * Convert IOC facts data into cpu endianness and cache it in
1559  * the driver .
1560  *
1561  * Return: Nothing.
1562  */
1563 static int mpi3mr_process_factsdata(struct mpi3mr_softc *sc,
1564     Mpi3IOCFactsData_t *facts_data)
1565 {
1566 	int retval = 0;
1567 	U32 ioc_config, req_sz, facts_flags;
1568         struct mpi3mr_compimg_ver *fwver;
1569 
1570 	if (le16toh(facts_data->IOCFactsDataLength) !=
1571 	    (sizeof(*facts_data) / 4)) {
1572 		mpi3mr_dprint(sc, MPI3MR_INFO, "IOCFacts data length mismatch "
1573 		    " driver_sz(%ld) firmware_sz(%d) \n",
1574 		    sizeof(*facts_data),
1575 		    facts_data->IOCFactsDataLength);
1576 	}
1577 
1578 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
1579         req_sz = 1 << ((ioc_config & MPI3_SYSIF_IOC_CONFIG_OPER_REQ_ENT_SZ) >>
1580                   MPI3_SYSIF_IOC_CONFIG_OPER_REQ_ENT_SZ_SHIFT);
1581 
1582 	if (facts_data->IOCRequestFrameSize != (req_sz/4)) {
1583 		 mpi3mr_dprint(sc, MPI3MR_INFO, "IOCFacts data reqFrameSize mismatch "
1584 		    " hw_size(%d) firmware_sz(%d) \n" , req_sz/4,
1585 		    facts_data->IOCRequestFrameSize);
1586 	}
1587 
1588 	memset(&sc->facts, 0, sizeof(sc->facts));
1589 
1590 	facts_flags = le32toh(facts_data->Flags);
1591 	sc->facts.op_req_sz = req_sz;
1592 	sc->op_reply_sz = 1 << ((ioc_config &
1593                                   MPI3_SYSIF_IOC_CONFIG_OPER_RPY_ENT_SZ) >>
1594                                   MPI3_SYSIF_IOC_CONFIG_OPER_RPY_ENT_SZ_SHIFT);
1595 
1596 	sc->facts.ioc_num = facts_data->IOCNumber;
1597         sc->facts.who_init = facts_data->WhoInit;
1598         sc->facts.max_msix_vectors = facts_data->MaxMSIxVectors;
1599 	sc->facts.personality = (facts_flags &
1600 	    MPI3_IOCFACTS_FLAGS_PERSONALITY_MASK);
1601 	sc->facts.dma_mask = (facts_flags &
1602 	    MPI3_IOCFACTS_FLAGS_DMA_ADDRESS_WIDTH_MASK) >>
1603 	    MPI3_IOCFACTS_FLAGS_DMA_ADDRESS_WIDTH_SHIFT;
1604         sc->facts.protocol_flags = facts_data->ProtocolFlags;
1605         sc->facts.mpi_version = (facts_data->MPIVersion.Word);
1606         sc->facts.max_reqs = (facts_data->MaxOutstandingRequests);
1607         sc->facts.product_id = (facts_data->ProductID);
1608 	sc->facts.reply_sz = (facts_data->ReplyFrameSize) * 4;
1609         sc->facts.exceptions = (facts_data->IOCExceptions);
1610         sc->facts.max_perids = (facts_data->MaxPersistentID);
1611         sc->facts.max_vds = (facts_data->MaxVDs);
1612         sc->facts.max_hpds = (facts_data->MaxHostPDs);
1613         sc->facts.max_advhpds = (facts_data->MaxAdvHostPDs);
1614         sc->facts.max_raidpds = (facts_data->MaxRAIDPDs);
1615         sc->facts.max_nvme = (facts_data->MaxNVMe);
1616         sc->facts.max_pcieswitches =
1617                 (facts_data->MaxPCIeSwitches);
1618         sc->facts.max_sasexpanders =
1619                 (facts_data->MaxSASExpanders);
1620         sc->facts.max_sasinitiators =
1621                 (facts_data->MaxSASInitiators);
1622         sc->facts.max_enclosures = (facts_data->MaxEnclosures);
1623         sc->facts.min_devhandle = (facts_data->MinDevHandle);
1624         sc->facts.max_devhandle = (facts_data->MaxDevHandle);
1625 	sc->facts.max_op_req_q =
1626                 (facts_data->MaxOperationalRequestQueues);
1627 	sc->facts.max_op_reply_q =
1628                 (facts_data->MaxOperationalReplyQueues);
1629         sc->facts.ioc_capabilities =
1630                 (facts_data->IOCCapabilities);
1631         sc->facts.fw_ver.build_num =
1632                 (facts_data->FWVersion.BuildNum);
1633         sc->facts.fw_ver.cust_id =
1634                 (facts_data->FWVersion.CustomerID);
1635         sc->facts.fw_ver.ph_minor = facts_data->FWVersion.PhaseMinor;
1636         sc->facts.fw_ver.ph_major = facts_data->FWVersion.PhaseMajor;
1637         sc->facts.fw_ver.gen_minor = facts_data->FWVersion.GenMinor;
1638         sc->facts.fw_ver.gen_major = facts_data->FWVersion.GenMajor;
1639         sc->max_msix_vectors = min(sc->max_msix_vectors,
1640             sc->facts.max_msix_vectors);
1641         sc->facts.sge_mod_mask = facts_data->SGEModifierMask;
1642         sc->facts.sge_mod_value = facts_data->SGEModifierValue;
1643         sc->facts.sge_mod_shift = facts_data->SGEModifierShift;
1644         sc->facts.shutdown_timeout =
1645                 (facts_data->ShutdownTimeout);
1646 	sc->facts.max_dev_per_tg = facts_data->MaxDevicesPerThrottleGroup;
1647 	sc->facts.io_throttle_data_length =
1648 	    facts_data->IOThrottleDataLength;
1649 	sc->facts.max_io_throttle_group =
1650 	    facts_data->MaxIOThrottleGroup;
1651 	sc->facts.io_throttle_low = facts_data->IOThrottleLow;
1652 	sc->facts.io_throttle_high = facts_data->IOThrottleHigh;
1653 
1654 	/*Store in 512b block count*/
1655 	if (sc->facts.io_throttle_data_length)
1656 		sc->io_throttle_data_length =
1657 		    (sc->facts.io_throttle_data_length * 2 * 4);
1658 	else
1659 		/* set the length to 1MB + 1K to disable throttle*/
1660 		sc->io_throttle_data_length = MPI3MR_MAX_SECTORS + 2;
1661 
1662 	sc->io_throttle_high = (sc->facts.io_throttle_high * 2 * 1024);
1663 	sc->io_throttle_low = (sc->facts.io_throttle_low * 2 * 1024);
1664 
1665 	fwver = &sc->facts.fw_ver;
1666 	snprintf(sc->fw_version, sizeof(sc->fw_version),
1667 	    "%d.%d.%d.%d.%05d-%05d",
1668 	    fwver->gen_major, fwver->gen_minor, fwver->ph_major,
1669 	    fwver->ph_minor, fwver->cust_id, fwver->build_num);
1670 
1671 	mpi3mr_dprint(sc, MPI3MR_INFO, "ioc_num(%d), maxopQ(%d), maxopRepQ(%d), maxdh(%d),"
1672             "maxreqs(%d), mindh(%d) maxPDs(%d) maxvectors(%d) maxperids(%d)\n",
1673 	    sc->facts.ioc_num, sc->facts.max_op_req_q,
1674 	    sc->facts.max_op_reply_q, sc->facts.max_devhandle,
1675             sc->facts.max_reqs, sc->facts.min_devhandle,
1676             sc->facts.max_pds, sc->facts.max_msix_vectors,
1677             sc->facts.max_perids);
1678         mpi3mr_dprint(sc, MPI3MR_INFO, "SGEModMask 0x%x SGEModVal 0x%x SGEModShift 0x%x\n",
1679             sc->facts.sge_mod_mask, sc->facts.sge_mod_value,
1680             sc->facts.sge_mod_shift);
1681 	mpi3mr_dprint(sc, MPI3MR_INFO,
1682 	    "max_dev_per_throttle_group(%d), max_throttle_groups(%d), io_throttle_data_len(%dKiB), io_throttle_high(%dMiB), io_throttle_low(%dMiB)\n",
1683 	    sc->facts.max_dev_per_tg, sc->facts.max_io_throttle_group,
1684 	    sc->facts.io_throttle_data_length * 4,
1685 	    sc->facts.io_throttle_high, sc->facts.io_throttle_low);
1686 
1687 	sc->max_host_ios = sc->facts.max_reqs -
1688 	    (MPI3MR_INTERNALCMDS_RESVD + 1);
1689 
1690 	/*
1691 	 * Set the DMA mask for the card.  dma_mask is the number of bits that
1692 	 * can have bits set in them.  Translate this into bus_dma loaddr args.
1693 	 * Add sanity for more bits than address space or other overflow
1694 	 * situations.
1695 	 */
1696 	if (sc->facts.dma_mask == 0 ||
1697 	    (sc->facts.dma_mask >= sizeof(bus_addr_t) * 8))
1698 		sc->dma_loaddr = BUS_SPACE_MAXADDR;
1699 	else
1700 		sc->dma_loaddr = ~((1ull << sc->facts.dma_mask) - 1);
1701 	mpi3mr_dprint(sc, MPI3MR_INFO,
1702 	    "dma_mask bits: %d loaddr 0x%jx\n",
1703 	    sc->facts.dma_mask, sc->dma_loaddr);
1704 
1705 	return retval;
1706 }
1707 
1708 static inline void mpi3mr_setup_reply_free_queues(struct mpi3mr_softc *sc)
1709 {
1710 	int i;
1711 	bus_addr_t phys_addr;
1712 
1713 	/* initialize Reply buffer Queue */
1714 	for (i = 0, phys_addr = sc->reply_buf_phys;
1715 	    i < sc->num_reply_bufs; i++, phys_addr += sc->reply_sz)
1716 		sc->reply_free_q[i] = phys_addr;
1717 	sc->reply_free_q[i] = (0);
1718 
1719 	/* initialize Sense Buffer Queue */
1720 	for (i = 0, phys_addr = sc->sense_buf_phys;
1721 	    i < sc->num_sense_bufs; i++, phys_addr += MPI3MR_SENSEBUF_SZ)
1722 		sc->sense_buf_q[i] = phys_addr;
1723 	sc->sense_buf_q[i] = (0);
1724 
1725 }
1726 
1727 static int mpi3mr_reply_dma_alloc(struct mpi3mr_softc *sc)
1728 {
1729 	U32 sz;
1730 
1731 	sc->num_reply_bufs = sc->facts.max_reqs + MPI3MR_NUM_EVTREPLIES;
1732 	sc->reply_free_q_sz = sc->num_reply_bufs + 1;
1733 	sc->num_sense_bufs = sc->facts.max_reqs / MPI3MR_SENSEBUF_FACTOR;
1734 	sc->sense_buf_q_sz = sc->num_sense_bufs + 1;
1735 
1736 	sz = sc->num_reply_bufs * sc->reply_sz;
1737 
1738 	if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,  /* parent */
1739 				16, 0,			/* algnmnt, boundary */
1740 				sc->dma_loaddr,		/* lowaddr */
1741 				BUS_SPACE_MAXADDR,	/* highaddr */
1742 				NULL, NULL,		/* filter, filterarg */
1743                                 sz,			/* maxsize */
1744                                 1,			/* nsegments */
1745                                 sz,			/* maxsegsize */
1746                                 0,			/* flags */
1747                                 NULL, NULL,		/* lockfunc, lockarg */
1748                                 &sc->reply_buf_tag)) {
1749 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
1750 		return (ENOMEM);
1751         }
1752 
1753 	if (bus_dmamem_alloc(sc->reply_buf_tag, (void **)&sc->reply_buf,
1754 	    BUS_DMA_NOWAIT, &sc->reply_buf_dmamap)) {
1755 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d  DMA mem alloc failed\n",
1756 			__func__, __LINE__);
1757 		return (ENOMEM);
1758         }
1759 
1760 	bzero(sc->reply_buf, sz);
1761         bus_dmamap_load(sc->reply_buf_tag, sc->reply_buf_dmamap, sc->reply_buf, sz,
1762 	    mpi3mr_memaddr_cb, &sc->reply_buf_phys, BUS_DMA_NOWAIT);
1763 
1764 	sc->reply_buf_dma_min_address = sc->reply_buf_phys;
1765 	sc->reply_buf_dma_max_address = sc->reply_buf_phys + sz;
1766 	mpi3mr_dprint(sc, MPI3MR_XINFO, "reply buf (0x%p): depth(%d), frame_size(%d), "
1767 	    "pool_size(%d kB), reply_buf_dma(0x%llx)\n",
1768 	    sc->reply_buf, sc->num_reply_bufs, sc->reply_sz,
1769 	    (sz / 1024), (unsigned long long)sc->reply_buf_phys);
1770 
1771 	/* reply free queue, 8 byte align */
1772 	sz = sc->reply_free_q_sz * 8;
1773 
1774         if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
1775 				8, 0,			/* algnmnt, boundary */
1776 				sc->dma_loaddr,		/* lowaddr */
1777 				BUS_SPACE_MAXADDR,	/* highaddr */
1778 				NULL, NULL,		/* filter, filterarg */
1779                                 sz,			/* maxsize */
1780                                 1,			/* nsegments */
1781                                 sz,			/* maxsegsize */
1782                                 0,			/* flags */
1783                                 NULL, NULL,		/* lockfunc, lockarg */
1784                                 &sc->reply_free_q_tag)) {
1785 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate reply free queue DMA tag\n");
1786 		return (ENOMEM);
1787         }
1788 
1789         if (bus_dmamem_alloc(sc->reply_free_q_tag, (void **)&sc->reply_free_q,
1790 	    BUS_DMA_NOWAIT, &sc->reply_free_q_dmamap)) {
1791 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d  DMA mem alloc failed\n",
1792 			__func__, __LINE__);
1793 		return (ENOMEM);
1794         }
1795 
1796 	bzero(sc->reply_free_q, sz);
1797         bus_dmamap_load(sc->reply_free_q_tag, sc->reply_free_q_dmamap, sc->reply_free_q, sz,
1798 	    mpi3mr_memaddr_cb, &sc->reply_free_q_phys, BUS_DMA_NOWAIT);
1799 
1800 	mpi3mr_dprint(sc, MPI3MR_XINFO, "reply_free_q (0x%p): depth(%d), frame_size(%d), "
1801 	    "pool_size(%d kB), reply_free_q_dma(0x%llx)\n",
1802 	    sc->reply_free_q, sc->reply_free_q_sz, 8, (sz / 1024),
1803 	    (unsigned long long)sc->reply_free_q_phys);
1804 
1805 	/* sense buffer pool,  4 byte align */
1806 	sz = sc->num_sense_bufs * MPI3MR_SENSEBUF_SZ;
1807 
1808         if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
1809 				4, 0,			/* algnmnt, boundary */
1810 				sc->dma_loaddr,		/* lowaddr */
1811 				BUS_SPACE_MAXADDR,	/* highaddr */
1812 				NULL, NULL,		/* filter, filterarg */
1813                                 sz,			/* maxsize */
1814                                 1,			/* nsegments */
1815                                 sz,			/* maxsegsize */
1816                                 0,			/* flags */
1817                                 NULL, NULL,		/* lockfunc, lockarg */
1818                                 &sc->sense_buf_tag)) {
1819 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate Sense buffer DMA tag\n");
1820 		return (ENOMEM);
1821         }
1822 
1823 	if (bus_dmamem_alloc(sc->sense_buf_tag, (void **)&sc->sense_buf,
1824 	    BUS_DMA_NOWAIT, &sc->sense_buf_dmamap)) {
1825 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d  DMA mem alloc failed\n",
1826 			__func__, __LINE__);
1827 		return (ENOMEM);
1828         }
1829 
1830 	bzero(sc->sense_buf, sz);
1831         bus_dmamap_load(sc->sense_buf_tag, sc->sense_buf_dmamap, sc->sense_buf, sz,
1832 	    mpi3mr_memaddr_cb, &sc->sense_buf_phys, BUS_DMA_NOWAIT);
1833 
1834 	mpi3mr_dprint(sc, MPI3MR_XINFO, "sense_buf (0x%p): depth(%d), frame_size(%d), "
1835 	    "pool_size(%d kB), sense_dma(0x%llx)\n",
1836 	    sc->sense_buf, sc->num_sense_bufs, MPI3MR_SENSEBUF_SZ,
1837 	    (sz / 1024), (unsigned long long)sc->sense_buf_phys);
1838 
1839 	/* sense buffer queue, 8 byte align */
1840 	sz = sc->sense_buf_q_sz * 8;
1841 
1842         if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
1843 				8, 0,			/* algnmnt, boundary */
1844 				sc->dma_loaddr,		/* lowaddr */
1845 				BUS_SPACE_MAXADDR,	/* highaddr */
1846 				NULL, NULL,		/* filter, filterarg */
1847                                 sz,			/* maxsize */
1848                                 1,			/* nsegments */
1849                                 sz,			/* maxsegsize */
1850                                 0,			/* flags */
1851                                 NULL, NULL,		/* lockfunc, lockarg */
1852                                 &sc->sense_buf_q_tag)) {
1853 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate Sense buffer Queue DMA tag\n");
1854 		return (ENOMEM);
1855         }
1856 
1857 	if (bus_dmamem_alloc(sc->sense_buf_q_tag, (void **)&sc->sense_buf_q,
1858 	    BUS_DMA_NOWAIT, &sc->sense_buf_q_dmamap)) {
1859 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d  DMA mem alloc failed\n",
1860 			__func__, __LINE__);
1861 		return (ENOMEM);
1862         }
1863 
1864 	bzero(sc->sense_buf_q, sz);
1865         bus_dmamap_load(sc->sense_buf_q_tag, sc->sense_buf_q_dmamap, sc->sense_buf_q, sz,
1866 	    mpi3mr_memaddr_cb, &sc->sense_buf_q_phys, BUS_DMA_NOWAIT);
1867 
1868 	mpi3mr_dprint(sc, MPI3MR_XINFO, "sense_buf_q (0x%p): depth(%d), frame_size(%d), "
1869 	    "pool_size(%d kB), sense_dma(0x%llx)\n",
1870 	    sc->sense_buf_q, sc->sense_buf_q_sz, 8, (sz / 1024),
1871 	    (unsigned long long)sc->sense_buf_q_phys);
1872 
1873 	return 0;
1874 }
1875 
1876 static int mpi3mr_reply_alloc(struct mpi3mr_softc *sc)
1877 {
1878 	int retval = 0;
1879 	U32 i;
1880 
1881 	if (sc->init_cmds.reply)
1882 		goto post_reply_sbuf;
1883 
1884 	sc->init_cmds.reply = malloc(sc->reply_sz,
1885 		M_MPI3MR, M_NOWAIT | M_ZERO);
1886 
1887 	if (!sc->init_cmds.reply) {
1888 		printf(IOCNAME "Cannot allocate memory for init_cmds.reply\n",
1889 		    sc->name);
1890 		goto out_failed;
1891 	}
1892 
1893 	sc->ioctl_cmds.reply = malloc(sc->reply_sz, M_MPI3MR, M_NOWAIT | M_ZERO);
1894 	if (!sc->ioctl_cmds.reply) {
1895 		printf(IOCNAME "Cannot allocate memory for ioctl_cmds.reply\n",
1896 		    sc->name);
1897 		goto out_failed;
1898 	}
1899 
1900 	sc->host_tm_cmds.reply = malloc(sc->reply_sz, M_MPI3MR, M_NOWAIT | M_ZERO);
1901 	if (!sc->host_tm_cmds.reply) {
1902 		printf(IOCNAME "Cannot allocate memory for host_tm.reply\n",
1903 		    sc->name);
1904 		goto out_failed;
1905 	}
1906 	for (i=0; i<MPI3MR_NUM_DEVRMCMD; i++) {
1907 		sc->dev_rmhs_cmds[i].reply = malloc(sc->reply_sz,
1908 		    M_MPI3MR, M_NOWAIT | M_ZERO);
1909 		if (!sc->dev_rmhs_cmds[i].reply) {
1910 			printf(IOCNAME "Cannot allocate memory for"
1911 			    " dev_rmhs_cmd[%d].reply\n",
1912 			    sc->name, i);
1913 			goto out_failed;
1914 		}
1915 	}
1916 
1917 	for (i = 0; i < MPI3MR_NUM_EVTACKCMD; i++) {
1918 		sc->evtack_cmds[i].reply = malloc(sc->reply_sz,
1919 			M_MPI3MR, M_NOWAIT | M_ZERO);
1920 		if (!sc->evtack_cmds[i].reply)
1921 			goto out_failed;
1922 	}
1923 
1924 	sc->dev_handle_bitmap_sz = MPI3MR_DIV_ROUND_UP(sc->facts.max_devhandle, 8);
1925 
1926 	sc->removepend_bitmap = malloc(sc->dev_handle_bitmap_sz,
1927 	    M_MPI3MR, M_NOWAIT | M_ZERO);
1928 	if (!sc->removepend_bitmap) {
1929 		printf(IOCNAME "Cannot alloc memory for remove pend bitmap\n",
1930 		    sc->name);
1931 		goto out_failed;
1932 	}
1933 
1934 	sc->devrem_bitmap_sz = MPI3MR_DIV_ROUND_UP(MPI3MR_NUM_DEVRMCMD, 8);
1935 	sc->devrem_bitmap = malloc(sc->devrem_bitmap_sz,
1936 	    M_MPI3MR, M_NOWAIT | M_ZERO);
1937 	if (!sc->devrem_bitmap) {
1938 		printf(IOCNAME "Cannot alloc memory for dev remove bitmap\n",
1939 		    sc->name);
1940 		goto out_failed;
1941 	}
1942 
1943 	sc->evtack_cmds_bitmap_sz = MPI3MR_DIV_ROUND_UP(MPI3MR_NUM_EVTACKCMD, 8);
1944 
1945 	sc->evtack_cmds_bitmap = malloc(sc->evtack_cmds_bitmap_sz,
1946 		M_MPI3MR, M_NOWAIT | M_ZERO);
1947 	if (!sc->evtack_cmds_bitmap)
1948 		goto out_failed;
1949 
1950 	if (mpi3mr_reply_dma_alloc(sc)) {
1951 		printf(IOCNAME "func:%s line:%d DMA memory allocation failed\n",
1952 		    sc->name, __func__, __LINE__);
1953 		goto out_failed;
1954 	}
1955 
1956 post_reply_sbuf:
1957 	mpi3mr_setup_reply_free_queues(sc);
1958 	return retval;
1959 out_failed:
1960 	mpi3mr_cleanup_interrupts(sc);
1961 	mpi3mr_free_mem(sc);
1962 	retval = -1;
1963 	return retval;
1964 }
1965 
1966 static void
1967 mpi3mr_print_fw_pkg_ver(struct mpi3mr_softc *sc)
1968 {
1969 	int retval = 0;
1970 	void *fw_pkg_ver = NULL;
1971 	bus_dma_tag_t fw_pkg_ver_tag;
1972 	bus_dmamap_t fw_pkg_ver_map;
1973 	bus_addr_t fw_pkg_ver_dma;
1974 	Mpi3CIUploadRequest_t ci_upload;
1975 	Mpi3ComponentImageHeader_t *ci_header;
1976 	U32 fw_pkg_ver_len = sizeof(*ci_header);
1977 	U8 sgl_flags = MPI3MR_SGEFLAGS_SYSTEM_SIMPLE_END_OF_LIST;
1978 
1979 	if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,  /* parent */
1980 				4, 0,			/* algnmnt, boundary */
1981 				sc->dma_loaddr,		/* lowaddr */
1982 				BUS_SPACE_MAXADDR,	/* highaddr */
1983 				NULL, NULL,		/* filter, filterarg */
1984 				fw_pkg_ver_len,		/* maxsize */
1985 				1,			/* nsegments */
1986 				fw_pkg_ver_len,		/* maxsegsize */
1987 				0,			/* flags */
1988 				NULL, NULL,		/* lockfunc, lockarg */
1989 				&fw_pkg_ver_tag)) {
1990 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate fw package version request DMA tag\n");
1991 		return;
1992 	}
1993 
1994 	if (bus_dmamem_alloc(fw_pkg_ver_tag, (void **)&fw_pkg_ver, BUS_DMA_NOWAIT, &fw_pkg_ver_map)) {
1995 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d fw package version DMA mem alloc failed\n",
1996 			      __func__, __LINE__);
1997 		return;
1998 	}
1999 
2000 	bzero(fw_pkg_ver, fw_pkg_ver_len);
2001 
2002 	bus_dmamap_load(fw_pkg_ver_tag, fw_pkg_ver_map, fw_pkg_ver, fw_pkg_ver_len,
2003 	    mpi3mr_memaddr_cb, &fw_pkg_ver_dma, BUS_DMA_NOWAIT);
2004 
2005 	mpi3mr_dprint(sc, MPI3MR_XINFO, "Func: %s line: %d fw package version phys addr= %#016jx size= %d\n",
2006 		      __func__, __LINE__, (uintmax_t)fw_pkg_ver_dma, fw_pkg_ver_len);
2007 
2008 	if (!fw_pkg_ver) {
2009 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Memory alloc for fw package version failed\n");
2010 		goto out;
2011 	}
2012 
2013 	memset(&ci_upload, 0, sizeof(ci_upload));
2014 	mtx_lock(&sc->init_cmds.completion.lock);
2015 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
2016 		mpi3mr_dprint(sc, MPI3MR_INFO,"Issue CI Header Upload: command is in use\n");
2017 		mtx_unlock(&sc->init_cmds.completion.lock);
2018 		goto out;
2019 	}
2020 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
2021 	sc->init_cmds.is_waiting = 1;
2022 	sc->init_cmds.callback = NULL;
2023 	ci_upload.HostTag = htole16(MPI3MR_HOSTTAG_INITCMDS);
2024 	ci_upload.Function = MPI3_FUNCTION_CI_UPLOAD;
2025 	ci_upload.MsgFlags = MPI3_CI_UPLOAD_MSGFLAGS_LOCATION_PRIMARY;
2026 	ci_upload.ImageOffset = MPI3_IMAGE_HEADER_SIGNATURE0_OFFSET;
2027 	ci_upload.SegmentSize = MPI3_IMAGE_HEADER_SIZE;
2028 
2029 	mpi3mr_add_sg_single(&ci_upload.SGL, sgl_flags, fw_pkg_ver_len,
2030 	    fw_pkg_ver_dma);
2031 
2032 	init_completion(&sc->init_cmds.completion);
2033 	if ((retval = mpi3mr_submit_admin_cmd(sc, &ci_upload, sizeof(ci_upload)))) {
2034 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Issue CI Header Upload: Admin Post failed\n");
2035 		goto out_unlock;
2036 	}
2037 	wait_for_completion_timeout(&sc->init_cmds.completion,
2038 		(MPI3MR_INTADMCMD_TIMEOUT));
2039 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
2040 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Issue CI Header Upload: command timed out\n");
2041 		sc->init_cmds.is_waiting = 0;
2042 		if (!(sc->init_cmds.state & MPI3MR_CMD_RESET))
2043 			mpi3mr_check_rh_fault_ioc(sc,
2044 				MPI3MR_RESET_FROM_GETPKGVER_TIMEOUT);
2045 		goto out_unlock;
2046 	}
2047 	if ((GET_IOC_STATUS(sc->init_cmds.ioc_status)) != MPI3_IOCSTATUS_SUCCESS) {
2048 		mpi3mr_dprint(sc, MPI3MR_ERROR,
2049 			      "Issue CI Header Upload: Failed IOCStatus(0x%04x) Loginfo(0x%08x)\n",
2050 			      GET_IOC_STATUS(sc->init_cmds.ioc_status), sc->init_cmds.ioc_loginfo);
2051 		goto out_unlock;
2052 	}
2053 
2054 	ci_header = (Mpi3ComponentImageHeader_t *) fw_pkg_ver;
2055 	mpi3mr_dprint(sc, MPI3MR_XINFO,
2056 		      "Issue CI Header Upload:EnvVariableOffset(0x%x) \
2057 		      HeaderSize(0x%x) Signature1(0x%x)\n",
2058 		      ci_header->EnvironmentVariableOffset,
2059 		      ci_header->HeaderSize,
2060 		      ci_header->Signature1);
2061 	mpi3mr_dprint(sc, MPI3MR_INFO, "FW Package Version: %02d.%02d.%02d.%02d\n",
2062 		      ci_header->ComponentImageVersion.GenMajor,
2063 		      ci_header->ComponentImageVersion.GenMinor,
2064 		      ci_header->ComponentImageVersion.PhaseMajor,
2065 		      ci_header->ComponentImageVersion.PhaseMinor);
2066 out_unlock:
2067 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
2068 	mtx_unlock(&sc->init_cmds.completion.lock);
2069 
2070 out:
2071 	if (fw_pkg_ver_dma != 0)
2072 		bus_dmamap_unload(fw_pkg_ver_tag, fw_pkg_ver_map);
2073 	if (fw_pkg_ver)
2074 		bus_dmamem_free(fw_pkg_ver_tag, fw_pkg_ver, fw_pkg_ver_map);
2075 	if (fw_pkg_ver_tag)
2076 		bus_dma_tag_destroy(fw_pkg_ver_tag);
2077 
2078 }
2079 
2080 /**
2081  * mpi3mr_issue_iocinit - Send IOC Init
2082  * @sc: Adapter instance reference
2083  *
2084  * Issue IOC Init MPI request through admin queue and wait for
2085  * the completion of it or time out.
2086  *
2087  * Return: 0 on success, non-zero on failures.
2088  */
2089 static int mpi3mr_issue_iocinit(struct mpi3mr_softc *sc)
2090 {
2091 	Mpi3IOCInitRequest_t iocinit_req;
2092 	Mpi3DriverInfoLayout_t *drvr_info = NULL;
2093 	bus_dma_tag_t drvr_info_tag;
2094 	bus_dmamap_t drvr_info_map;
2095 	bus_addr_t drvr_info_phys;
2096 	U32 drvr_info_len = sizeof(*drvr_info);
2097 	int retval = 0;
2098 	struct timeval now;
2099 	uint64_t time_in_msec;
2100 
2101 	if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,  /* parent */
2102 				4, 0,			/* algnmnt, boundary */
2103 				sc->dma_loaddr,		/* lowaddr */
2104 				BUS_SPACE_MAXADDR,	/* highaddr */
2105 				NULL, NULL,		/* filter, filterarg */
2106                                 drvr_info_len,		/* maxsize */
2107                                 1,			/* nsegments */
2108                                 drvr_info_len,		/* maxsegsize */
2109                                 0,			/* flags */
2110                                 NULL, NULL,		/* lockfunc, lockarg */
2111                                 &drvr_info_tag)) {
2112 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
2113 		return (ENOMEM);
2114         }
2115 
2116 	if (bus_dmamem_alloc(drvr_info_tag, (void **)&drvr_info,
2117 	    BUS_DMA_NOWAIT, &drvr_info_map)) {
2118 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d Data  DMA mem alloc failed\n",
2119 			__func__, __LINE__);
2120 		return (ENOMEM);
2121         }
2122 
2123 	bzero(drvr_info, drvr_info_len);
2124         bus_dmamap_load(drvr_info_tag, drvr_info_map, drvr_info, drvr_info_len,
2125 	    mpi3mr_memaddr_cb, &drvr_info_phys, BUS_DMA_NOWAIT);
2126 	mpi3mr_dprint(sc, MPI3MR_XINFO, "Func: %s line: %d IOCfacts drvr_info phys addr= %#016jx size= %d\n",
2127 	    __func__, __LINE__, (uintmax_t)drvr_info_phys, drvr_info_len);
2128 
2129 	if (!drvr_info)
2130 	{
2131 		retval = -1;
2132 		printf(IOCNAME "Memory alloc for Driver Info failed\n",
2133 		    sc->name);
2134 		goto out;
2135 	}
2136 	drvr_info->InformationLength = (drvr_info_len);
2137 	strcpy(drvr_info->DriverSignature, "Broadcom");
2138 	strcpy(drvr_info->OsName, "FreeBSD");
2139 	strcpy(drvr_info->OsVersion, fmt_os_ver);
2140 	strcpy(drvr_info->DriverName, MPI3MR_DRIVER_NAME);
2141 	strcpy(drvr_info->DriverVersion, MPI3MR_DRIVER_VERSION);
2142 	strcpy(drvr_info->DriverReleaseDate, MPI3MR_DRIVER_RELDATE);
2143 	drvr_info->DriverCapabilities = 0;
2144 	memcpy((U8 *)&sc->driver_info, (U8 *)drvr_info, sizeof(sc->driver_info));
2145 
2146 	memset(&iocinit_req, 0, sizeof(iocinit_req));
2147 	mtx_lock(&sc->init_cmds.completion.lock);
2148 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
2149 		retval = -1;
2150 		printf(IOCNAME "Issue IOCInit: Init command is in use\n",
2151 		    sc->name);
2152 		mtx_unlock(&sc->init_cmds.completion.lock);
2153 		goto out;
2154 	}
2155 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
2156 	sc->init_cmds.is_waiting = 1;
2157 	sc->init_cmds.callback = NULL;
2158         iocinit_req.HostTag = MPI3MR_HOSTTAG_INITCMDS;
2159         iocinit_req.Function = MPI3_FUNCTION_IOC_INIT;
2160         iocinit_req.MPIVersion.Struct.Dev = MPI3_VERSION_DEV;
2161         iocinit_req.MPIVersion.Struct.Unit = MPI3_VERSION_UNIT;
2162         iocinit_req.MPIVersion.Struct.Major = MPI3_VERSION_MAJOR;
2163         iocinit_req.MPIVersion.Struct.Minor = MPI3_VERSION_MINOR;
2164         iocinit_req.WhoInit = MPI3_WHOINIT_HOST_DRIVER;
2165         iocinit_req.ReplyFreeQueueDepth = sc->reply_free_q_sz;
2166         iocinit_req.ReplyFreeQueueAddress =
2167                 sc->reply_free_q_phys;
2168         iocinit_req.SenseBufferLength = MPI3MR_SENSEBUF_SZ;
2169         iocinit_req.SenseBufferFreeQueueDepth =
2170                 sc->sense_buf_q_sz;
2171         iocinit_req.SenseBufferFreeQueueAddress =
2172                 sc->sense_buf_q_phys;
2173         iocinit_req.DriverInformationAddress = drvr_info_phys;
2174 
2175 	getmicrotime(&now);
2176 	time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
2177 	iocinit_req.TimeStamp = htole64(time_in_msec);
2178 
2179 	init_completion(&sc->init_cmds.completion);
2180 	retval = mpi3mr_submit_admin_cmd(sc, &iocinit_req,
2181 	    sizeof(iocinit_req));
2182 
2183 	if (retval) {
2184 		printf(IOCNAME "Issue IOCInit: Admin Post failed\n",
2185 		    sc->name);
2186 		goto out_unlock;
2187 	}
2188 
2189 	wait_for_completion_timeout(&sc->init_cmds.completion,
2190 	    (MPI3MR_INTADMCMD_TIMEOUT));
2191 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
2192 		printf(IOCNAME "Issue IOCInit: command timed out\n",
2193 		    sc->name);
2194 		mpi3mr_check_rh_fault_ioc(sc,
2195 		    MPI3MR_RESET_FROM_IOCINIT_TIMEOUT);
2196 		sc->unrecoverable = 1;
2197 		retval = -1;
2198 		goto out_unlock;
2199 	}
2200 
2201 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
2202 	     != MPI3_IOCSTATUS_SUCCESS ) {
2203 		printf(IOCNAME "Issue IOCInit: Failed IOCStatus(0x%04x) "
2204 		    " Loginfo(0x%08x) \n" , sc->name,
2205 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
2206 		    sc->init_cmds.ioc_loginfo);
2207 		retval = -1;
2208 		goto out_unlock;
2209 	}
2210 
2211 out_unlock:
2212 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
2213 	mtx_unlock(&sc->init_cmds.completion.lock);
2214 
2215 out:
2216 	if (drvr_info_phys != 0)
2217 		bus_dmamap_unload(drvr_info_tag, drvr_info_map);
2218 	if (drvr_info != NULL)
2219 		bus_dmamem_free(drvr_info_tag, drvr_info, drvr_info_map);
2220 	if (drvr_info_tag != NULL)
2221 		bus_dma_tag_destroy(drvr_info_tag);
2222 	return retval;
2223 }
2224 
2225 static void
2226 mpi3mr_display_ioc_info(struct mpi3mr_softc *sc)
2227 {
2228         int i = 0;
2229         char personality[16];
2230 
2231         switch (sc->facts.personality) {
2232         case MPI3_IOCFACTS_FLAGS_PERSONALITY_EHBA:
2233                 strcpy(personality, "Enhanced HBA");
2234                 break;
2235         case MPI3_IOCFACTS_FLAGS_PERSONALITY_RAID_DDR:
2236                 strcpy(personality, "RAID");
2237                 break;
2238         default:
2239                 strcpy(personality, "Unknown");
2240                 break;
2241         }
2242 
2243 	mpi3mr_dprint(sc, MPI3MR_INFO, "Current Personality: %s\n", personality);
2244 
2245 	mpi3mr_dprint(sc, MPI3MR_INFO, "%s\n", sc->fw_version);
2246 
2247         mpi3mr_dprint(sc, MPI3MR_INFO, "Protocol=(");
2248 
2249         if (sc->facts.protocol_flags &
2250             MPI3_IOCFACTS_PROTOCOL_SCSI_INITIATOR) {
2251                 printf("Initiator");
2252                 i++;
2253         }
2254 
2255         if (sc->facts.protocol_flags &
2256             MPI3_IOCFACTS_PROTOCOL_SCSI_TARGET) {
2257                 printf("%sTarget", i ? "," : "");
2258                 i++;
2259         }
2260 
2261         if (sc->facts.protocol_flags &
2262             MPI3_IOCFACTS_PROTOCOL_NVME) {
2263                 printf("%sNVMe attachment", i ? "," : "");
2264                 i++;
2265         }
2266         i = 0;
2267         printf("), ");
2268         printf("Capabilities=(");
2269 
2270         if (sc->facts.ioc_capabilities &
2271 	    MPI3_IOCFACTS_CAPABILITY_RAID_SUPPORTED) {
2272                 printf("RAID");
2273                 i++;
2274         }
2275 
2276         printf(")\n");
2277 }
2278 
2279 /**
2280  * mpi3mr_unmask_events - Unmask events in event mask bitmap
2281  * @sc: Adapter instance reference
2282  * @event: MPI event ID
2283  *
2284  * Un mask the specific event by resetting the event_mask
2285  * bitmap.
2286  *
2287  * Return: None.
2288  */
2289 static void mpi3mr_unmask_events(struct mpi3mr_softc *sc, U16 event)
2290 {
2291 	U32 desired_event;
2292 
2293 	if (event >= 128)
2294 		return;
2295 
2296 	desired_event = (1 << (event % 32));
2297 
2298 	if (event < 32)
2299 		sc->event_masks[0] &= ~desired_event;
2300 	else if (event < 64)
2301 		sc->event_masks[1] &= ~desired_event;
2302 	else if (event < 96)
2303 		sc->event_masks[2] &= ~desired_event;
2304 	else if (event < 128)
2305 		sc->event_masks[3] &= ~desired_event;
2306 }
2307 
2308 static void mpi3mr_set_events_mask(struct mpi3mr_softc *sc)
2309 {
2310 	int i;
2311 	for (i = 0; i < MPI3_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2312 		sc->event_masks[i] = -1;
2313 
2314         mpi3mr_unmask_events(sc, MPI3_EVENT_DEVICE_ADDED);
2315         mpi3mr_unmask_events(sc, MPI3_EVENT_DEVICE_INFO_CHANGED);
2316         mpi3mr_unmask_events(sc, MPI3_EVENT_DEVICE_STATUS_CHANGE);
2317 
2318         mpi3mr_unmask_events(sc, MPI3_EVENT_ENCL_DEVICE_STATUS_CHANGE);
2319 
2320         mpi3mr_unmask_events(sc, MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST);
2321         mpi3mr_unmask_events(sc, MPI3_EVENT_SAS_DISCOVERY);
2322         mpi3mr_unmask_events(sc, MPI3_EVENT_SAS_DEVICE_DISCOVERY_ERROR);
2323         mpi3mr_unmask_events(sc, MPI3_EVENT_SAS_BROADCAST_PRIMITIVE);
2324 
2325         mpi3mr_unmask_events(sc, MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST);
2326         mpi3mr_unmask_events(sc, MPI3_EVENT_PCIE_ENUMERATION);
2327 
2328         mpi3mr_unmask_events(sc, MPI3_EVENT_PREPARE_FOR_RESET);
2329         mpi3mr_unmask_events(sc, MPI3_EVENT_CABLE_MGMT);
2330         mpi3mr_unmask_events(sc, MPI3_EVENT_ENERGY_PACK_CHANGE);
2331 }
2332 
2333 /**
2334  * mpi3mr_issue_event_notification - Send event notification
2335  * @sc: Adapter instance reference
2336  *
2337  * Issue event notification MPI request through admin queue and
2338  * wait for the completion of it or time out.
2339  *
2340  * Return: 0 on success, non-zero on failures.
2341  */
2342 int mpi3mr_issue_event_notification(struct mpi3mr_softc *sc)
2343 {
2344 	Mpi3EventNotificationRequest_t evtnotify_req;
2345 	int retval = 0;
2346 	U8 i;
2347 
2348 	memset(&evtnotify_req, 0, sizeof(evtnotify_req));
2349 	mtx_lock(&sc->init_cmds.completion.lock);
2350 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
2351 		retval = -1;
2352 		printf(IOCNAME "Issue EvtNotify: Init command is in use\n",
2353 		    sc->name);
2354 		mtx_unlock(&sc->init_cmds.completion.lock);
2355 		goto out;
2356 	}
2357 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
2358 	sc->init_cmds.is_waiting = 1;
2359 	sc->init_cmds.callback = NULL;
2360 	evtnotify_req.HostTag = (MPI3MR_HOSTTAG_INITCMDS);
2361 	evtnotify_req.Function = MPI3_FUNCTION_EVENT_NOTIFICATION;
2362 	for (i = 0; i < MPI3_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2363 		evtnotify_req.EventMasks[i] =
2364 		    (sc->event_masks[i]);
2365 	init_completion(&sc->init_cmds.completion);
2366 	retval = mpi3mr_submit_admin_cmd(sc, &evtnotify_req,
2367 	    sizeof(evtnotify_req));
2368 	if (retval) {
2369 		printf(IOCNAME "Issue EvtNotify: Admin Post failed\n",
2370 		    sc->name);
2371 		goto out_unlock;
2372 	}
2373 
2374 	poll_for_command_completion(sc,
2375 				    &sc->init_cmds,
2376 				    (MPI3MR_INTADMCMD_TIMEOUT));
2377 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
2378 		printf(IOCNAME "Issue EvtNotify: command timed out\n",
2379 		    sc->name);
2380 		mpi3mr_check_rh_fault_ioc(sc,
2381 		    MPI3MR_RESET_FROM_EVTNOTIFY_TIMEOUT);
2382 		retval = -1;
2383 		goto out_unlock;
2384 	}
2385 
2386 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
2387 	     != MPI3_IOCSTATUS_SUCCESS ) {
2388 		printf(IOCNAME "Issue EvtNotify: Failed IOCStatus(0x%04x) "
2389 		    " Loginfo(0x%08x) \n" , sc->name,
2390 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
2391 		    sc->init_cmds.ioc_loginfo);
2392 		retval = -1;
2393 		goto out_unlock;
2394 	}
2395 
2396 out_unlock:
2397 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
2398 	mtx_unlock(&sc->init_cmds.completion.lock);
2399 
2400 out:
2401 	return retval;
2402 }
2403 
2404 int
2405 mpi3mr_register_events(struct mpi3mr_softc *sc)
2406 {
2407 	int error;
2408 
2409 	mpi3mr_set_events_mask(sc);
2410 
2411 	error = mpi3mr_issue_event_notification(sc);
2412 
2413 	if (error) {
2414 		printf(IOCNAME "Failed to issue event notification %d\n",
2415 		    sc->name, error);
2416 	}
2417 
2418 	return error;
2419 }
2420 
2421 /**
2422  * mpi3mr_process_event_ack - Process event acknowledgment
2423  * @sc: Adapter instance reference
2424  * @event: MPI3 event ID
2425  * @event_ctx: Event context
2426  *
2427  * Send event acknowledgement through admin queue and wait for
2428  * it to complete.
2429  *
2430  * Return: 0 on success, non-zero on failures.
2431  */
2432 int mpi3mr_process_event_ack(struct mpi3mr_softc *sc, U8 event,
2433 	U32 event_ctx)
2434 {
2435 	Mpi3EventAckRequest_t evtack_req;
2436 	int retval = 0;
2437 
2438 	memset(&evtack_req, 0, sizeof(evtack_req));
2439 	mtx_lock(&sc->init_cmds.completion.lock);
2440 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
2441 		retval = -1;
2442 		printf(IOCNAME "Issue EvtAck: Init command is in use\n",
2443 		    sc->name);
2444 		mtx_unlock(&sc->init_cmds.completion.lock);
2445 		goto out;
2446 	}
2447 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
2448 	sc->init_cmds.is_waiting = 1;
2449 	sc->init_cmds.callback = NULL;
2450 	evtack_req.HostTag = htole16(MPI3MR_HOSTTAG_INITCMDS);
2451 	evtack_req.Function = MPI3_FUNCTION_EVENT_ACK;
2452 	evtack_req.Event = event;
2453 	evtack_req.EventContext = htole32(event_ctx);
2454 
2455 	init_completion(&sc->init_cmds.completion);
2456 	retval = mpi3mr_submit_admin_cmd(sc, &evtack_req,
2457 	    sizeof(evtack_req));
2458 	if (retval) {
2459 		printf(IOCNAME "Issue EvtAck: Admin Post failed\n",
2460 		    sc->name);
2461 		goto out_unlock;
2462 	}
2463 
2464 	wait_for_completion_timeout(&sc->init_cmds.completion,
2465 	    (MPI3MR_INTADMCMD_TIMEOUT));
2466 	if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
2467 		printf(IOCNAME "Issue EvtAck: command timed out\n",
2468 		    sc->name);
2469 		retval = -1;
2470 		goto out_unlock;
2471 	}
2472 
2473 	if ((sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
2474 	     != MPI3_IOCSTATUS_SUCCESS ) {
2475 		printf(IOCNAME "Issue EvtAck: Failed IOCStatus(0x%04x) "
2476 		    " Loginfo(0x%08x) \n" , sc->name,
2477 		    (sc->init_cmds.ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
2478 		    sc->init_cmds.ioc_loginfo);
2479 		retval = -1;
2480 		goto out_unlock;
2481 	}
2482 
2483 out_unlock:
2484 	sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
2485 	mtx_unlock(&sc->init_cmds.completion.lock);
2486 
2487 out:
2488 	return retval;
2489 }
2490 
2491 
2492 static int mpi3mr_alloc_chain_bufs(struct mpi3mr_softc *sc)
2493 {
2494 	int retval = 0;
2495 	U32 sz, i;
2496 	U16 num_chains;
2497 
2498 	num_chains = sc->max_host_ios;
2499 
2500 	sc->chain_buf_count = num_chains;
2501 	sz = sizeof(struct mpi3mr_chain) * num_chains;
2502 
2503 	sc->chain_sgl_list = malloc(sz, M_MPI3MR, M_NOWAIT | M_ZERO);
2504 
2505 	if (!sc->chain_sgl_list) {
2506 		printf(IOCNAME "Cannot allocate memory for chain SGL list\n",
2507 		    sc->name);
2508 		retval = -1;
2509 		goto out_failed;
2510 	}
2511 
2512 	sz = MPI3MR_CHAINSGE_SIZE;
2513 
2514         if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,  /* parent */
2515 				4096, 0,		/* algnmnt, boundary */
2516 				sc->dma_loaddr,		/* lowaddr */
2517 				BUS_SPACE_MAXADDR,	/* highaddr */
2518 				NULL, NULL,		/* filter, filterarg */
2519                                 sz,			/* maxsize */
2520                                 1,			/* nsegments */
2521                                 sz,			/* maxsegsize */
2522                                 0,			/* flags */
2523                                 NULL, NULL,		/* lockfunc, lockarg */
2524                                 &sc->chain_sgl_list_tag)) {
2525 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate Chain buffer DMA tag\n");
2526 		return (ENOMEM);
2527         }
2528 
2529 	for (i = 0; i < num_chains; i++) {
2530 		if (bus_dmamem_alloc(sc->chain_sgl_list_tag, (void **)&sc->chain_sgl_list[i].buf,
2531 		    BUS_DMA_NOWAIT, &sc->chain_sgl_list[i].buf_dmamap)) {
2532 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Func: %s line: %d  DMA mem alloc failed\n",
2533 				__func__, __LINE__);
2534 			return (ENOMEM);
2535 		}
2536 
2537 		bzero(sc->chain_sgl_list[i].buf, sz);
2538 		bus_dmamap_load(sc->chain_sgl_list_tag, sc->chain_sgl_list[i].buf_dmamap, sc->chain_sgl_list[i].buf, sz,
2539 		    mpi3mr_memaddr_cb, &sc->chain_sgl_list[i].buf_phys, BUS_DMA_NOWAIT);
2540 		mpi3mr_dprint(sc, MPI3MR_XINFO, "Func: %s line: %d phys addr= %#016jx size= %d\n",
2541 		    __func__, __LINE__, (uintmax_t)sc->chain_sgl_list[i].buf_phys, sz);
2542 	}
2543 
2544 	sc->chain_bitmap_sz = MPI3MR_DIV_ROUND_UP(num_chains, 8);
2545 
2546 	sc->chain_bitmap = malloc(sc->chain_bitmap_sz, M_MPI3MR, M_NOWAIT | M_ZERO);
2547 	if (!sc->chain_bitmap) {
2548 		mpi3mr_dprint(sc, MPI3MR_INFO, "Cannot alloc memory for chain bitmap\n");
2549 		retval = -1;
2550 		goto out_failed;
2551 	}
2552 	return retval;
2553 
2554 out_failed:
2555 	for (i = 0; i < num_chains; i++) {
2556 		if (sc->chain_sgl_list[i].buf_phys != 0)
2557 			bus_dmamap_unload(sc->chain_sgl_list_tag, sc->chain_sgl_list[i].buf_dmamap);
2558 		if (sc->chain_sgl_list[i].buf != NULL)
2559 			bus_dmamem_free(sc->chain_sgl_list_tag, sc->chain_sgl_list[i].buf, sc->chain_sgl_list[i].buf_dmamap);
2560 	}
2561 	if (sc->chain_sgl_list_tag != NULL)
2562 		bus_dma_tag_destroy(sc->chain_sgl_list_tag);
2563 	return retval;
2564 }
2565 
2566 static int mpi3mr_pel_alloc(struct mpi3mr_softc *sc)
2567 {
2568 	int retval = 0;
2569 
2570 	if (!sc->pel_cmds.reply) {
2571 		sc->pel_cmds.reply = malloc(sc->reply_sz, M_MPI3MR, M_NOWAIT | M_ZERO);
2572 		if (!sc->pel_cmds.reply) {
2573 			printf(IOCNAME "Cannot allocate memory for pel_cmds.reply\n",
2574 			    sc->name);
2575 			goto out_failed;
2576 		}
2577 	}
2578 
2579 	if (!sc->pel_abort_cmd.reply) {
2580 		sc->pel_abort_cmd.reply = malloc(sc->reply_sz, M_MPI3MR, M_NOWAIT | M_ZERO);
2581 		if (!sc->pel_abort_cmd.reply) {
2582 			printf(IOCNAME "Cannot allocate memory for pel_abort_cmd.reply\n",
2583 			    sc->name);
2584 			goto out_failed;
2585 		}
2586 	}
2587 
2588 	if (!sc->pel_seq_number) {
2589 		sc->pel_seq_number_sz = sizeof(Mpi3PELSeq_t);
2590 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,   /* parent */
2591 				 4, 0,                           /* alignment, boundary */
2592 				 sc->dma_loaddr,	         /* lowaddr */
2593 				 BUS_SPACE_MAXADDR,		 /* highaddr */
2594 				 NULL, NULL,                     /* filter, filterarg */
2595 				 sc->pel_seq_number_sz,		 /* maxsize */
2596 				 1,                              /* nsegments */
2597 				 sc->pel_seq_number_sz,          /* maxsegsize */
2598 				 0,                              /* flags */
2599 				 NULL, NULL,                     /* lockfunc, lockarg */
2600 				 &sc->pel_seq_num_dmatag)) {
2601 			 mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot create PEL seq number dma memory tag\n");
2602 			 retval = -ENOMEM;
2603 			 goto out_failed;
2604 		}
2605 
2606 		if (bus_dmamem_alloc(sc->pel_seq_num_dmatag, (void **)&sc->pel_seq_number,
2607 		    BUS_DMA_NOWAIT, &sc->pel_seq_num_dmamap)) {
2608 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate PEL seq number kernel buffer dma memory\n");
2609 			retval = -ENOMEM;
2610 			goto out_failed;
2611 		}
2612 
2613 		bzero(sc->pel_seq_number, sc->pel_seq_number_sz);
2614 
2615 		bus_dmamap_load(sc->pel_seq_num_dmatag, sc->pel_seq_num_dmamap, sc->pel_seq_number,
2616 		    sc->pel_seq_number_sz, mpi3mr_memaddr_cb, &sc->pel_seq_number_dma, BUS_DMA_NOWAIT);
2617 
2618 		if (!sc->pel_seq_number) {
2619 			printf(IOCNAME "%s:%d Cannot load PEL seq number dma memory for size: %d\n", sc->name,
2620 				__func__, __LINE__, sc->pel_seq_number_sz);
2621 			retval = -ENOMEM;
2622 			goto out_failed;
2623 		}
2624 	}
2625 
2626 out_failed:
2627 	return retval;
2628 }
2629 
2630 /**
2631  * mpi3mr_validate_fw_update - validate IOCFacts post adapter reset
2632  * @sc: Adapter instance reference
2633  *
2634  * Return zero if the new IOCFacts is compatible with previous values
2635  * else return appropriate error
2636  */
2637 static int
2638 mpi3mr_validate_fw_update(struct mpi3mr_softc *sc)
2639 {
2640 	U16 dev_handle_bitmap_sz;
2641 	U8 *removepend_bitmap;
2642 
2643 	if (sc->facts.reply_sz > sc->reply_sz) {
2644 		mpi3mr_dprint(sc, MPI3MR_ERROR,
2645 		    "Cannot increase reply size from %d to %d\n",
2646 		    sc->reply_sz, sc->reply_sz);
2647 		return -EPERM;
2648 	}
2649 
2650 	if (sc->num_io_throttle_group != sc->facts.max_io_throttle_group) {
2651 		mpi3mr_dprint(sc, MPI3MR_ERROR,
2652 		    "max io throttle group doesn't match old(%d), new(%d)\n",
2653 		    sc->num_io_throttle_group,
2654 		    sc->facts.max_io_throttle_group);
2655 		return -EPERM;
2656 	}
2657 
2658 	if (sc->facts.max_op_reply_q < sc->num_queues) {
2659 		mpi3mr_dprint(sc, MPI3MR_ERROR,
2660 		    "Cannot reduce number of operational reply queues from %d to %d\n",
2661 		    sc->num_queues,
2662 		    sc->facts.max_op_reply_q);
2663 		return -EPERM;
2664 	}
2665 
2666 	if (sc->facts.max_op_req_q < sc->num_queues) {
2667 		mpi3mr_dprint(sc, MPI3MR_ERROR,
2668 		    "Cannot reduce number of operational request queues from %d to %d\n",
2669 		    sc->num_queues, sc->facts.max_op_req_q);
2670 		return -EPERM;
2671 	}
2672 
2673 	dev_handle_bitmap_sz = MPI3MR_DIV_ROUND_UP(sc->facts.max_devhandle, 8);
2674 
2675 	if (dev_handle_bitmap_sz > sc->dev_handle_bitmap_sz) {
2676 		removepend_bitmap = realloc(sc->removepend_bitmap,
2677 		    dev_handle_bitmap_sz, M_MPI3MR, M_NOWAIT);
2678 
2679 		if (!removepend_bitmap) {
2680 			mpi3mr_dprint(sc, MPI3MR_ERROR,
2681 			    "failed to increase removepend_bitmap sz from: %d to %d\n",
2682 			    sc->dev_handle_bitmap_sz, dev_handle_bitmap_sz);
2683 			return -ENOMEM;
2684 		}
2685 
2686 		memset(removepend_bitmap + sc->dev_handle_bitmap_sz, 0,
2687 		    dev_handle_bitmap_sz - sc->dev_handle_bitmap_sz);
2688 		sc->removepend_bitmap = removepend_bitmap;
2689 		mpi3mr_dprint(sc, MPI3MR_INFO,
2690 		    "increased dev_handle_bitmap_sz from %d to %d\n",
2691 		    sc->dev_handle_bitmap_sz, dev_handle_bitmap_sz);
2692 		sc->dev_handle_bitmap_sz = dev_handle_bitmap_sz;
2693 	}
2694 
2695 	return 0;
2696 }
2697 
2698 /*
2699  * mpi3mr_initialize_ioc - Controller initialization
2700  * @dev: pointer to device struct
2701  *
2702  * This function allocates the controller wide resources and brings
2703  * the controller to operational state
2704  *
2705  * Return: 0 on success and proper error codes on failure
2706  */
2707 int mpi3mr_initialize_ioc(struct mpi3mr_softc *sc, U8 init_type)
2708 {
2709 	int retval = 0;
2710 	enum mpi3mr_iocstate ioc_state;
2711 	U64 ioc_info;
2712 	U32 ioc_status, ioc_control, i, timeout;
2713 	Mpi3IOCFactsData_t facts_data;
2714 	char str[32];
2715 	U32 size;
2716 
2717 	sc->cpu_count = mp_ncpus;
2718 
2719 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
2720 	ioc_control = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
2721 	ioc_info = mpi3mr_regread64(sc, MPI3_SYSIF_IOC_INFO_LOW_OFFSET);
2722 
2723 	mpi3mr_dprint(sc, MPI3MR_INFO, "SOD ioc_status: 0x%x ioc_control: 0x%x "
2724 	    "ioc_info: 0x%lx\n", ioc_status, ioc_control, ioc_info);
2725 
2726         /*The timeout value is in 2sec unit, changing it to seconds*/
2727 	sc->ready_timeout =
2728                 ((ioc_info & MPI3_SYSIF_IOC_INFO_LOW_TIMEOUT_MASK) >>
2729                     MPI3_SYSIF_IOC_INFO_LOW_TIMEOUT_SHIFT) * 2;
2730 
2731 	ioc_state = mpi3mr_get_iocstate(sc);
2732 
2733 	mpi3mr_dprint(sc, MPI3MR_INFO, "IOC state: %s   IOC ready timeout: %d\n",
2734 	    mpi3mr_iocstate_name(ioc_state), sc->ready_timeout);
2735 
2736 	if (ioc_state == MRIOC_STATE_BECOMING_READY ||
2737 	    ioc_state == MRIOC_STATE_RESET_REQUESTED) {
2738 		timeout = sc->ready_timeout * 10;
2739 		do {
2740 			DELAY(1000 * 100);
2741 		} while (--timeout);
2742 
2743 		ioc_state = mpi3mr_get_iocstate(sc);
2744 		mpi3mr_dprint(sc, MPI3MR_INFO,
2745 			"IOC in %s state after waiting for reset time\n",
2746 			mpi3mr_iocstate_name(ioc_state));
2747 	}
2748 
2749 	if (ioc_state == MRIOC_STATE_READY) {
2750                 retval = mpi3mr_mur_ioc(sc, MPI3MR_RESET_FROM_BRINGUP);
2751                 if (retval) {
2752                         mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to MU reset IOC, error 0x%x\n",
2753                                 retval);
2754                 }
2755                 ioc_state = mpi3mr_get_iocstate(sc);
2756         }
2757 
2758         if (ioc_state != MRIOC_STATE_RESET) {
2759                 mpi3mr_print_fault_info(sc);
2760 		 mpi3mr_dprint(sc, MPI3MR_ERROR, "issuing soft reset to bring to reset state\n");
2761                  retval = mpi3mr_issue_reset(sc,
2762                      MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET,
2763                      MPI3MR_RESET_FROM_BRINGUP);
2764                 if (retval) {
2765                         mpi3mr_dprint(sc, MPI3MR_ERROR,
2766                             "%s :Failed to soft reset IOC, error 0x%d\n",
2767                             __func__, retval);
2768                         goto out_failed;
2769                 }
2770         }
2771 
2772 	ioc_state = mpi3mr_get_iocstate(sc);
2773 
2774         if (ioc_state != MRIOC_STATE_RESET) {
2775 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot bring IOC to reset state\n");
2776 		goto out_failed;
2777         }
2778 
2779 	retval = mpi3mr_setup_admin_qpair(sc);
2780 	if (retval) {
2781 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to setup Admin queues, error 0x%x\n",
2782 		    retval);
2783 		goto out_failed;
2784 	}
2785 
2786 	retval = mpi3mr_bring_ioc_ready(sc);
2787 	if (retval) {
2788 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to bring IOC ready, error 0x%x\n",
2789 		    retval);
2790 		goto out_failed;
2791 	}
2792 
2793 	if (init_type == MPI3MR_INIT_TYPE_INIT) {
2794 		retval = mpi3mr_alloc_interrupts(sc, 1);
2795 		if (retval) {
2796 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to allocate interrupts, error 0x%x\n",
2797 			    retval);
2798 			goto out_failed;
2799 		}
2800 
2801 		retval = mpi3mr_setup_irqs(sc);
2802 		if (retval) {
2803 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to setup ISR, error 0x%x\n",
2804 			    retval);
2805 			goto out_failed;
2806 		}
2807 	}
2808 
2809 	mpi3mr_enable_interrupts(sc);
2810 
2811 	if (init_type == MPI3MR_INIT_TYPE_INIT) {
2812 		mtx_init(&sc->mpi3mr_mtx, "SIM lock", NULL, MTX_DEF);
2813 		mtx_init(&sc->io_lock, "IO lock", NULL, MTX_DEF);
2814 		mtx_init(&sc->admin_req_lock, "Admin Request Queue lock", NULL, MTX_SPIN);
2815 		mtx_init(&sc->reply_free_q_lock, "Reply free Queue lock", NULL, MTX_SPIN);
2816 		mtx_init(&sc->sense_buf_q_lock, "Sense buffer Queue lock", NULL, MTX_SPIN);
2817 		mtx_init(&sc->chain_buf_lock, "Chain buffer lock", NULL, MTX_SPIN);
2818 		mtx_init(&sc->cmd_pool_lock, "Command pool lock", NULL, MTX_DEF);
2819 		mtx_init(&sc->fwevt_lock, "Firmware Event lock", NULL, MTX_DEF);
2820 		mtx_init(&sc->target_lock, "Target lock", NULL, MTX_SPIN);
2821 		mtx_init(&sc->reset_mutex, "Reset lock", NULL, MTX_DEF);
2822 
2823 		mtx_init(&sc->init_cmds.completion.lock, "Init commands lock", NULL, MTX_DEF);
2824 		sc->init_cmds.reply = NULL;
2825 		sc->init_cmds.state = MPI3MR_CMD_NOTUSED;
2826 		sc->init_cmds.dev_handle = MPI3MR_INVALID_DEV_HANDLE;
2827 		sc->init_cmds.host_tag = MPI3MR_HOSTTAG_INITCMDS;
2828 
2829 		mtx_init(&sc->ioctl_cmds.completion.lock, "IOCTL commands lock", NULL, MTX_DEF);
2830 		sc->ioctl_cmds.reply = NULL;
2831 		sc->ioctl_cmds.state = MPI3MR_CMD_NOTUSED;
2832 		sc->ioctl_cmds.dev_handle = MPI3MR_INVALID_DEV_HANDLE;
2833 		sc->ioctl_cmds.host_tag = MPI3MR_HOSTTAG_IOCTLCMDS;
2834 
2835 		mtx_init(&sc->pel_abort_cmd.completion.lock, "PEL Abort command lock", NULL, MTX_DEF);
2836 		sc->pel_abort_cmd.reply = NULL;
2837 		sc->pel_abort_cmd.state = MPI3MR_CMD_NOTUSED;
2838 		sc->pel_abort_cmd.dev_handle = MPI3MR_INVALID_DEV_HANDLE;
2839 		sc->pel_abort_cmd.host_tag = MPI3MR_HOSTTAG_PELABORT;
2840 
2841 		mtx_init(&sc->host_tm_cmds.completion.lock, "TM commands lock", NULL, MTX_DEF);
2842 		sc->host_tm_cmds.reply = NULL;
2843 		sc->host_tm_cmds.state = MPI3MR_CMD_NOTUSED;
2844 		sc->host_tm_cmds.dev_handle = MPI3MR_INVALID_DEV_HANDLE;
2845 		sc->host_tm_cmds.host_tag = MPI3MR_HOSTTAG_TMS;
2846 
2847 		TAILQ_INIT(&sc->cmd_list_head);
2848 		TAILQ_INIT(&sc->event_list);
2849 		TAILQ_INIT(&sc->delayed_rmhs_list);
2850 		TAILQ_INIT(&sc->delayed_evtack_cmds_list);
2851 
2852 		for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++) {
2853 			snprintf(str, 32, "Dev REMHS commands lock[%d]", i);
2854 			mtx_init(&sc->dev_rmhs_cmds[i].completion.lock, str, NULL, MTX_DEF);
2855 			sc->dev_rmhs_cmds[i].reply = NULL;
2856 			sc->dev_rmhs_cmds[i].state = MPI3MR_CMD_NOTUSED;
2857 			sc->dev_rmhs_cmds[i].dev_handle = MPI3MR_INVALID_DEV_HANDLE;
2858 			sc->dev_rmhs_cmds[i].host_tag = MPI3MR_HOSTTAG_DEVRMCMD_MIN
2859 							    + i;
2860 		}
2861 	}
2862 
2863 	retval = mpi3mr_issue_iocfacts(sc, &facts_data);
2864 	if (retval) {
2865 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to Issue IOC Facts, retval: 0x%x\n",
2866 		    retval);
2867 		goto out_failed;
2868 	}
2869 
2870 	retval = mpi3mr_process_factsdata(sc, &facts_data);
2871 	if (retval) {
2872 		mpi3mr_dprint(sc, MPI3MR_ERROR, "IOC Facts data processing failedi, retval: 0x%x\n",
2873 		    retval);
2874 		goto out_failed;
2875 	}
2876 
2877 	sc->num_io_throttle_group = sc->facts.max_io_throttle_group;
2878 	mpi3mr_atomic_set(&sc->pend_large_data_sz, 0);
2879 
2880 	if (init_type == MPI3MR_INIT_TYPE_RESET) {
2881 		retval = mpi3mr_validate_fw_update(sc);
2882 		if (retval)
2883 			goto out_failed;
2884 	} else {
2885 		sc->reply_sz = sc->facts.reply_sz;
2886 	}
2887 
2888 	mpi3mr_display_ioc_info(sc);
2889 
2890 	retval = mpi3mr_reply_alloc(sc);
2891 	if (retval) {
2892 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to allocated reply and sense buffers, retval: 0x%x\n",
2893 		    retval);
2894 		goto out_failed;
2895 	}
2896 
2897 	if (init_type == MPI3MR_INIT_TYPE_INIT) {
2898 		retval = mpi3mr_alloc_chain_bufs(sc);
2899 		if (retval) {
2900 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to allocated chain buffers, retval: 0x%x\n",
2901 			    retval);
2902 			goto out_failed;
2903 		}
2904 	}
2905 
2906 	retval = mpi3mr_issue_iocinit(sc);
2907 	if (retval) {
2908 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to Issue IOC Init, retval: 0x%x\n",
2909 		    retval);
2910 		goto out_failed;
2911 	}
2912 
2913 	mpi3mr_print_fw_pkg_ver(sc);
2914 
2915 	sc->reply_free_q_host_index = sc->num_reply_bufs;
2916 	mpi3mr_regwrite(sc, MPI3_SYSIF_REPLY_FREE_HOST_INDEX_OFFSET,
2917 		sc->reply_free_q_host_index);
2918 
2919 	sc->sense_buf_q_host_index = sc->num_sense_bufs;
2920 
2921 	mpi3mr_regwrite(sc, MPI3_SYSIF_SENSE_BUF_FREE_HOST_INDEX_OFFSET,
2922 		sc->sense_buf_q_host_index);
2923 
2924 	if (init_type == MPI3MR_INIT_TYPE_INIT) {
2925 		retval = mpi3mr_alloc_interrupts(sc, 0);
2926 		if (retval) {
2927 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to allocate interrupts, retval: 0x%x\n",
2928 			    retval);
2929 			goto out_failed;
2930 		}
2931 
2932 		retval = mpi3mr_setup_irqs(sc);
2933 		if (retval) {
2934 			printf(IOCNAME "Failed to setup ISR, error: 0x%x\n",
2935 			    sc->name, retval);
2936 			goto out_failed;
2937 		}
2938 
2939 		mpi3mr_enable_interrupts(sc);
2940 
2941 	} else
2942 		mpi3mr_enable_interrupts(sc);
2943 
2944 	retval = mpi3mr_create_op_queues(sc);
2945 
2946 	if (retval) {
2947 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to create operational queues, error: %d\n",
2948 		    retval);
2949 		goto out_failed;
2950 	}
2951 
2952 	if (!sc->throttle_groups && sc->num_io_throttle_group) {
2953 		mpi3mr_dprint(sc, MPI3MR_ERROR, "allocating memory for throttle groups\n");
2954 		size = sizeof(struct mpi3mr_throttle_group_info);
2955 		sc->throttle_groups = (struct mpi3mr_throttle_group_info *)
2956 					  malloc(sc->num_io_throttle_group *
2957 					      size, M_MPI3MR, M_NOWAIT | M_ZERO);
2958 		if (!sc->throttle_groups)
2959 			goto out_failed;
2960 	}
2961 
2962 	if (init_type == MPI3MR_INIT_TYPE_RESET) {
2963 		mpi3mr_dprint(sc, MPI3MR_INFO, "Re-register events\n");
2964 		retval = mpi3mr_register_events(sc);
2965 		if (retval) {
2966 			mpi3mr_dprint(sc, MPI3MR_INFO, "Failed to re-register events, retval: 0x%x\n",
2967 			    retval);
2968 			goto out_failed;
2969 		}
2970 
2971 		mpi3mr_dprint(sc, MPI3MR_INFO, "Issuing Port Enable\n");
2972 		retval = mpi3mr_issue_port_enable(sc, 0);
2973 		if (retval) {
2974 			mpi3mr_dprint(sc, MPI3MR_INFO, "Failed to issue port enable, retval: 0x%x\n",
2975 			    retval);
2976 			goto out_failed;
2977 		}
2978 	}
2979 	retval = mpi3mr_pel_alloc(sc);
2980 	if (retval) {
2981 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to allocate memory for PEL, retval: 0x%x\n",
2982 		    retval);
2983 		goto out_failed;
2984 	}
2985 
2986 	return retval;
2987 
2988 out_failed:
2989 	retval = -1;
2990 	return retval;
2991 }
2992 
2993 static void mpi3mr_port_enable_complete(struct mpi3mr_softc *sc,
2994     struct mpi3mr_drvr_cmd *drvrcmd)
2995 {
2996 	drvrcmd->state = MPI3MR_CMD_NOTUSED;
2997 	drvrcmd->callback = NULL;
2998 	printf(IOCNAME "Completing Port Enable Request\n", sc->name);
2999 	sc->mpi3mr_flags |= MPI3MR_FLAGS_PORT_ENABLE_DONE;
3000 	mpi3mr_startup_decrement(sc->cam_sc);
3001 }
3002 
3003 int mpi3mr_issue_port_enable(struct mpi3mr_softc *sc, U8 async)
3004 {
3005 	Mpi3PortEnableRequest_t pe_req;
3006 	int retval = 0;
3007 
3008 	memset(&pe_req, 0, sizeof(pe_req));
3009 	mtx_lock(&sc->init_cmds.completion.lock);
3010 	if (sc->init_cmds.state & MPI3MR_CMD_PENDING) {
3011 		retval = -1;
3012 		printf(IOCNAME "Issue PortEnable: Init command is in use\n", sc->name);
3013 		mtx_unlock(&sc->init_cmds.completion.lock);
3014 		goto out;
3015 	}
3016 
3017 	sc->init_cmds.state = MPI3MR_CMD_PENDING;
3018 
3019 	if (async) {
3020 		sc->init_cmds.is_waiting = 0;
3021 		sc->init_cmds.callback = mpi3mr_port_enable_complete;
3022 	} else {
3023 		sc->init_cmds.is_waiting = 1;
3024 		sc->init_cmds.callback = NULL;
3025 		init_completion(&sc->init_cmds.completion);
3026 	}
3027 	pe_req.HostTag = MPI3MR_HOSTTAG_INITCMDS;
3028 	pe_req.Function = MPI3_FUNCTION_PORT_ENABLE;
3029 
3030 	printf(IOCNAME "Sending Port Enable Request\n", sc->name);
3031 	retval = mpi3mr_submit_admin_cmd(sc, &pe_req, sizeof(pe_req));
3032 	if (retval) {
3033 		printf(IOCNAME "Issue PortEnable: Admin Post failed\n",
3034 		    sc->name);
3035 		goto out_unlock;
3036 	}
3037 
3038 	if (!async) {
3039 		wait_for_completion_timeout(&sc->init_cmds.completion,
3040 		    MPI3MR_PORTENABLE_TIMEOUT);
3041 		if (!(sc->init_cmds.state & MPI3MR_CMD_COMPLETE)) {
3042 			printf(IOCNAME "Issue PortEnable: command timed out\n",
3043 			    sc->name);
3044 			retval = -1;
3045 			mpi3mr_check_rh_fault_ioc(sc, MPI3MR_RESET_FROM_PE_TIMEOUT);
3046 			goto out_unlock;
3047 		}
3048 		mpi3mr_port_enable_complete(sc, &sc->init_cmds);
3049 	}
3050 out_unlock:
3051 	mtx_unlock(&sc->init_cmds.completion.lock);
3052 
3053 out:
3054 	return retval;
3055 }
3056 
3057 void
3058 mpi3mr_watchdog_thread(void *arg)
3059 {
3060 	struct mpi3mr_softc *sc;
3061 	enum mpi3mr_iocstate ioc_state;
3062 	U32 fault, host_diagnostic, ioc_status;
3063 
3064 	sc = (struct mpi3mr_softc *)arg;
3065 
3066 	mpi3mr_dprint(sc, MPI3MR_XINFO, "%s\n", __func__);
3067 
3068 	sc->watchdog_thread_active = 1;
3069 	mtx_lock(&sc->reset_mutex);
3070 	for (;;) {
3071 		if (sc->mpi3mr_flags & MPI3MR_FLAGS_SHUTDOWN ||
3072 		    (sc->unrecoverable == 1)) {
3073 			mpi3mr_dprint(sc, MPI3MR_INFO,
3074 			    "Exit due to %s from %s\n",
3075 			   sc->mpi3mr_flags & MPI3MR_FLAGS_SHUTDOWN ? "Shutdown" :
3076 			    "Hardware critical error", __func__);
3077 			break;
3078 		}
3079 		mtx_unlock(&sc->reset_mutex);
3080 
3081 		if ((sc->prepare_for_reset) &&
3082 		    ((sc->prepare_for_reset_timeout_counter++) >=
3083 		     MPI3MR_PREPARE_FOR_RESET_TIMEOUT)) {
3084 			mpi3mr_soft_reset_handler(sc,
3085 			    MPI3MR_RESET_FROM_CIACTVRST_TIMER, 1);
3086 			goto sleep;
3087 		}
3088 
3089 		ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
3090 
3091 		if (ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY) {
3092 			mpi3mr_soft_reset_handler(sc, MPI3MR_RESET_FROM_FIRMWARE, 0);
3093 			goto sleep;
3094 		}
3095 
3096 		ioc_state = mpi3mr_get_iocstate(sc);
3097 		if (ioc_state == MRIOC_STATE_FAULT) {
3098 			fault = mpi3mr_regread(sc, MPI3_SYSIF_FAULT_OFFSET) &
3099 			    MPI3_SYSIF_FAULT_CODE_MASK;
3100 
3101 			host_diagnostic = mpi3mr_regread(sc, MPI3_SYSIF_HOST_DIAG_OFFSET);
3102 			if (host_diagnostic & MPI3_SYSIF_HOST_DIAG_SAVE_IN_PROGRESS) {
3103 				if (!sc->diagsave_timeout) {
3104 					mpi3mr_print_fault_info(sc);
3105 					mpi3mr_dprint(sc, MPI3MR_INFO,
3106 						"diag save in progress\n");
3107 				}
3108 				if ((sc->diagsave_timeout++) <= MPI3_SYSIF_DIAG_SAVE_TIMEOUT)
3109 					goto sleep;
3110 			}
3111 			mpi3mr_print_fault_info(sc);
3112 			sc->diagsave_timeout = 0;
3113 
3114 			if ((fault == MPI3_SYSIF_FAULT_CODE_POWER_CYCLE_REQUIRED) ||
3115 			    (fault == MPI3_SYSIF_FAULT_CODE_COMPLETE_RESET_NEEDED)) {
3116 				mpi3mr_dprint(sc, MPI3MR_INFO,
3117 				    "Controller requires system power cycle or complete reset is needed,"
3118 				    "fault code: 0x%x. marking controller as unrecoverable\n", fault);
3119 				sc->unrecoverable = 1;
3120 				break;
3121 			}
3122 			if ((fault == MPI3_SYSIF_FAULT_CODE_DIAG_FAULT_RESET)
3123 			    || (fault == MPI3_SYSIF_FAULT_CODE_SOFT_RESET_IN_PROGRESS)
3124 			    || (sc->reset_in_progress))
3125 				break;
3126 			if (fault == MPI3_SYSIF_FAULT_CODE_CI_ACTIVATION_RESET)
3127 				mpi3mr_soft_reset_handler(sc,
3128 				    MPI3MR_RESET_FROM_CIACTIV_FAULT, 0);
3129 			else
3130 				mpi3mr_soft_reset_handler(sc,
3131 				    MPI3MR_RESET_FROM_FAULT_WATCH, 0);
3132 
3133 		}
3134 
3135 		if (sc->reset.type == MPI3MR_TRIGGER_SOFT_RESET) {
3136 			mpi3mr_print_fault_info(sc);
3137 			mpi3mr_soft_reset_handler(sc, sc->reset.reason, 1);
3138 		}
3139 sleep:
3140 		mtx_lock(&sc->reset_mutex);
3141 		/*
3142 		 * Sleep for 1 second if we're not exiting, then loop to top
3143 		 * to poll exit status and hardware health.
3144 		 */
3145 		if ((sc->mpi3mr_flags & MPI3MR_FLAGS_SHUTDOWN) == 0 &&
3146 		    !sc->unrecoverable) {
3147 			msleep(&sc->watchdog_chan, &sc->reset_mutex, PRIBIO,
3148 			    "mpi3mr_watchdog", 1 * hz);
3149 		}
3150 	}
3151 	mtx_unlock(&sc->reset_mutex);
3152 	sc->watchdog_thread_active = 0;
3153 	mpi3mr_kproc_exit(0);
3154 }
3155 
3156 static void mpi3mr_display_event_data(struct mpi3mr_softc *sc,
3157 	Mpi3EventNotificationReply_t *event_rep)
3158 {
3159 	char *desc = NULL;
3160 	U16 event;
3161 
3162 	event = event_rep->Event;
3163 
3164 	switch (event) {
3165 	case MPI3_EVENT_LOG_DATA:
3166 		desc = "Log Data";
3167 		break;
3168 	case MPI3_EVENT_CHANGE:
3169 		desc = "Event Change";
3170 		break;
3171 	case MPI3_EVENT_GPIO_INTERRUPT:
3172 		desc = "GPIO Interrupt";
3173 		break;
3174 	case MPI3_EVENT_CABLE_MGMT:
3175 		desc = "Cable Management";
3176 		break;
3177 	case MPI3_EVENT_ENERGY_PACK_CHANGE:
3178 		desc = "Energy Pack Change";
3179 		break;
3180 	case MPI3_EVENT_DEVICE_ADDED:
3181 	{
3182 		Mpi3DevicePage0_t *event_data =
3183 		    (Mpi3DevicePage0_t *)event_rep->EventData;
3184 		mpi3mr_dprint(sc, MPI3MR_EVENT, "Device Added: Dev=0x%04x Form=0x%x Perst id: 0x%x\n",
3185 			event_data->DevHandle, event_data->DeviceForm, event_data->PersistentID);
3186 		return;
3187 	}
3188 	case MPI3_EVENT_DEVICE_INFO_CHANGED:
3189 	{
3190 		Mpi3DevicePage0_t *event_data =
3191 		    (Mpi3DevicePage0_t *)event_rep->EventData;
3192 		mpi3mr_dprint(sc, MPI3MR_EVENT, "Device Info Changed: Dev=0x%04x Form=0x%x\n",
3193 			event_data->DevHandle, event_data->DeviceForm);
3194 		return;
3195 	}
3196 	case MPI3_EVENT_DEVICE_STATUS_CHANGE:
3197 	{
3198 		Mpi3EventDataDeviceStatusChange_t *event_data =
3199 		    (Mpi3EventDataDeviceStatusChange_t *)event_rep->EventData;
3200 		mpi3mr_dprint(sc, MPI3MR_EVENT, "Device Status Change: Dev=0x%04x RC=0x%x\n",
3201 			event_data->DevHandle, event_data->ReasonCode);
3202 		return;
3203 	}
3204 	case MPI3_EVENT_SAS_DISCOVERY:
3205 	{
3206 		Mpi3EventDataSasDiscovery_t *event_data =
3207 		    (Mpi3EventDataSasDiscovery_t *)event_rep->EventData;
3208 		mpi3mr_dprint(sc, MPI3MR_EVENT, "SAS Discovery: (%s)",
3209 			(event_data->ReasonCode == MPI3_EVENT_SAS_DISC_RC_STARTED) ?
3210 		    "start" : "stop");
3211 		if (event_data->DiscoveryStatus &&
3212 		    (sc->mpi3mr_debug & MPI3MR_EVENT)) {
3213 			printf("discovery_status(0x%08x)",
3214 			    event_data->DiscoveryStatus);
3215 
3216 		}
3217 
3218 		if (sc->mpi3mr_debug & MPI3MR_EVENT)
3219 			printf("\n");
3220 		return;
3221 	}
3222 	case MPI3_EVENT_SAS_BROADCAST_PRIMITIVE:
3223 		desc = "SAS Broadcast Primitive";
3224 		break;
3225 	case MPI3_EVENT_SAS_NOTIFY_PRIMITIVE:
3226 		desc = "SAS Notify Primitive";
3227 		break;
3228 	case MPI3_EVENT_SAS_INIT_DEVICE_STATUS_CHANGE:
3229 		desc = "SAS Init Device Status Change";
3230 		break;
3231 	case MPI3_EVENT_SAS_INIT_TABLE_OVERFLOW:
3232 		desc = "SAS Init Table Overflow";
3233 		break;
3234 	case MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
3235 		desc = "SAS Topology Change List";
3236 		break;
3237 	case MPI3_EVENT_ENCL_DEVICE_STATUS_CHANGE:
3238 		desc = "Enclosure Device Status Change";
3239 		break;
3240 	case MPI3_EVENT_HARD_RESET_RECEIVED:
3241 		desc = "Hard Reset Received";
3242 		break;
3243 	case MPI3_EVENT_SAS_PHY_COUNTER:
3244 		desc = "SAS PHY Counter";
3245 		break;
3246 	case MPI3_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
3247 		desc = "SAS Device Discovery Error";
3248 		break;
3249 	case MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
3250 		desc = "PCIE Topology Change List";
3251 		break;
3252 	case MPI3_EVENT_PCIE_ENUMERATION:
3253 	{
3254 		Mpi3EventDataPcieEnumeration_t *event_data =
3255 			(Mpi3EventDataPcieEnumeration_t *)event_rep->EventData;
3256 		mpi3mr_dprint(sc, MPI3MR_EVENT, "PCIE Enumeration: (%s)",
3257 			(event_data->ReasonCode ==
3258 			    MPI3_EVENT_PCIE_ENUM_RC_STARTED) ? "start" :
3259 			    "stop");
3260 		if (event_data->EnumerationStatus)
3261 			mpi3mr_dprint(sc, MPI3MR_EVENT, "enumeration_status(0x%08x)",
3262 			   event_data->EnumerationStatus);
3263 		if (sc->mpi3mr_debug & MPI3MR_EVENT)
3264 			printf("\n");
3265 		return;
3266 	}
3267 	case MPI3_EVENT_PREPARE_FOR_RESET:
3268 		desc = "Prepare For Reset";
3269 		break;
3270 	}
3271 
3272 	if (!desc)
3273 		return;
3274 
3275 	mpi3mr_dprint(sc, MPI3MR_EVENT, "%s\n", desc);
3276 }
3277 
3278 struct mpi3mr_target *
3279 mpi3mr_find_target_by_per_id(struct mpi3mr_cam_softc *cam_sc,
3280     uint16_t per_id)
3281 {
3282 	struct mpi3mr_target *target = NULL;
3283 
3284 	mtx_lock_spin(&cam_sc->sc->target_lock);
3285 	TAILQ_FOREACH(target, &cam_sc->tgt_list, tgt_next) {
3286 		if (target->per_id == per_id)
3287 			break;
3288 	}
3289 
3290 	mtx_unlock_spin(&cam_sc->sc->target_lock);
3291 	return target;
3292 }
3293 
3294 struct mpi3mr_target *
3295 mpi3mr_find_target_by_dev_handle(struct mpi3mr_cam_softc *cam_sc,
3296     uint16_t handle)
3297 {
3298 	struct mpi3mr_target *target = NULL;
3299 
3300 	mtx_lock_spin(&cam_sc->sc->target_lock);
3301 	TAILQ_FOREACH(target, &cam_sc->tgt_list, tgt_next) {
3302 		if (target->dev_handle == handle)
3303 			break;
3304 
3305 	}
3306 	mtx_unlock_spin(&cam_sc->sc->target_lock);
3307 	return target;
3308 }
3309 
3310 void mpi3mr_update_device(struct mpi3mr_softc *sc,
3311     struct mpi3mr_target *tgtdev, Mpi3DevicePage0_t *dev_pg0,
3312     bool is_added)
3313 {
3314 	U16 flags = 0;
3315 
3316 	tgtdev->per_id = (dev_pg0->PersistentID);
3317 	tgtdev->dev_handle = (dev_pg0->DevHandle);
3318 	tgtdev->dev_type = dev_pg0->DeviceForm;
3319 	tgtdev->encl_handle = (dev_pg0->EnclosureHandle);
3320 	tgtdev->parent_handle = (dev_pg0->ParentDevHandle);
3321 	tgtdev->slot = (dev_pg0->Slot);
3322 	tgtdev->qdepth = (dev_pg0->QueueDepth);
3323 	tgtdev->wwid = (dev_pg0->WWID);
3324 
3325 	flags = (dev_pg0->Flags);
3326 	tgtdev->is_hidden = (flags & MPI3_DEVICE0_FLAGS_HIDDEN);
3327 	if (is_added == true)
3328 		tgtdev->io_throttle_enabled =
3329 		    (flags & MPI3_DEVICE0_FLAGS_IO_THROTTLING_REQUIRED) ? 1 : 0;
3330 
3331 	switch (dev_pg0->AccessStatus) {
3332 	case MPI3_DEVICE0_ASTATUS_NO_ERRORS:
3333 	case MPI3_DEVICE0_ASTATUS_PREPARE:
3334 	case MPI3_DEVICE0_ASTATUS_NEEDS_INITIALIZATION:
3335 	case MPI3_DEVICE0_ASTATUS_DEVICE_MISSING_DELAY:
3336 		break;
3337 	default:
3338 		tgtdev->is_hidden = 1;
3339 		break;
3340 	}
3341 
3342 	switch (tgtdev->dev_type) {
3343 	case MPI3_DEVICE_DEVFORM_SAS_SATA:
3344 	{
3345 		Mpi3Device0SasSataFormat_t *sasinf =
3346 		    &dev_pg0->DeviceSpecific.SasSataFormat;
3347 		U16 dev_info = (sasinf->DeviceInfo);
3348 		tgtdev->dev_spec.sassata_inf.dev_info = dev_info;
3349 		tgtdev->dev_spec.sassata_inf.sas_address =
3350 		    (sasinf->SASAddress);
3351 		if ((dev_info & MPI3_SAS_DEVICE_INFO_DEVICE_TYPE_MASK) !=
3352 		    MPI3_SAS_DEVICE_INFO_DEVICE_TYPE_END_DEVICE)
3353 			tgtdev->is_hidden = 1;
3354 		else if (!(dev_info & (MPI3_SAS_DEVICE_INFO_STP_SATA_TARGET |
3355 			    MPI3_SAS_DEVICE_INFO_SSP_TARGET)))
3356 			tgtdev->is_hidden = 1;
3357 		break;
3358 	}
3359 	case MPI3_DEVICE_DEVFORM_PCIE:
3360 	{
3361 		Mpi3Device0PcieFormat_t *pcieinf =
3362 		    &dev_pg0->DeviceSpecific.PcieFormat;
3363 		U16 dev_info = (pcieinf->DeviceInfo);
3364 
3365 		tgtdev->q_depth = dev_pg0->QueueDepth;
3366 		tgtdev->dev_spec.pcie_inf.dev_info = dev_info;
3367 		tgtdev->dev_spec.pcie_inf.capb =
3368 		    (pcieinf->Capabilities);
3369 		tgtdev->dev_spec.pcie_inf.mdts = MPI3MR_DEFAULT_MDTS;
3370 		if (dev_pg0->AccessStatus == MPI3_DEVICE0_ASTATUS_NO_ERRORS) {
3371 			tgtdev->dev_spec.pcie_inf.mdts =
3372 			    (pcieinf->MaximumDataTransferSize);
3373 			tgtdev->dev_spec.pcie_inf.pgsz = pcieinf->PageSize;
3374 			tgtdev->dev_spec.pcie_inf.reset_to =
3375 				pcieinf->ControllerResetTO;
3376 			tgtdev->dev_spec.pcie_inf.abort_to =
3377 				pcieinf->NVMeAbortTO;
3378 		}
3379 		if (tgtdev->dev_spec.pcie_inf.mdts > (1024 * 1024))
3380 			tgtdev->dev_spec.pcie_inf.mdts = (1024 * 1024);
3381 
3382 		if (((dev_info & MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) !=
3383 		    MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_NVME_DEVICE) &&
3384 		    ((dev_info & MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_MASK) !=
3385 		    MPI3_DEVICE0_PCIE_DEVICE_INFO_TYPE_SCSI_DEVICE))
3386 			tgtdev->is_hidden = 1;
3387 
3388 		break;
3389 	}
3390 	case MPI3_DEVICE_DEVFORM_VD:
3391 	{
3392 		Mpi3Device0VdFormat_t *vdinf =
3393 		    &dev_pg0->DeviceSpecific.VdFormat;
3394 		struct mpi3mr_throttle_group_info *tg = NULL;
3395 
3396 		tgtdev->dev_spec.vol_inf.state = vdinf->VdState;
3397 		if (vdinf->VdState == MPI3_DEVICE0_VD_STATE_OFFLINE)
3398 			tgtdev->is_hidden = 1;
3399 		tgtdev->dev_spec.vol_inf.tg_id = vdinf->IOThrottleGroup;
3400 		tgtdev->dev_spec.vol_inf.tg_high =
3401 			vdinf->IOThrottleGroupHigh * 2048;
3402 		tgtdev->dev_spec.vol_inf.tg_low =
3403 			vdinf->IOThrottleGroupLow * 2048;
3404 		if (vdinf->IOThrottleGroup < sc->num_io_throttle_group) {
3405 			tg = sc->throttle_groups + vdinf->IOThrottleGroup;
3406 			tg->id = vdinf->IOThrottleGroup;
3407 			tg->high = tgtdev->dev_spec.vol_inf.tg_high;
3408 			tg->low = tgtdev->dev_spec.vol_inf.tg_low;
3409 			if (is_added == true)
3410 				tg->fw_qd = tgtdev->q_depth;
3411 			tg->modified_qd = tgtdev->q_depth;
3412 		}
3413 		tgtdev->dev_spec.vol_inf.tg = tg;
3414 		tgtdev->throttle_group = tg;
3415 		break;
3416 	}
3417 	default:
3418 		goto out;
3419 	}
3420 
3421 out:
3422 	return;
3423 }
3424 
3425 int mpi3mr_create_device(struct mpi3mr_softc *sc,
3426     Mpi3DevicePage0_t *dev_pg0)
3427 {
3428 	int retval = 0;
3429 	struct mpi3mr_target *target = NULL;
3430 	U16 per_id = 0;
3431 
3432 	per_id = dev_pg0->PersistentID;
3433 
3434 	mtx_lock_spin(&sc->target_lock);
3435 	TAILQ_FOREACH(target, &sc->cam_sc->tgt_list, tgt_next) {
3436 		if (target->per_id == per_id) {
3437 			target->state = MPI3MR_DEV_CREATED;
3438 			break;
3439 		}
3440 	}
3441 	mtx_unlock_spin(&sc->target_lock);
3442 
3443 	if (target) {
3444 			mpi3mr_update_device(sc, target, dev_pg0, true);
3445 	} else {
3446 			target = malloc(sizeof(*target), M_MPI3MR,
3447 				 M_NOWAIT | M_ZERO);
3448 
3449 			if (target == NULL) {
3450 				retval = -1;
3451 				goto out;
3452 			}
3453 
3454 			target->exposed_to_os = 0;
3455 			mpi3mr_update_device(sc, target, dev_pg0, true);
3456 			mtx_lock_spin(&sc->target_lock);
3457 			TAILQ_INSERT_TAIL(&sc->cam_sc->tgt_list, target, tgt_next);
3458 			target->state = MPI3MR_DEV_CREATED;
3459 			mtx_unlock_spin(&sc->target_lock);
3460 	}
3461 out:
3462 	return retval;
3463 }
3464 
3465 /**
3466  * mpi3mr_dev_rmhs_complete_iou - Device removal IOUC completion
3467  * @sc: Adapter instance reference
3468  * @drv_cmd: Internal command tracker
3469  *
3470  * Issues a target reset TM to the firmware from the device
3471  * removal TM pend list or retry the removal handshake sequence
3472  * based on the IOU control request IOC status.
3473  *
3474  * Return: Nothing
3475  */
3476 static void mpi3mr_dev_rmhs_complete_iou(struct mpi3mr_softc *sc,
3477 	struct mpi3mr_drvr_cmd *drv_cmd)
3478 {
3479 	U16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
3480 	struct delayed_dev_rmhs_node *delayed_dev_rmhs = NULL;
3481 	struct mpi3mr_target *tgtdev = NULL;
3482 
3483 	mpi3mr_dprint(sc, MPI3MR_EVENT,
3484 	    "%s :dev_rmhs_iouctrl_complete:handle(0x%04x), ioc_status(0x%04x), loginfo(0x%08x)\n",
3485 	    __func__, drv_cmd->dev_handle, drv_cmd->ioc_status,
3486 	    drv_cmd->ioc_loginfo);
3487 	if (drv_cmd->ioc_status != MPI3_IOCSTATUS_SUCCESS) {
3488 		if (drv_cmd->retry_count < MPI3MR_DEVRMHS_RETRYCOUNT) {
3489 			drv_cmd->retry_count++;
3490 			mpi3mr_dprint(sc, MPI3MR_EVENT,
3491 			    "%s :dev_rmhs_iouctrl_complete: handle(0x%04x)retrying handshake retry=%d\n",
3492 			    __func__, drv_cmd->dev_handle,
3493 			    drv_cmd->retry_count);
3494 			mpi3mr_dev_rmhs_send_tm(sc, drv_cmd->dev_handle,
3495 			    drv_cmd, drv_cmd->iou_rc);
3496 			return;
3497 		}
3498 		mpi3mr_dprint(sc, MPI3MR_ERROR,
3499 		    "%s :dev removal handshake failed after all retries: handle(0x%04x)\n",
3500 		    __func__, drv_cmd->dev_handle);
3501 	} else {
3502 		mtx_lock_spin(&sc->target_lock);
3503 		TAILQ_FOREACH(tgtdev, &sc->cam_sc->tgt_list, tgt_next) {
3504 		       if (tgtdev->dev_handle == drv_cmd->dev_handle)
3505 			       tgtdev->state = MPI3MR_DEV_REMOVE_HS_COMPLETED;
3506 		}
3507 		mtx_unlock_spin(&sc->target_lock);
3508 
3509 		mpi3mr_dprint(sc, MPI3MR_INFO,
3510 		    "%s :dev removal handshake completed successfully: handle(0x%04x)\n",
3511 		    __func__, drv_cmd->dev_handle);
3512 		mpi3mr_clear_bit(drv_cmd->dev_handle, sc->removepend_bitmap);
3513 	}
3514 
3515 	if (!TAILQ_EMPTY(&sc->delayed_rmhs_list)) {
3516 		delayed_dev_rmhs = TAILQ_FIRST(&sc->delayed_rmhs_list);
3517 		drv_cmd->dev_handle = delayed_dev_rmhs->handle;
3518 		drv_cmd->retry_count = 0;
3519 		drv_cmd->iou_rc = delayed_dev_rmhs->iou_rc;
3520 		mpi3mr_dprint(sc, MPI3MR_EVENT,
3521 		    "%s :dev_rmhs_iouctrl_complete: processing delayed TM: handle(0x%04x)\n",
3522 		    __func__, drv_cmd->dev_handle);
3523 		mpi3mr_dev_rmhs_send_tm(sc, drv_cmd->dev_handle, drv_cmd,
3524 		    drv_cmd->iou_rc);
3525 		TAILQ_REMOVE(&sc->delayed_rmhs_list, delayed_dev_rmhs, list);
3526 		free(delayed_dev_rmhs, M_MPI3MR);
3527 		return;
3528 	}
3529 	drv_cmd->state = MPI3MR_CMD_NOTUSED;
3530 	drv_cmd->callback = NULL;
3531 	drv_cmd->retry_count = 0;
3532 	drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
3533 	mpi3mr_clear_bit(cmd_idx, sc->devrem_bitmap);
3534 }
3535 
3536 /**
3537  * mpi3mr_dev_rmhs_complete_tm - Device removal TM completion
3538  * @sc: Adapter instance reference
3539  * @drv_cmd: Internal command tracker
3540  *
3541  * Issues a target reset TM to the firmware from the device
3542  * removal TM pend list or issue IO Unit control request as
3543  * part of device removal or hidden acknowledgment handshake.
3544  *
3545  * Return: Nothing
3546  */
3547 static void mpi3mr_dev_rmhs_complete_tm(struct mpi3mr_softc *sc,
3548 	struct mpi3mr_drvr_cmd *drv_cmd)
3549 {
3550 	Mpi3IoUnitControlRequest_t iou_ctrl;
3551 	U16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
3552 	Mpi3SCSITaskMgmtReply_t *tm_reply = NULL;
3553 	int retval;
3554 
3555 	if (drv_cmd->state & MPI3MR_CMD_REPLYVALID)
3556 		tm_reply = (Mpi3SCSITaskMgmtReply_t *)drv_cmd->reply;
3557 
3558 	if (tm_reply)
3559 		printf(IOCNAME
3560 		    "dev_rmhs_tr_complete:handle(0x%04x), ioc_status(0x%04x), loginfo(0x%08x), term_count(%d)\n",
3561 		    sc->name, drv_cmd->dev_handle, drv_cmd->ioc_status,
3562 		    drv_cmd->ioc_loginfo,
3563 		    le32toh(tm_reply->TerminationCount));
3564 
3565 	printf(IOCNAME "Issuing IOU CTL: handle(0x%04x) dev_rmhs idx(%d)\n",
3566 	    sc->name, drv_cmd->dev_handle, cmd_idx);
3567 
3568 	memset(&iou_ctrl, 0, sizeof(iou_ctrl));
3569 
3570 	drv_cmd->state = MPI3MR_CMD_PENDING;
3571 	drv_cmd->is_waiting = 0;
3572 	drv_cmd->callback = mpi3mr_dev_rmhs_complete_iou;
3573 	iou_ctrl.Operation = drv_cmd->iou_rc;
3574 	iou_ctrl.Param16[0] = htole16(drv_cmd->dev_handle);
3575 	iou_ctrl.HostTag = htole16(drv_cmd->host_tag);
3576 	iou_ctrl.Function = MPI3_FUNCTION_IO_UNIT_CONTROL;
3577 
3578 	retval = mpi3mr_submit_admin_cmd(sc, &iou_ctrl, sizeof(iou_ctrl));
3579 	if (retval) {
3580 		printf(IOCNAME "Issue DevRmHsTMIOUCTL: Admin post failed\n",
3581 		    sc->name);
3582 		goto out_failed;
3583 	}
3584 
3585 	return;
3586 out_failed:
3587 	drv_cmd->state = MPI3MR_CMD_NOTUSED;
3588 	drv_cmd->callback = NULL;
3589 	drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
3590 	drv_cmd->retry_count = 0;
3591 	mpi3mr_clear_bit(cmd_idx, sc->devrem_bitmap);
3592 }
3593 
3594 /**
3595  * mpi3mr_dev_rmhs_send_tm - Issue TM for device removal
3596  * @sc: Adapter instance reference
3597  * @handle: Device handle
3598  * @cmdparam: Internal command tracker
3599  * @iou_rc: IO Unit reason code
3600  *
3601  * Issues a target reset TM to the firmware or add it to a pend
3602  * list as part of device removal or hidden acknowledgment
3603  * handshake.
3604  *
3605  * Return: Nothing
3606  */
3607 static void mpi3mr_dev_rmhs_send_tm(struct mpi3mr_softc *sc, U16 handle,
3608 	struct mpi3mr_drvr_cmd *cmdparam, U8 iou_rc)
3609 {
3610 	Mpi3SCSITaskMgmtRequest_t tm_req;
3611 	int retval = 0;
3612 	U16 cmd_idx = MPI3MR_NUM_DEVRMCMD;
3613 	U8 retrycount = 5;
3614 	struct mpi3mr_drvr_cmd *drv_cmd = cmdparam;
3615 	struct delayed_dev_rmhs_node *delayed_dev_rmhs = NULL;
3616 
3617 	if (drv_cmd)
3618 		goto issue_cmd;
3619 	do {
3620 		cmd_idx = mpi3mr_find_first_zero_bit(sc->devrem_bitmap,
3621 		    MPI3MR_NUM_DEVRMCMD);
3622 		if (cmd_idx < MPI3MR_NUM_DEVRMCMD) {
3623 			if (!mpi3mr_test_and_set_bit(cmd_idx, sc->devrem_bitmap))
3624 				break;
3625 			cmd_idx = MPI3MR_NUM_DEVRMCMD;
3626 		}
3627 	} while (retrycount--);
3628 
3629 	if (cmd_idx >= MPI3MR_NUM_DEVRMCMD) {
3630 		delayed_dev_rmhs = malloc(sizeof(*delayed_dev_rmhs),M_MPI3MR,
3631 		     M_ZERO|M_NOWAIT);
3632 
3633 		if (!delayed_dev_rmhs)
3634 			return;
3635 		delayed_dev_rmhs->handle = handle;
3636 		delayed_dev_rmhs->iou_rc = iou_rc;
3637 		TAILQ_INSERT_TAIL(&(sc->delayed_rmhs_list), delayed_dev_rmhs, list);
3638 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s :DevRmHs: tr:handle(0x%04x) is postponed\n",
3639 		    __func__, handle);
3640 
3641 
3642 		return;
3643 	}
3644 	drv_cmd = &sc->dev_rmhs_cmds[cmd_idx];
3645 
3646 issue_cmd:
3647 	cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
3648 	mpi3mr_dprint(sc, MPI3MR_EVENT,
3649 	    "%s :Issuing TR TM: for devhandle 0x%04x with dev_rmhs %d\n",
3650 	    __func__, handle, cmd_idx);
3651 
3652 	memset(&tm_req, 0, sizeof(tm_req));
3653 	if (drv_cmd->state & MPI3MR_CMD_PENDING) {
3654 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s :Issue TM: Command is in use\n", __func__);
3655 		goto out;
3656 	}
3657 	drv_cmd->state = MPI3MR_CMD_PENDING;
3658 	drv_cmd->is_waiting = 0;
3659 	drv_cmd->callback = mpi3mr_dev_rmhs_complete_tm;
3660 	drv_cmd->dev_handle = handle;
3661 	drv_cmd->iou_rc = iou_rc;
3662 	tm_req.DevHandle = htole16(handle);
3663 	tm_req.TaskType = MPI3_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
3664 	tm_req.HostTag = htole16(drv_cmd->host_tag);
3665 	tm_req.TaskHostTag = htole16(MPI3MR_HOSTTAG_INVALID);
3666 	tm_req.Function = MPI3_FUNCTION_SCSI_TASK_MGMT;
3667 
3668 	mpi3mr_set_bit(handle, sc->removepend_bitmap);
3669 	retval = mpi3mr_submit_admin_cmd(sc, &tm_req, sizeof(tm_req));
3670 	if (retval) {
3671 		mpi3mr_dprint(sc, MPI3MR_ERROR, "%s :Issue DevRmHsTM: Admin Post failed\n",
3672 		    __func__);
3673 		goto out_failed;
3674 	}
3675 out:
3676 	return;
3677 out_failed:
3678 	drv_cmd->state = MPI3MR_CMD_NOTUSED;
3679 	drv_cmd->callback = NULL;
3680 	drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
3681 	drv_cmd->retry_count = 0;
3682 	mpi3mr_clear_bit(cmd_idx, sc->devrem_bitmap);
3683 }
3684 
3685 /**
3686  * mpi3mr_complete_evt_ack - Event ack request completion
3687  * @sc: Adapter instance reference
3688  * @drv_cmd: Internal command tracker
3689  *
3690  * This is the completion handler for non blocking event
3691  * acknowledgment sent to the firmware and this will issue any
3692  * pending event acknowledgment request.
3693  *
3694  * Return: Nothing
3695  */
3696 static void mpi3mr_complete_evt_ack(struct mpi3mr_softc *sc,
3697 	struct mpi3mr_drvr_cmd *drv_cmd)
3698 {
3699 	U16 cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_EVTACKCMD_MIN;
3700 	struct delayed_evtack_node *delayed_evtack = NULL;
3701 
3702 	if (drv_cmd->ioc_status != MPI3_IOCSTATUS_SUCCESS) {
3703 		mpi3mr_dprint(sc, MPI3MR_EVENT,
3704 		    "%s: Failed IOCStatus(0x%04x) Loginfo(0x%08x)\n", __func__,
3705 		    (drv_cmd->ioc_status & MPI3_IOCSTATUS_STATUS_MASK),
3706 		    drv_cmd->ioc_loginfo);
3707 	}
3708 
3709 	if (!TAILQ_EMPTY(&sc->delayed_evtack_cmds_list)) {
3710 		delayed_evtack = TAILQ_FIRST(&sc->delayed_evtack_cmds_list);
3711 		mpi3mr_dprint(sc, MPI3MR_EVENT,
3712 		    "%s: processing delayed event ack for event %d\n",
3713 		    __func__, delayed_evtack->event);
3714 		mpi3mr_send_evt_ack(sc, delayed_evtack->event, drv_cmd,
3715 		    delayed_evtack->event_ctx);
3716 		TAILQ_REMOVE(&sc->delayed_evtack_cmds_list, delayed_evtack, list);
3717 		free(delayed_evtack, M_MPI3MR);
3718 		return;
3719 	}
3720 	drv_cmd->state = MPI3MR_CMD_NOTUSED;
3721 	drv_cmd->callback = NULL;
3722 	mpi3mr_clear_bit(cmd_idx, sc->evtack_cmds_bitmap);
3723 }
3724 
3725 /**
3726  * mpi3mr_send_evt_ack - Issue event acknwoledgment request
3727  * @sc: Adapter instance reference
3728  * @event: MPI3 event id
3729  * @cmdparam: Internal command tracker
3730  * @event_ctx: Event context
3731  *
3732  * Issues event acknowledgment request to the firmware if there
3733  * is a free command to send the event ack else it to a pend
3734  * list so that it will be processed on a completion of a prior
3735  * event acknowledgment .
3736  *
3737  * Return: Nothing
3738  */
3739 static void mpi3mr_send_evt_ack(struct mpi3mr_softc *sc, U8 event,
3740 	struct mpi3mr_drvr_cmd *cmdparam, U32 event_ctx)
3741 {
3742 	Mpi3EventAckRequest_t evtack_req;
3743 	int retval = 0;
3744 	U8 retrycount = 5;
3745 	U16 cmd_idx = MPI3MR_NUM_EVTACKCMD;
3746 	struct mpi3mr_drvr_cmd *drv_cmd = cmdparam;
3747 	struct delayed_evtack_node *delayed_evtack = NULL;
3748 
3749 	if (drv_cmd)
3750 		goto issue_cmd;
3751 	do {
3752 		cmd_idx = mpi3mr_find_first_zero_bit(sc->evtack_cmds_bitmap,
3753 		    MPI3MR_NUM_EVTACKCMD);
3754 		if (cmd_idx < MPI3MR_NUM_EVTACKCMD) {
3755 			if (!mpi3mr_test_and_set_bit(cmd_idx,
3756 			    sc->evtack_cmds_bitmap))
3757 				break;
3758 			cmd_idx = MPI3MR_NUM_EVTACKCMD;
3759 		}
3760 	} while (retrycount--);
3761 
3762 	if (cmd_idx >= MPI3MR_NUM_EVTACKCMD) {
3763 		delayed_evtack = malloc(sizeof(*delayed_evtack),M_MPI3MR,
3764 		     M_ZERO | M_NOWAIT);
3765 		if (!delayed_evtack)
3766 			return;
3767 		delayed_evtack->event = event;
3768 		delayed_evtack->event_ctx = event_ctx;
3769 		TAILQ_INSERT_TAIL(&(sc->delayed_evtack_cmds_list), delayed_evtack, list);
3770 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s : Event ack for event:%d is postponed\n",
3771 		    __func__, event);
3772 		return;
3773 	}
3774 	drv_cmd = &sc->evtack_cmds[cmd_idx];
3775 
3776 issue_cmd:
3777 	cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_EVTACKCMD_MIN;
3778 
3779 	memset(&evtack_req, 0, sizeof(evtack_req));
3780 	if (drv_cmd->state & MPI3MR_CMD_PENDING) {
3781 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s: Command is in use\n", __func__);
3782 		goto out;
3783 	}
3784 	drv_cmd->state = MPI3MR_CMD_PENDING;
3785 	drv_cmd->is_waiting = 0;
3786 	drv_cmd->callback = mpi3mr_complete_evt_ack;
3787 	evtack_req.HostTag = htole16(drv_cmd->host_tag);
3788 	evtack_req.Function = MPI3_FUNCTION_EVENT_ACK;
3789 	evtack_req.Event = event;
3790 	evtack_req.EventContext = htole32(event_ctx);
3791 	retval = mpi3mr_submit_admin_cmd(sc, &evtack_req,
3792 	    sizeof(evtack_req));
3793 
3794 	if (retval) {
3795 		mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Admin Post failed\n", __func__);
3796 		goto out_failed;
3797 	}
3798 out:
3799 	return;
3800 out_failed:
3801 	drv_cmd->state = MPI3MR_CMD_NOTUSED;
3802 	drv_cmd->callback = NULL;
3803 	mpi3mr_clear_bit(cmd_idx, sc->evtack_cmds_bitmap);
3804 }
3805 
3806 /*
3807  * mpi3mr_pcietopochg_evt_th - PCIETopologyChange evt tophalf
3808  * @sc: Adapter instance reference
3809  * @event_reply: Event data
3810  *
3811  * Checks for the reason code and based on that either block I/O
3812  * to device, or unblock I/O to the device, or start the device
3813  * removal handshake with reason as remove with the firmware for
3814  * PCIe devices.
3815  *
3816  * Return: Nothing
3817  */
3818 static void mpi3mr_pcietopochg_evt_th(struct mpi3mr_softc *sc,
3819 	Mpi3EventNotificationReply_t *event_reply)
3820 {
3821 	Mpi3EventDataPcieTopologyChangeList_t *topo_evt =
3822 	    (Mpi3EventDataPcieTopologyChangeList_t *) event_reply->EventData;
3823 	int i;
3824 	U16 handle;
3825 	U8 reason_code;
3826 	struct mpi3mr_target *tgtdev = NULL;
3827 
3828 	for (i = 0; i < topo_evt->NumEntries; i++) {
3829 		handle = le16toh(topo_evt->PortEntry[i].AttachedDevHandle);
3830 		if (!handle)
3831 			continue;
3832 		reason_code = topo_evt->PortEntry[i].PortStatus;
3833 		tgtdev = mpi3mr_find_target_by_dev_handle(sc->cam_sc, handle);
3834 		switch (reason_code) {
3835 		case MPI3_EVENT_PCIE_TOPO_PS_NOT_RESPONDING:
3836 			if (tgtdev) {
3837 				tgtdev->dev_removed = 1;
3838 				tgtdev->dev_removedelay = 0;
3839 				mpi3mr_atomic_set(&tgtdev->block_io, 0);
3840 			}
3841 			mpi3mr_dev_rmhs_send_tm(sc, handle, NULL,
3842 			    MPI3_CTRL_OP_REMOVE_DEVICE);
3843 			break;
3844 		case MPI3_EVENT_PCIE_TOPO_PS_DELAY_NOT_RESPONDING:
3845 			if (tgtdev) {
3846 				tgtdev->dev_removedelay = 1;
3847 				mpi3mr_atomic_inc(&tgtdev->block_io);
3848 			}
3849 			break;
3850 		case MPI3_EVENT_PCIE_TOPO_PS_RESPONDING:
3851 			if (tgtdev &&
3852 			    tgtdev->dev_removedelay) {
3853 				tgtdev->dev_removedelay = 0;
3854 				if (mpi3mr_atomic_read(&tgtdev->block_io) > 0)
3855 					mpi3mr_atomic_dec(&tgtdev->block_io);
3856 			}
3857 			break;
3858 		case MPI3_EVENT_PCIE_TOPO_PS_PORT_CHANGED:
3859 		default:
3860 			break;
3861 		}
3862 	}
3863 }
3864 
3865 /**
3866  * mpi3mr_sastopochg_evt_th - SASTopologyChange evt tophalf
3867  * @sc: Adapter instance reference
3868  * @event_reply: Event data
3869  *
3870  * Checks for the reason code and based on that either block I/O
3871  * to device, or unblock I/O to the device, or start the device
3872  * removal handshake with reason as remove with the firmware for
3873  * SAS/SATA devices.
3874  *
3875  * Return: Nothing
3876  */
3877 static void mpi3mr_sastopochg_evt_th(struct mpi3mr_softc *sc,
3878 	Mpi3EventNotificationReply_t *event_reply)
3879 {
3880 	Mpi3EventDataSasTopologyChangeList_t *topo_evt =
3881 	    (Mpi3EventDataSasTopologyChangeList_t *)event_reply->EventData;
3882 	int i;
3883 	U16 handle;
3884 	U8 reason_code;
3885 	struct mpi3mr_target *tgtdev = NULL;
3886 
3887 	for (i = 0; i < topo_evt->NumEntries; i++) {
3888 		handle = le16toh(topo_evt->PhyEntry[i].AttachedDevHandle);
3889 		if (!handle)
3890 			continue;
3891 		reason_code = topo_evt->PhyEntry[i].PhyStatus &
3892 		    MPI3_EVENT_SAS_TOPO_PHY_RC_MASK;
3893 		tgtdev = mpi3mr_find_target_by_dev_handle(sc->cam_sc, handle);
3894 		switch (reason_code) {
3895 		case MPI3_EVENT_SAS_TOPO_PHY_RC_TARG_NOT_RESPONDING:
3896 			if (tgtdev) {
3897 				tgtdev->dev_removed = 1;
3898 				tgtdev->dev_removedelay = 0;
3899 				mpi3mr_atomic_set(&tgtdev->block_io, 0);
3900 			}
3901 			mpi3mr_dev_rmhs_send_tm(sc, handle, NULL,
3902 			    MPI3_CTRL_OP_REMOVE_DEVICE);
3903 			break;
3904 		case MPI3_EVENT_SAS_TOPO_PHY_RC_DELAY_NOT_RESPONDING:
3905 			if (tgtdev) {
3906 				tgtdev->dev_removedelay = 1;
3907 				mpi3mr_atomic_inc(&tgtdev->block_io);
3908 			}
3909 			break;
3910 		case MPI3_EVENT_SAS_TOPO_PHY_RC_RESPONDING:
3911 			if (tgtdev &&
3912 			    tgtdev->dev_removedelay) {
3913 				tgtdev->dev_removedelay = 0;
3914 				if (mpi3mr_atomic_read(&tgtdev->block_io) > 0)
3915 					mpi3mr_atomic_dec(&tgtdev->block_io);
3916 			}
3917 		case MPI3_EVENT_SAS_TOPO_PHY_RC_PHY_CHANGED:
3918 		default:
3919 			break;
3920 		}
3921 	}
3922 
3923 }
3924 /**
3925  * mpi3mr_devstatuschg_evt_th - DeviceStatusChange evt tophalf
3926  * @sc: Adapter instance reference
3927  * @event_reply: Event data
3928  *
3929  * Checks for the reason code and based on that either block I/O
3930  * to device, or unblock I/O to the device, or start the device
3931  * removal handshake with reason as remove/hide acknowledgment
3932  * with the firmware.
3933  *
3934  * Return: Nothing
3935  */
3936 static void mpi3mr_devstatuschg_evt_th(struct mpi3mr_softc *sc,
3937 	Mpi3EventNotificationReply_t *event_reply)
3938 {
3939 	U16 dev_handle = 0;
3940 	U8 ublock = 0, block = 0, hide = 0, uhide = 0, delete = 0, remove = 0;
3941 	struct mpi3mr_target *tgtdev = NULL;
3942 	Mpi3EventDataDeviceStatusChange_t *evtdata =
3943 	    (Mpi3EventDataDeviceStatusChange_t *) event_reply->EventData;
3944 
3945 	dev_handle = le16toh(evtdata->DevHandle);
3946 
3947 	switch (evtdata->ReasonCode) {
3948 	case MPI3_EVENT_DEV_STAT_RC_INT_DEVICE_RESET_STRT:
3949 	case MPI3_EVENT_DEV_STAT_RC_INT_IT_NEXUS_RESET_STRT:
3950 		block = 1;
3951 		break;
3952 	case MPI3_EVENT_DEV_STAT_RC_HIDDEN:
3953 		delete = 1;
3954 		hide = 1;
3955 		break;
3956 	case MPI3_EVENT_DEV_STAT_RC_NOT_HIDDEN:
3957 		uhide = 1;
3958 		break;
3959 	case MPI3_EVENT_DEV_STAT_RC_VD_NOT_RESPONDING:
3960 		delete = 1;
3961 		remove = 1;
3962 		break;
3963 	case MPI3_EVENT_DEV_STAT_RC_INT_DEVICE_RESET_CMP:
3964 	case MPI3_EVENT_DEV_STAT_RC_INT_IT_NEXUS_RESET_CMP:
3965 		ublock = 1;
3966 		break;
3967 	default:
3968 		break;
3969 	}
3970 
3971 	tgtdev = mpi3mr_find_target_by_dev_handle(sc->cam_sc, dev_handle);
3972 
3973 	if (!tgtdev) {
3974 		mpi3mr_dprint(sc, MPI3MR_ERROR, "%s :target with dev_handle:0x%x not found\n",
3975 		    __func__, dev_handle);
3976 		return;
3977 	}
3978 
3979 	if (block)
3980 		mpi3mr_atomic_inc(&tgtdev->block_io);
3981 
3982 	if (hide)
3983 		tgtdev->is_hidden = hide;
3984 
3985 	if (uhide) {
3986 		tgtdev->is_hidden = 0;
3987 		tgtdev->dev_removed = 0;
3988 	}
3989 
3990 	if (delete)
3991 		tgtdev->dev_removed = 1;
3992 
3993 	if (ublock) {
3994 		if (mpi3mr_atomic_read(&tgtdev->block_io) > 0)
3995 			mpi3mr_atomic_dec(&tgtdev->block_io);
3996 	}
3997 
3998 	if (remove) {
3999 		mpi3mr_dev_rmhs_send_tm(sc, dev_handle, NULL,
4000 					MPI3_CTRL_OP_REMOVE_DEVICE);
4001 	}
4002 	if (hide)
4003 		mpi3mr_dev_rmhs_send_tm(sc, dev_handle, NULL,
4004 					MPI3_CTRL_OP_HIDDEN_ACK);
4005 }
4006 
4007 /**
4008  * mpi3mr_preparereset_evt_th - Prepareforreset evt tophalf
4009  * @sc: Adapter instance reference
4010  * @event_reply: Event data
4011  *
4012  * Blocks and unblocks host level I/O based on the reason code
4013  *
4014  * Return: Nothing
4015  */
4016 static void mpi3mr_preparereset_evt_th(struct mpi3mr_softc *sc,
4017 	Mpi3EventNotificationReply_t *event_reply)
4018 {
4019 	Mpi3EventDataPrepareForReset_t *evtdata =
4020 	    (Mpi3EventDataPrepareForReset_t *)event_reply->EventData;
4021 
4022 	if (evtdata->ReasonCode == MPI3_EVENT_PREPARE_RESET_RC_START) {
4023 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s :Recieved PrepForReset Event with RC=START\n",
4024 		    __func__);
4025 		if (sc->prepare_for_reset)
4026 			return;
4027 		sc->prepare_for_reset = 1;
4028 		sc->prepare_for_reset_timeout_counter = 0;
4029 	} else if (evtdata->ReasonCode == MPI3_EVENT_PREPARE_RESET_RC_ABORT) {
4030 		mpi3mr_dprint(sc, MPI3MR_EVENT, "%s :Recieved PrepForReset Event with RC=ABORT\n",
4031 		    __func__);
4032 		sc->prepare_for_reset = 0;
4033 		sc->prepare_for_reset_timeout_counter = 0;
4034 	}
4035 	if ((event_reply->MsgFlags & MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_MASK)
4036 	    == MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_REQUIRED)
4037 		mpi3mr_send_evt_ack(sc, event_reply->Event, NULL,
4038 		    le32toh(event_reply->EventContext));
4039 }
4040 
4041 /**
4042  * mpi3mr_energypackchg_evt_th - Energypackchange evt tophalf
4043  * @sc: Adapter instance reference
4044  * @event_reply: Event data
4045  *
4046  * Identifies the new shutdown timeout value and update.
4047  *
4048  * Return: Nothing
4049  */
4050 static void mpi3mr_energypackchg_evt_th(struct mpi3mr_softc *sc,
4051 	Mpi3EventNotificationReply_t *event_reply)
4052 {
4053 	Mpi3EventDataEnergyPackChange_t *evtdata =
4054 	    (Mpi3EventDataEnergyPackChange_t *)event_reply->EventData;
4055 	U16 shutdown_timeout = le16toh(evtdata->ShutdownTimeout);
4056 
4057 	if (shutdown_timeout <= 0) {
4058 		mpi3mr_dprint(sc, MPI3MR_ERROR,
4059 		    "%s :Invalid Shutdown Timeout received = %d\n",
4060 		    __func__, shutdown_timeout);
4061 		return;
4062 	}
4063 
4064 	mpi3mr_dprint(sc, MPI3MR_EVENT,
4065 	    "%s :Previous Shutdown Timeout Value = %d New Shutdown Timeout Value = %d\n",
4066 	    __func__, sc->facts.shutdown_timeout, shutdown_timeout);
4067 	sc->facts.shutdown_timeout = shutdown_timeout;
4068 }
4069 
4070 /**
4071  * mpi3mr_cablemgmt_evt_th - Cable mgmt evt tophalf
4072  * @sc: Adapter instance reference
4073  * @event_reply: Event data
4074  *
4075  * Displays Cable manegemt event details.
4076  *
4077  * Return: Nothing
4078  */
4079 static void mpi3mr_cablemgmt_evt_th(struct mpi3mr_softc *sc,
4080 	Mpi3EventNotificationReply_t *event_reply)
4081 {
4082 	Mpi3EventDataCableManagement_t *evtdata =
4083 	    (Mpi3EventDataCableManagement_t *)event_reply->EventData;
4084 
4085 	switch (evtdata->Status) {
4086 	case MPI3_EVENT_CABLE_MGMT_STATUS_INSUFFICIENT_POWER:
4087 	{
4088 		mpi3mr_dprint(sc, MPI3MR_INFO, "An active cable with ReceptacleID %d cannot be powered.\n"
4089 		    "Devices connected to this cable are not detected.\n"
4090 		    "This cable requires %d mW of power.\n",
4091 		    evtdata->ReceptacleID,
4092 		    le32toh(evtdata->ActiveCablePowerRequirement));
4093 		break;
4094 	}
4095 	case MPI3_EVENT_CABLE_MGMT_STATUS_DEGRADED:
4096 	{
4097 		mpi3mr_dprint(sc, MPI3MR_INFO, "A cable with ReceptacleID %d is not running at optimal speed\n",
4098 		    evtdata->ReceptacleID);
4099 		break;
4100 	}
4101 	default:
4102 		break;
4103 	}
4104 }
4105 
4106 /**
4107  * mpi3mr_process_events - Event's toph-half handler
4108  * @sc: Adapter instance reference
4109  * @event_reply: Event data
4110  *
4111  * Top half of event processing.
4112  *
4113  * Return: Nothing
4114  */
4115 static void mpi3mr_process_events(struct mpi3mr_softc *sc,
4116     uintptr_t data, Mpi3EventNotificationReply_t *event_reply)
4117 {
4118 	U16 evt_type;
4119 	bool ack_req = 0, process_evt_bh = 0;
4120 	struct mpi3mr_fw_event_work *fw_event;
4121 	U16 sz;
4122 
4123 	if (sc->mpi3mr_flags & MPI3MR_FLAGS_SHUTDOWN)
4124 		goto out;
4125 
4126 	if ((event_reply->MsgFlags & MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_MASK)
4127 	    == MPI3_EVENT_NOTIFY_MSGFLAGS_ACK_REQUIRED)
4128 		ack_req = 1;
4129 
4130 	evt_type = event_reply->Event;
4131 
4132 	switch (evt_type) {
4133 	case MPI3_EVENT_DEVICE_ADDED:
4134 	{
4135 		Mpi3DevicePage0_t *dev_pg0 =
4136 			(Mpi3DevicePage0_t *) event_reply->EventData;
4137 		if (mpi3mr_create_device(sc, dev_pg0))
4138 			mpi3mr_dprint(sc, MPI3MR_ERROR,
4139 			"%s :Failed to add device in the device add event\n",
4140 			__func__);
4141 		else
4142 			process_evt_bh = 1;
4143 		break;
4144 	}
4145 
4146 	case MPI3_EVENT_DEVICE_STATUS_CHANGE:
4147 	{
4148 		process_evt_bh = 1;
4149 		mpi3mr_devstatuschg_evt_th(sc, event_reply);
4150 		break;
4151 	}
4152 	case MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST:
4153 	{
4154 		process_evt_bh = 1;
4155 		mpi3mr_sastopochg_evt_th(sc, event_reply);
4156 		break;
4157 	}
4158 	case MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST:
4159 	{
4160 		process_evt_bh = 1;
4161 		mpi3mr_pcietopochg_evt_th(sc, event_reply);
4162 		break;
4163 	}
4164 	case MPI3_EVENT_PREPARE_FOR_RESET:
4165 	{
4166 		mpi3mr_preparereset_evt_th(sc, event_reply);
4167 		ack_req = 0;
4168 		break;
4169 	}
4170 	case MPI3_EVENT_DEVICE_INFO_CHANGED:
4171 	case MPI3_EVENT_LOG_DATA:
4172 	{
4173 		process_evt_bh = 1;
4174 		break;
4175 	}
4176 	case MPI3_EVENT_ENERGY_PACK_CHANGE:
4177 	{
4178 		mpi3mr_energypackchg_evt_th(sc, event_reply);
4179 		break;
4180 	}
4181 	case MPI3_EVENT_CABLE_MGMT:
4182 	{
4183 		mpi3mr_cablemgmt_evt_th(sc, event_reply);
4184 		break;
4185 	}
4186 
4187 	case MPI3_EVENT_ENCL_DEVICE_STATUS_CHANGE:
4188 	case MPI3_EVENT_SAS_DISCOVERY:
4189 	case MPI3_EVENT_SAS_DEVICE_DISCOVERY_ERROR:
4190 	case MPI3_EVENT_SAS_BROADCAST_PRIMITIVE:
4191 	case MPI3_EVENT_PCIE_ENUMERATION:
4192 		break;
4193 	default:
4194 		mpi3mr_dprint(sc, MPI3MR_INFO, "%s :Event 0x%02x is not handled by driver\n",
4195 		    __func__, evt_type);
4196 		break;
4197 	}
4198 
4199 	if (process_evt_bh || ack_req) {
4200 		fw_event = malloc(sizeof(struct mpi3mr_fw_event_work), M_MPI3MR,
4201 		     M_ZERO|M_NOWAIT);
4202 
4203 		if (!fw_event) {
4204 			printf("%s: allocate failed for fw_event\n", __func__);
4205 			return;
4206 		}
4207 
4208 		sz = le16toh(event_reply->EventDataLength) * 4;
4209 		fw_event->event_data = malloc(sz, M_MPI3MR, M_ZERO|M_NOWAIT);
4210 
4211 		if (!fw_event->event_data) {
4212 			printf("%s: allocate failed for event_data\n", __func__);
4213 			free(fw_event, M_MPI3MR);
4214 			return;
4215 		}
4216 
4217 		bcopy(event_reply->EventData, fw_event->event_data, sz);
4218 		fw_event->event = event_reply->Event;
4219 		if ((event_reply->Event == MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
4220 		    event_reply->Event == MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST ||
4221 		    event_reply->Event == MPI3_EVENT_ENCL_DEVICE_STATUS_CHANGE ) &&
4222 		    sc->track_mapping_events)
4223 			sc->pending_map_events++;
4224 
4225 		/*
4226 		 * Events should be processed after Port enable is completed.
4227 		 */
4228 		if ((event_reply->Event == MPI3_EVENT_SAS_TOPOLOGY_CHANGE_LIST ||
4229 		    event_reply->Event == MPI3_EVENT_PCIE_TOPOLOGY_CHANGE_LIST ) &&
4230 		    !(sc->mpi3mr_flags & MPI3MR_FLAGS_PORT_ENABLE_DONE))
4231 			mpi3mr_startup_increment(sc->cam_sc);
4232 
4233 		fw_event->send_ack = ack_req;
4234 		fw_event->event_context = le32toh(event_reply->EventContext);
4235 		fw_event->event_data_size = sz;
4236 		fw_event->process_event = process_evt_bh;
4237 
4238 		mtx_lock(&sc->fwevt_lock);
4239 		TAILQ_INSERT_TAIL(&sc->cam_sc->ev_queue, fw_event, ev_link);
4240 		taskqueue_enqueue(sc->cam_sc->ev_tq, &sc->cam_sc->ev_task);
4241 		mtx_unlock(&sc->fwevt_lock);
4242 
4243 	}
4244 out:
4245 	return;
4246 }
4247 
4248 static void mpi3mr_handle_events(struct mpi3mr_softc *sc, uintptr_t data,
4249     Mpi3DefaultReply_t *def_reply)
4250 {
4251 	Mpi3EventNotificationReply_t *event_reply =
4252 		(Mpi3EventNotificationReply_t *)def_reply;
4253 
4254 	sc->change_count = event_reply->IOCChangeCount;
4255 	mpi3mr_display_event_data(sc, event_reply);
4256 
4257 	mpi3mr_process_events(sc, data, event_reply);
4258 }
4259 
4260 static void mpi3mr_process_admin_reply_desc(struct mpi3mr_softc *sc,
4261     Mpi3DefaultReplyDescriptor_t *reply_desc, U64 *reply_dma)
4262 {
4263 	U16 reply_desc_type, host_tag = 0, idx;
4264 	U16 ioc_status = MPI3_IOCSTATUS_SUCCESS;
4265 	U32 ioc_loginfo = 0;
4266 	Mpi3StatusReplyDescriptor_t *status_desc;
4267 	Mpi3AddressReplyDescriptor_t *addr_desc;
4268 	Mpi3SuccessReplyDescriptor_t *success_desc;
4269 	Mpi3DefaultReply_t *def_reply = NULL;
4270 	struct mpi3mr_drvr_cmd *cmdptr = NULL;
4271 	Mpi3SCSIIOReply_t *scsi_reply;
4272 	U8 *sense_buf = NULL;
4273 
4274 	*reply_dma = 0;
4275 	reply_desc_type = reply_desc->ReplyFlags &
4276 			    MPI3_REPLY_DESCRIPT_FLAGS_TYPE_MASK;
4277 	switch (reply_desc_type) {
4278 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_STATUS:
4279 		status_desc = (Mpi3StatusReplyDescriptor_t *)reply_desc;
4280 		host_tag = status_desc->HostTag;
4281 		ioc_status = status_desc->IOCStatus;
4282 		if (ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
4283 			ioc_loginfo = status_desc->IOCLogInfo;
4284 		ioc_status &= MPI3_IOCSTATUS_STATUS_MASK;
4285 		break;
4286 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_ADDRESS_REPLY:
4287 		addr_desc = (Mpi3AddressReplyDescriptor_t *)reply_desc;
4288 		*reply_dma = addr_desc->ReplyFrameAddress;
4289 		def_reply = mpi3mr_get_reply_virt_addr(sc, *reply_dma);
4290 		if (def_reply == NULL)
4291 			goto out;
4292 		host_tag = def_reply->HostTag;
4293 		ioc_status = def_reply->IOCStatus;
4294 		if (ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
4295 			ioc_loginfo = def_reply->IOCLogInfo;
4296 		ioc_status &= MPI3_IOCSTATUS_STATUS_MASK;
4297 		if (def_reply->Function == MPI3_FUNCTION_SCSI_IO) {
4298 			scsi_reply = (Mpi3SCSIIOReply_t *)def_reply;
4299 			sense_buf = mpi3mr_get_sensebuf_virt_addr(sc,
4300 			    scsi_reply->SenseDataBufferAddress);
4301 		}
4302 		break;
4303 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_SUCCESS:
4304 		success_desc = (Mpi3SuccessReplyDescriptor_t *)reply_desc;
4305 		host_tag = success_desc->HostTag;
4306 		break;
4307 	default:
4308 		break;
4309 	}
4310 	switch (host_tag) {
4311 	case MPI3MR_HOSTTAG_INITCMDS:
4312 		cmdptr = &sc->init_cmds;
4313 		break;
4314 	case MPI3MR_HOSTTAG_IOCTLCMDS:
4315 		cmdptr = &sc->ioctl_cmds;
4316 		break;
4317 	case MPI3MR_HOSTTAG_TMS:
4318 		cmdptr = &sc->host_tm_cmds;
4319 		wakeup((void *)&sc->tm_chan);
4320 		break;
4321 	case MPI3MR_HOSTTAG_PELABORT:
4322 		cmdptr = &sc->pel_abort_cmd;
4323 		break;
4324 	case MPI3MR_HOSTTAG_PELWAIT:
4325 		cmdptr = &sc->pel_cmds;
4326 		break;
4327 	case MPI3MR_HOSTTAG_INVALID:
4328 		if (def_reply && def_reply->Function ==
4329 		    MPI3_FUNCTION_EVENT_NOTIFICATION)
4330 			mpi3mr_handle_events(sc, *reply_dma ,def_reply);
4331 	default:
4332 		break;
4333 	}
4334 
4335 	if (host_tag >= MPI3MR_HOSTTAG_DEVRMCMD_MIN &&
4336 	    host_tag <= MPI3MR_HOSTTAG_DEVRMCMD_MAX ) {
4337 		idx = host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN;
4338 		cmdptr = &sc->dev_rmhs_cmds[idx];
4339 	}
4340 
4341 	if (host_tag >= MPI3MR_HOSTTAG_EVTACKCMD_MIN &&
4342 	    host_tag <= MPI3MR_HOSTTAG_EVTACKCMD_MAX) {
4343 		idx = host_tag - MPI3MR_HOSTTAG_EVTACKCMD_MIN;
4344 		cmdptr = &sc->evtack_cmds[idx];
4345 	}
4346 
4347 	if (cmdptr) {
4348 		if (cmdptr->state & MPI3MR_CMD_PENDING) {
4349 			cmdptr->state |= MPI3MR_CMD_COMPLETE;
4350 			cmdptr->ioc_loginfo = ioc_loginfo;
4351 			cmdptr->ioc_status = ioc_status;
4352 			cmdptr->state &= ~MPI3MR_CMD_PENDING;
4353 			if (def_reply) {
4354 				cmdptr->state |= MPI3MR_CMD_REPLYVALID;
4355 				memcpy((U8 *)cmdptr->reply, (U8 *)def_reply,
4356 				    sc->reply_sz);
4357 			}
4358 			if (sense_buf && cmdptr->sensebuf) {
4359 				cmdptr->is_senseprst = 1;
4360 				memcpy(cmdptr->sensebuf, sense_buf,
4361 				    MPI3MR_SENSEBUF_SZ);
4362 			}
4363 			if (cmdptr->is_waiting) {
4364 				complete(&cmdptr->completion);
4365 				cmdptr->is_waiting = 0;
4366 			} else if (cmdptr->callback)
4367 				cmdptr->callback(sc, cmdptr);
4368 		}
4369 	}
4370 out:
4371 	if (sense_buf != NULL)
4372 		mpi3mr_repost_sense_buf(sc,
4373 		    scsi_reply->SenseDataBufferAddress);
4374 	return;
4375 }
4376 
4377 /*
4378  * mpi3mr_complete_admin_cmd:	ISR routine for admin commands
4379  * @sc:				Adapter's soft instance
4380  *
4381  * This function processes admin command completions.
4382  */
4383 static int mpi3mr_complete_admin_cmd(struct mpi3mr_softc *sc)
4384 {
4385 	U32 exp_phase = sc->admin_reply_ephase;
4386 	U32 adm_reply_ci = sc->admin_reply_ci;
4387 	U32 num_adm_reply = 0;
4388 	U64 reply_dma = 0;
4389 	Mpi3DefaultReplyDescriptor_t *reply_desc;
4390 	U16 threshold_comps = 0;
4391 
4392 	mtx_lock_spin(&sc->admin_reply_lock);
4393 	if (sc->admin_in_use == false) {
4394 		sc->admin_in_use = true;
4395 		mtx_unlock_spin(&sc->admin_reply_lock);
4396 	} else {
4397 		mtx_unlock_spin(&sc->admin_reply_lock);
4398 		return 0;
4399 	}
4400 
4401 	reply_desc = (Mpi3DefaultReplyDescriptor_t *)sc->admin_reply +
4402 		adm_reply_ci;
4403 
4404 	if ((reply_desc->ReplyFlags &
4405 	     MPI3_REPLY_DESCRIPT_FLAGS_PHASE_MASK) != exp_phase) {
4406 		mtx_lock_spin(&sc->admin_reply_lock);
4407 		sc->admin_in_use = false;
4408 		mtx_unlock_spin(&sc->admin_reply_lock);
4409 		return 0;
4410 	}
4411 
4412 	do {
4413 		sc->admin_req_ci = reply_desc->RequestQueueCI;
4414 		mpi3mr_process_admin_reply_desc(sc, reply_desc, &reply_dma);
4415 		if (reply_dma)
4416 			mpi3mr_repost_reply_buf(sc, reply_dma);
4417 		num_adm_reply++;
4418 		if (++adm_reply_ci == sc->num_admin_replies) {
4419 			adm_reply_ci = 0;
4420 			exp_phase ^= 1;
4421 		}
4422 		reply_desc =
4423 			(Mpi3DefaultReplyDescriptor_t *)sc->admin_reply +
4424 			    adm_reply_ci;
4425 		if ((reply_desc->ReplyFlags &
4426 		     MPI3_REPLY_DESCRIPT_FLAGS_PHASE_MASK) != exp_phase)
4427 			break;
4428 
4429 		if (++threshold_comps == MPI3MR_THRESHOLD_REPLY_COUNT) {
4430 			mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_REPLY_Q_CI_OFFSET, adm_reply_ci);
4431 			threshold_comps = 0;
4432 		}
4433 	} while (1);
4434 
4435 	mpi3mr_regwrite(sc, MPI3_SYSIF_ADMIN_REPLY_Q_CI_OFFSET, adm_reply_ci);
4436 	sc->admin_reply_ci = adm_reply_ci;
4437 	sc->admin_reply_ephase = exp_phase;
4438 	mtx_lock_spin(&sc->admin_reply_lock);
4439 	sc->admin_in_use = false;
4440 	mtx_unlock_spin(&sc->admin_reply_lock);
4441 	return num_adm_reply;
4442 }
4443 
4444 static void
4445 mpi3mr_cmd_done(struct mpi3mr_softc *sc, struct mpi3mr_cmd *cmd)
4446 {
4447 	mpi3mr_unmap_request(sc, cmd);
4448 
4449 	mtx_lock(&sc->mpi3mr_mtx);
4450 	if (cmd->callout_owner) {
4451 		callout_stop(&cmd->callout);
4452 		cmd->callout_owner = false;
4453 	}
4454 
4455 	if (sc->unrecoverable)
4456 		mpi3mr_set_ccbstatus(cmd->ccb, CAM_DEV_NOT_THERE);
4457 
4458 	xpt_done(cmd->ccb);
4459 	cmd->ccb = NULL;
4460 	mtx_unlock(&sc->mpi3mr_mtx);
4461 	mpi3mr_release_command(cmd);
4462 }
4463 
4464 void mpi3mr_process_op_reply_desc(struct mpi3mr_softc *sc,
4465     Mpi3DefaultReplyDescriptor_t *reply_desc, U64 *reply_dma)
4466 {
4467 	U16 reply_desc_type, host_tag = 0;
4468 	U16 ioc_status = MPI3_IOCSTATUS_SUCCESS;
4469 	U32 ioc_loginfo = 0;
4470 	Mpi3StatusReplyDescriptor_t *status_desc = NULL;
4471 	Mpi3AddressReplyDescriptor_t *addr_desc = NULL;
4472 	Mpi3SuccessReplyDescriptor_t *success_desc = NULL;
4473 	Mpi3SCSIIOReply_t *scsi_reply = NULL;
4474 	U8 *sense_buf = NULL;
4475 	U8 scsi_state = 0, scsi_status = 0, sense_state = 0;
4476 	U32 xfer_count = 0, sense_count =0, resp_data = 0;
4477 	struct mpi3mr_cmd *cm = NULL;
4478 	union ccb *ccb;
4479 	struct ccb_scsiio *csio;
4480 	struct mpi3mr_cam_softc *cam_sc;
4481 	U32 target_id;
4482 	U8 *scsi_cdb;
4483 	struct mpi3mr_target *target = NULL;
4484 	U32 ioc_pend_data_len = 0, tg_pend_data_len = 0, data_len_blks = 0;
4485 	struct mpi3mr_throttle_group_info *tg = NULL;
4486 	U8 throttle_enabled_dev = 0;
4487 	static int ratelimit;
4488 
4489 	*reply_dma = 0;
4490 	reply_desc_type = reply_desc->ReplyFlags &
4491 			    MPI3_REPLY_DESCRIPT_FLAGS_TYPE_MASK;
4492 	switch (reply_desc_type) {
4493 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_STATUS:
4494 		status_desc = (Mpi3StatusReplyDescriptor_t *)reply_desc;
4495 		host_tag = status_desc->HostTag;
4496 		ioc_status = status_desc->IOCStatus;
4497 		if (ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
4498 			ioc_loginfo = status_desc->IOCLogInfo;
4499 		ioc_status &= MPI3_IOCSTATUS_STATUS_MASK;
4500 		break;
4501 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_ADDRESS_REPLY:
4502 		addr_desc = (Mpi3AddressReplyDescriptor_t *)reply_desc;
4503 		*reply_dma = addr_desc->ReplyFrameAddress;
4504 		scsi_reply = mpi3mr_get_reply_virt_addr(sc,
4505 		    *reply_dma);
4506 		if (scsi_reply == NULL) {
4507 			mpi3mr_dprint(sc, MPI3MR_ERROR, "scsi_reply is NULL, "
4508 			    "this shouldn't happen, reply_desc: %p\n",
4509 			    reply_desc);
4510 			goto out;
4511 		}
4512 
4513 		host_tag = scsi_reply->HostTag;
4514 		ioc_status = scsi_reply->IOCStatus;
4515 		scsi_status = scsi_reply->SCSIStatus;
4516 		scsi_state = scsi_reply->SCSIState;
4517 		sense_state = (scsi_state & MPI3_SCSI_STATE_SENSE_MASK);
4518 		xfer_count = scsi_reply->TransferCount;
4519 		sense_count = scsi_reply->SenseCount;
4520 		resp_data = scsi_reply->ResponseData;
4521 		sense_buf = mpi3mr_get_sensebuf_virt_addr(sc,
4522 		    scsi_reply->SenseDataBufferAddress);
4523 		if (ioc_status & MPI3_IOCSTATUS_STATUS_MASK)
4524 			ioc_loginfo = scsi_reply->IOCLogInfo;
4525 		ioc_status &= MPI3_IOCSTATUS_STATUS_MASK;
4526 		if (sense_state == MPI3_SCSI_STATE_SENSE_BUFF_Q_EMPTY)
4527 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Ran out of sense buffers\n");
4528 
4529 		break;
4530 	case MPI3_REPLY_DESCRIPT_FLAGS_TYPE_SUCCESS:
4531 		success_desc = (Mpi3SuccessReplyDescriptor_t *)reply_desc;
4532 		host_tag = success_desc->HostTag;
4533 
4534 	default:
4535 		break;
4536 	}
4537 
4538 	cm = sc->cmd_list[host_tag];
4539 
4540 	if (cm->state == MPI3MR_CMD_STATE_FREE)
4541 		goto out;
4542 
4543 	cam_sc = sc->cam_sc;
4544 	ccb = cm->ccb;
4545 	csio = &ccb->csio;
4546 	target_id = csio->ccb_h.target_id;
4547 
4548 	scsi_cdb = scsiio_cdb_ptr(csio);
4549 
4550 	target = mpi3mr_find_target_by_per_id(cam_sc, target_id);
4551 	if (sc->iot_enable) {
4552 		data_len_blks = csio->dxfer_len >> 9;
4553 
4554 		if (target) {
4555 			tg = target->throttle_group;
4556 			throttle_enabled_dev =
4557 				target->io_throttle_enabled;
4558 		}
4559 
4560 		if ((data_len_blks >= sc->io_throttle_data_length) &&
4561 		     throttle_enabled_dev) {
4562 			mpi3mr_atomic_sub(&sc->pend_large_data_sz, data_len_blks);
4563 			ioc_pend_data_len = mpi3mr_atomic_read(
4564 			    &sc->pend_large_data_sz);
4565 			if (tg) {
4566 				mpi3mr_atomic_sub(&tg->pend_large_data_sz,
4567 					data_len_blks);
4568 				tg_pend_data_len = mpi3mr_atomic_read(&tg->pend_large_data_sz);
4569 				if (ratelimit % 1000) {
4570 					mpi3mr_dprint(sc, MPI3MR_IOT,
4571 						"large vd_io completion persist_id(%d), handle(0x%04x), data_len(%d),"
4572 						"ioc_pending(%d), tg_pending(%d), ioc_low(%d), tg_low(%d)\n",
4573 						    target->per_id,
4574 						    target->dev_handle,
4575 						    data_len_blks, ioc_pend_data_len,
4576 						    tg_pend_data_len,
4577 						    sc->io_throttle_low,
4578 						    tg->low);
4579 					ratelimit++;
4580 				}
4581 				if (tg->io_divert  && ((ioc_pend_data_len <=
4582 				    sc->io_throttle_low) &&
4583 				    (tg_pend_data_len <= tg->low))) {
4584 					tg->io_divert = 0;
4585 					mpi3mr_dprint(sc, MPI3MR_IOT,
4586 						"VD: Coming out of divert perst_id(%d) tg_id(%d)\n",
4587 						target->per_id, tg->id);
4588 					mpi3mr_set_io_divert_for_all_vd_in_tg(
4589 					    sc, tg, 0);
4590 				}
4591 			} else {
4592 				if (ratelimit % 1000) {
4593 					mpi3mr_dprint(sc, MPI3MR_IOT,
4594 					    "large pd_io completion persist_id(%d), handle(0x%04x), data_len(%d), ioc_pending(%d), ioc_low(%d)\n",
4595 					    target->per_id,
4596 					    target->dev_handle,
4597 					    data_len_blks, ioc_pend_data_len,
4598 					    sc->io_throttle_low);
4599 					ratelimit++;
4600 				}
4601 
4602 				if (ioc_pend_data_len <= sc->io_throttle_low) {
4603 					target->io_divert = 0;
4604 					mpi3mr_dprint(sc, MPI3MR_IOT,
4605 						"PD: Coming out of divert perst_id(%d)\n",
4606 						target->per_id);
4607 				}
4608 			}
4609 
4610 			} else if (target->io_divert) {
4611 			ioc_pend_data_len = mpi3mr_atomic_read(&sc->pend_large_data_sz);
4612 			if (!tg) {
4613 				if (ratelimit % 1000) {
4614 					mpi3mr_dprint(sc, MPI3MR_IOT,
4615 					    "pd_io completion persist_id(%d), handle(0x%04x), data_len(%d), ioc_pending(%d), ioc_low(%d)\n",
4616 					    target->per_id,
4617 					    target->dev_handle,
4618 					    data_len_blks, ioc_pend_data_len,
4619 					    sc->io_throttle_low);
4620 					ratelimit++;
4621 				}
4622 
4623 				if ( ioc_pend_data_len <= sc->io_throttle_low) {
4624 					mpi3mr_dprint(sc, MPI3MR_IOT,
4625 						"PD: Coming out of divert perst_id(%d)\n",
4626 						target->per_id);
4627 					target->io_divert = 0;
4628 				}
4629 
4630 			} else if (ioc_pend_data_len <= sc->io_throttle_low) {
4631 				tg_pend_data_len = mpi3mr_atomic_read(&tg->pend_large_data_sz);
4632 				if (ratelimit % 1000) {
4633 					mpi3mr_dprint(sc, MPI3MR_IOT,
4634 						"vd_io completion persist_id(%d), handle(0x%04x), data_len(%d),"
4635 						"ioc_pending(%d), tg_pending(%d), ioc_low(%d), tg_low(%d)\n",
4636 						    target->per_id,
4637 						    target->dev_handle,
4638 						    data_len_blks, ioc_pend_data_len,
4639 						    tg_pend_data_len,
4640 						    sc->io_throttle_low,
4641 						    tg->low);
4642 					ratelimit++;
4643 				}
4644 				if (tg->io_divert  && (tg_pend_data_len <= tg->low)) {
4645 					tg->io_divert = 0;
4646 					mpi3mr_dprint(sc, MPI3MR_IOT,
4647 						"VD: Coming out of divert perst_id(%d) tg_id(%d)\n",
4648 						target->per_id, tg->id);
4649 					mpi3mr_set_io_divert_for_all_vd_in_tg(
4650 					    sc, tg, 0);
4651 				}
4652 
4653 			}
4654 		}
4655 	}
4656 
4657 	if (success_desc) {
4658 		mpi3mr_set_ccbstatus(ccb, CAM_REQ_CMP);
4659 		goto out_success;
4660 	}
4661 
4662 	if (ioc_status == MPI3_IOCSTATUS_SCSI_DATA_UNDERRUN
4663 	    && xfer_count == 0 && (scsi_status == MPI3_SCSI_STATUS_BUSY ||
4664 	    scsi_status == MPI3_SCSI_STATUS_RESERVATION_CONFLICT ||
4665 	    scsi_status == MPI3_SCSI_STATUS_TASK_SET_FULL))
4666 		ioc_status = MPI3_IOCSTATUS_SUCCESS;
4667 
4668 	if ((sense_state == MPI3_SCSI_STATE_SENSE_VALID) && sense_count
4669 	    && sense_buf) {
4670 		int sense_len, returned_sense_len;
4671 
4672 		returned_sense_len = min(le32toh(sense_count),
4673 		    sizeof(struct scsi_sense_data));
4674 		if (returned_sense_len < csio->sense_len)
4675 			csio->sense_resid = csio->sense_len -
4676 			    returned_sense_len;
4677 		else
4678 			csio->sense_resid = 0;
4679 
4680 		sense_len = min(returned_sense_len,
4681 		    csio->sense_len - csio->sense_resid);
4682 		bzero(&csio->sense_data, sizeof(csio->sense_data));
4683 		bcopy(sense_buf, &csio->sense_data, sense_len);
4684 		ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
4685 	}
4686 
4687 	switch (ioc_status) {
4688 	case MPI3_IOCSTATUS_BUSY:
4689 	case MPI3_IOCSTATUS_INSUFFICIENT_RESOURCES:
4690 		mpi3mr_set_ccbstatus(ccb, CAM_REQUEUE_REQ);
4691 		break;
4692 	case MPI3_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
4693 		/*
4694 		 * If devinfo is 0 this will be a volume.  In that case don't
4695 		 * tell CAM that the volume is not there.  We want volumes to
4696 		 * be enumerated until they are deleted/removed, not just
4697 		 * failed.
4698 		 */
4699 		if (cm->targ->devinfo == 0)
4700 			mpi3mr_set_ccbstatus(ccb, CAM_REQ_CMP);
4701 		else
4702 			mpi3mr_set_ccbstatus(ccb, CAM_DEV_NOT_THERE);
4703 		break;
4704 	case MPI3_IOCSTATUS_SCSI_TASK_TERMINATED:
4705 	case MPI3_IOCSTATUS_SCSI_IOC_TERMINATED:
4706 	case MPI3_IOCSTATUS_SCSI_EXT_TERMINATED:
4707 		mpi3mr_set_ccbstatus(ccb, CAM_SCSI_BUSY);
4708 		mpi3mr_dprint(sc, MPI3MR_TRACE,
4709 		    "func: %s line:%d tgt %u Hosttag %u loginfo %x\n",
4710 		    __func__, __LINE__,
4711 		    target_id, cm->hosttag,
4712 		    le32toh(scsi_reply->IOCLogInfo));
4713 		mpi3mr_dprint(sc, MPI3MR_TRACE,
4714 		    "SCSIStatus %x SCSIState %x xfercount %u\n",
4715 		    scsi_reply->SCSIStatus, scsi_reply->SCSIState,
4716 		    le32toh(xfer_count));
4717 		break;
4718 	case MPI3_IOCSTATUS_SCSI_DATA_OVERRUN:
4719 		/* resid is ignored for this condition */
4720 		csio->resid = 0;
4721 		mpi3mr_set_ccbstatus(ccb, CAM_DATA_RUN_ERR);
4722 		break;
4723 	case MPI3_IOCSTATUS_SCSI_DATA_UNDERRUN:
4724 		csio->resid = cm->length - le32toh(xfer_count);
4725 	case MPI3_IOCSTATUS_SCSI_RECOVERED_ERROR:
4726 	case MPI3_IOCSTATUS_SUCCESS:
4727 		if ((scsi_reply->IOCStatus & MPI3_IOCSTATUS_STATUS_MASK) ==
4728 		    MPI3_IOCSTATUS_SCSI_RECOVERED_ERROR)
4729 			mpi3mr_dprint(sc, MPI3MR_XINFO, "func: %s line: %d recovered error\n",  __func__, __LINE__);
4730 
4731 		/* Completion failed at the transport level. */
4732 		if (scsi_reply->SCSIState & (MPI3_SCSI_STATE_NO_SCSI_STATUS |
4733 		    MPI3_SCSI_STATE_TERMINATED)) {
4734 			mpi3mr_set_ccbstatus(ccb, CAM_REQ_CMP_ERR);
4735 			break;
4736 		}
4737 
4738 		/* In a modern packetized environment, an autosense failure
4739 		 * implies that there's not much else that can be done to
4740 		 * recover the command.
4741 		 */
4742 		if (scsi_reply->SCSIState & MPI3_SCSI_STATE_SENSE_VALID) {
4743 			mpi3mr_set_ccbstatus(ccb, CAM_AUTOSENSE_FAIL);
4744 			break;
4745 		}
4746 
4747 		/*
4748 		 * Intentionally override the normal SCSI status reporting
4749 		 * for these two cases.  These are likely to happen in a
4750 		 * multi-initiator environment, and we want to make sure that
4751 		 * CAM retries these commands rather than fail them.
4752 		 */
4753 		if ((scsi_reply->SCSIStatus == MPI3_SCSI_STATUS_COMMAND_TERMINATED) ||
4754 		    (scsi_reply->SCSIStatus == MPI3_SCSI_STATUS_TASK_ABORTED)) {
4755 			mpi3mr_set_ccbstatus(ccb, CAM_REQ_ABORTED);
4756 			break;
4757 		}
4758 
4759 		/* Handle normal status and sense */
4760 		csio->scsi_status = scsi_reply->SCSIStatus;
4761 		if (scsi_reply->SCSIStatus == MPI3_SCSI_STATUS_GOOD)
4762 			mpi3mr_set_ccbstatus(ccb, CAM_REQ_CMP);
4763 		else
4764 			mpi3mr_set_ccbstatus(ccb, CAM_SCSI_STATUS_ERROR);
4765 
4766 		if (scsi_reply->SCSIState & MPI3_SCSI_STATE_SENSE_VALID) {
4767 			int sense_len, returned_sense_len;
4768 
4769 			returned_sense_len = min(le32toh(scsi_reply->SenseCount),
4770 			    sizeof(struct scsi_sense_data));
4771 			if (returned_sense_len < csio->sense_len)
4772 				csio->sense_resid = csio->sense_len -
4773 				    returned_sense_len;
4774 			else
4775 				csio->sense_resid = 0;
4776 
4777 			sense_len = min(returned_sense_len,
4778 			    csio->sense_len - csio->sense_resid);
4779 			bzero(&csio->sense_data, sizeof(csio->sense_data));
4780 			bcopy(cm->sense, &csio->sense_data, sense_len);
4781 			ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
4782 		}
4783 
4784 		break;
4785 	case MPI3_IOCSTATUS_INVALID_SGL:
4786 		mpi3mr_set_ccbstatus(ccb, CAM_UNREC_HBA_ERROR);
4787 		break;
4788 	case MPI3_IOCSTATUS_EEDP_GUARD_ERROR:
4789 	case MPI3_IOCSTATUS_EEDP_REF_TAG_ERROR:
4790 	case MPI3_IOCSTATUS_EEDP_APP_TAG_ERROR:
4791 	case MPI3_IOCSTATUS_SCSI_PROTOCOL_ERROR:
4792 	case MPI3_IOCSTATUS_INVALID_FUNCTION:
4793 	case MPI3_IOCSTATUS_INTERNAL_ERROR:
4794 	case MPI3_IOCSTATUS_INVALID_FIELD:
4795 	case MPI3_IOCSTATUS_INVALID_STATE:
4796 	case MPI3_IOCSTATUS_SCSI_IO_DATA_ERROR:
4797 	case MPI3_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
4798 	case MPI3_IOCSTATUS_INSUFFICIENT_POWER:
4799 	case MPI3_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
4800 	default:
4801 		csio->resid = cm->length;
4802 		mpi3mr_set_ccbstatus(ccb, CAM_REQ_CMP_ERR);
4803 		break;
4804 	}
4805 
4806 out_success:
4807 	if (mpi3mr_get_ccbstatus(ccb) != CAM_REQ_CMP) {
4808 		ccb->ccb_h.status |= CAM_DEV_QFRZN;
4809 		xpt_freeze_devq(ccb->ccb_h.path, /*count*/ 1);
4810 	}
4811 
4812 	mpi3mr_atomic_dec(&cm->targ->outstanding);
4813 	mpi3mr_cmd_done(sc, cm);
4814 	mpi3mr_dprint(sc, MPI3MR_TRACE, "Completion IO path :"
4815 		" cdb[0]: %x targetid: 0x%x SMID: %x ioc_status: 0x%x ioc_loginfo: 0x%x scsi_status: 0x%x "
4816 		"scsi_state: 0x%x response_data: 0x%x\n", scsi_cdb[0], target_id, host_tag,
4817 		ioc_status, ioc_loginfo, scsi_status, scsi_state, resp_data);
4818 	mpi3mr_atomic_dec(&sc->fw_outstanding);
4819 out:
4820 
4821 	if (sense_buf)
4822 		mpi3mr_repost_sense_buf(sc,
4823 		    scsi_reply->SenseDataBufferAddress);
4824 	return;
4825 }
4826 
4827 /*
4828  * mpi3mr_complete_io_cmd:	ISR routine for IO commands
4829  * @sc:				Adapter's soft instance
4830  * @irq_ctx:			Driver's internal per IRQ structure
4831  *
4832  * This function processes IO command completions.
4833  */
4834 int mpi3mr_complete_io_cmd(struct mpi3mr_softc *sc,
4835     struct mpi3mr_irq_context *irq_ctx)
4836 {
4837 	struct mpi3mr_op_reply_queue *op_reply_q = irq_ctx->op_reply_q;
4838 	U32 exp_phase = op_reply_q->ephase;
4839 	U32 reply_ci = op_reply_q->ci;
4840 	U32 num_op_replies = 0;
4841 	U64 reply_dma = 0;
4842 	Mpi3DefaultReplyDescriptor_t *reply_desc;
4843 	U16 req_qid = 0, threshold_comps = 0;
4844 
4845 	mtx_lock_spin(&op_reply_q->q_lock);
4846 	if (op_reply_q->in_use == false) {
4847 		op_reply_q->in_use = true;
4848 		mtx_unlock_spin(&op_reply_q->q_lock);
4849 	} else {
4850 		mtx_unlock_spin(&op_reply_q->q_lock);
4851 		return 0;
4852 	}
4853 
4854 	reply_desc = (Mpi3DefaultReplyDescriptor_t *)op_reply_q->q_base + reply_ci;
4855 	mpi3mr_dprint(sc, MPI3MR_TRACE, "[QID:%d]:reply_desc: (%pa) reply_ci: %x"
4856 		" reply_desc->ReplyFlags: 0x%x\n"
4857 		"reply_q_base_phys: %#016jx reply_q_base: (%pa) exp_phase: %x\n",
4858 		op_reply_q->qid, reply_desc, reply_ci, reply_desc->ReplyFlags, op_reply_q->q_base_phys,
4859 		op_reply_q->q_base, exp_phase);
4860 
4861 	if (((reply_desc->ReplyFlags &
4862 	     MPI3_REPLY_DESCRIPT_FLAGS_PHASE_MASK) != exp_phase) || !op_reply_q->qid) {
4863 		mtx_lock_spin(&op_reply_q->q_lock);
4864 		op_reply_q->in_use = false;
4865 		mtx_unlock_spin(&op_reply_q->q_lock);
4866 		return 0;
4867 	}
4868 
4869 	do {
4870 		req_qid = reply_desc->RequestQueueID;
4871 		sc->op_req_q[req_qid - 1].ci =
4872 		    reply_desc->RequestQueueCI;
4873 
4874 		mpi3mr_process_op_reply_desc(sc, reply_desc, &reply_dma);
4875 		mpi3mr_atomic_dec(&op_reply_q->pend_ios);
4876 		if (reply_dma)
4877 			mpi3mr_repost_reply_buf(sc, reply_dma);
4878 		num_op_replies++;
4879 		if (++reply_ci == op_reply_q->num_replies) {
4880 			reply_ci = 0;
4881 			exp_phase ^= 1;
4882 		}
4883 		reply_desc =
4884 		    (Mpi3DefaultReplyDescriptor_t *)op_reply_q->q_base + reply_ci;
4885 		if ((reply_desc->ReplyFlags &
4886 		     MPI3_REPLY_DESCRIPT_FLAGS_PHASE_MASK) != exp_phase)
4887 			break;
4888 
4889 		if (++threshold_comps == MPI3MR_THRESHOLD_REPLY_COUNT) {
4890 			mpi3mr_regwrite(sc, MPI3_SYSIF_OPER_REPLY_Q_N_CI_OFFSET(op_reply_q->qid), reply_ci);
4891 			threshold_comps = 0;
4892 		}
4893 
4894 	} while (1);
4895 
4896 
4897 	mpi3mr_regwrite(sc, MPI3_SYSIF_OPER_REPLY_Q_N_CI_OFFSET(op_reply_q->qid), reply_ci);
4898 	op_reply_q->ci = reply_ci;
4899 	op_reply_q->ephase = exp_phase;
4900 	mtx_lock_spin(&op_reply_q->q_lock);
4901 	op_reply_q->in_use = false;
4902 	mtx_unlock_spin(&op_reply_q->q_lock);
4903 	return num_op_replies;
4904 }
4905 
4906 /*
4907  * mpi3mr_isr:			Primary ISR function
4908  * privdata:			Driver's internal per IRQ structure
4909  *
4910  * This is driver's primary ISR function which is being called whenever any admin/IO
4911  * command completion.
4912  */
4913 void mpi3mr_isr(void *privdata)
4914 {
4915 	struct mpi3mr_irq_context *irq_ctx = (struct mpi3mr_irq_context *)privdata;
4916 	struct mpi3mr_softc *sc = irq_ctx->sc;
4917 	U16 msi_idx;
4918 
4919 	if (!irq_ctx)
4920 		return;
4921 
4922 	msi_idx = irq_ctx->msix_index;
4923 
4924 	if (!sc->intr_enabled)
4925 		return;
4926 
4927 	if (!msi_idx)
4928 		mpi3mr_complete_admin_cmd(sc);
4929 
4930 	if (irq_ctx->op_reply_q && irq_ctx->op_reply_q->qid) {
4931 		mpi3mr_complete_io_cmd(sc, irq_ctx);
4932 	}
4933 }
4934 
4935 /*
4936  * mpi3mr_alloc_requests - Allocates host commands
4937  * @sc: Adapter reference
4938  *
4939  * This function allocates controller supported host commands
4940  *
4941  * Return: 0 on success and proper error codes on failure
4942  */
4943 int
4944 mpi3mr_alloc_requests(struct mpi3mr_softc *sc)
4945 {
4946 	struct mpi3mr_cmd *cmd;
4947 	int i, j, nsegs, ret;
4948 
4949 	nsegs = MPI3MR_SG_DEPTH;
4950 	ret = bus_dma_tag_create( sc->mpi3mr_parent_dmat,    /* parent */
4951 				1, 0,			/* algnmnt, boundary */
4952 				sc->dma_loaddr,		/* lowaddr */
4953 				BUS_SPACE_MAXADDR,	/* highaddr */
4954 				NULL, NULL,		/* filter, filterarg */
4955 				BUS_SPACE_MAXSIZE,	/* maxsize */
4956                                 nsegs,			/* nsegments */
4957 				BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
4958                                 BUS_DMA_ALLOCNOW,	/* flags */
4959                                 busdma_lock_mutex,	/* lockfunc */
4960 				&sc->io_lock,	/* lockarg */
4961 				&sc->buffer_dmat);
4962 	if (ret) {
4963 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate buffer DMA tag ret: %d\n", ret);
4964 		return (ENOMEM);
4965         }
4966 
4967 	/*
4968 	 * sc->cmd_list is an array of struct mpi3mr_cmd pointers.
4969 	 * Allocate the dynamic array first and then allocate individual
4970 	 * commands.
4971 	 */
4972 	sc->cmd_list = malloc(sizeof(struct mpi3mr_cmd *) * sc->max_host_ios,
4973 	    M_MPI3MR, M_NOWAIT | M_ZERO);
4974 
4975 	if (!sc->cmd_list) {
4976 		device_printf(sc->mpi3mr_dev, "Cannot alloc memory for mpt_cmd_list.\n");
4977 		return (ENOMEM);
4978 	}
4979 
4980 	for (i = 0; i < sc->max_host_ios; i++) {
4981 		sc->cmd_list[i] = malloc(sizeof(struct mpi3mr_cmd),
4982 		    M_MPI3MR, M_NOWAIT | M_ZERO);
4983 		if (!sc->cmd_list[i]) {
4984 			for (j = 0; j < i; j++)
4985 				free(sc->cmd_list[j], M_MPI3MR);
4986 			free(sc->cmd_list, M_MPI3MR);
4987 			sc->cmd_list = NULL;
4988 			return (ENOMEM);
4989 		}
4990 	}
4991 
4992 	for (i = 1; i < sc->max_host_ios; i++) {
4993 		cmd = sc->cmd_list[i];
4994 		cmd->hosttag = i;
4995 		cmd->sc = sc;
4996 		cmd->state = MPI3MR_CMD_STATE_BUSY;
4997 		callout_init_mtx(&cmd->callout, &sc->mpi3mr_mtx, 0);
4998 		cmd->ccb = NULL;
4999 		TAILQ_INSERT_TAIL(&(sc->cmd_list_head), cmd, next);
5000 		if (bus_dmamap_create(sc->buffer_dmat, 0, &cmd->dmamap))
5001 			return ENOMEM;
5002 	}
5003 	return (0);
5004 }
5005 
5006 /*
5007  * mpi3mr_get_command:		Get a coomand structure from free command pool
5008  * @sc:				Adapter soft instance
5009  * Return:			MPT command reference
5010  *
5011  * This function returns an MPT command to the caller.
5012  */
5013 struct mpi3mr_cmd *
5014 mpi3mr_get_command(struct mpi3mr_softc *sc)
5015 {
5016 	struct mpi3mr_cmd *cmd = NULL;
5017 
5018 	mtx_lock(&sc->cmd_pool_lock);
5019 	if (!TAILQ_EMPTY(&sc->cmd_list_head)) {
5020 		cmd = TAILQ_FIRST(&sc->cmd_list_head);
5021 		TAILQ_REMOVE(&sc->cmd_list_head, cmd, next);
5022 	} else {
5023 		goto out;
5024 	}
5025 
5026 	mpi3mr_dprint(sc, MPI3MR_TRACE, "Get command SMID: 0x%x\n", cmd->hosttag);
5027 
5028 	memset((uint8_t *)&cmd->io_request, 0, MPI3MR_AREQ_FRAME_SZ);
5029 	cmd->data_dir = 0;
5030 	cmd->ccb = NULL;
5031 	cmd->targ = NULL;
5032 	cmd->state = MPI3MR_CMD_STATE_BUSY;
5033 	cmd->data = NULL;
5034 	cmd->length = 0;
5035 out:
5036 	mtx_unlock(&sc->cmd_pool_lock);
5037 	return cmd;
5038 }
5039 
5040 /*
5041  * mpi3mr_release_command:	Return a cmd to free command pool
5042  * input:			Command packet for return to free command pool
5043  *
5044  * This function returns an MPT command to the free command list.
5045  */
5046 void
5047 mpi3mr_release_command(struct mpi3mr_cmd *cmd)
5048 {
5049 	struct mpi3mr_softc *sc = cmd->sc;
5050 
5051 	mtx_lock(&sc->cmd_pool_lock);
5052 	TAILQ_INSERT_HEAD(&(sc->cmd_list_head), cmd, next);
5053 	cmd->state = MPI3MR_CMD_STATE_FREE;
5054 	cmd->req_qidx = 0;
5055 	mpi3mr_dprint(sc, MPI3MR_TRACE, "Release command SMID: 0x%x\n", cmd->hosttag);
5056 	mtx_unlock(&sc->cmd_pool_lock);
5057 
5058 	return;
5059 }
5060 
5061  /**
5062  * mpi3mr_free_ioctl_dma_memory - free memory for ioctl dma
5063  * @sc: Adapter instance reference
5064  *
5065  * Free the DMA memory allocated for IOCTL handling purpose.
5066  *
5067  * Return: None
5068  */
5069 static void mpi3mr_free_ioctl_dma_memory(struct mpi3mr_softc *sc)
5070 {
5071 	U16 i;
5072 	struct dma_memory_desc *mem_desc;
5073 
5074 	for (i=0; i<MPI3MR_NUM_IOCTL_SGE; i++) {
5075 		mem_desc = &sc->ioctl_sge[i];
5076 		if (mem_desc->addr && mem_desc->dma_addr) {
5077 			bus_dmamap_unload(mem_desc->tag, mem_desc->dmamap);
5078 			bus_dmamem_free(mem_desc->tag, mem_desc->addr, mem_desc->dmamap);
5079 			mem_desc->addr = NULL;
5080 			if (mem_desc->tag != NULL)
5081 				bus_dma_tag_destroy(mem_desc->tag);
5082 		}
5083 	}
5084 
5085 	mem_desc = &sc->ioctl_chain_sge;
5086 	if (mem_desc->addr && mem_desc->dma_addr) {
5087 		bus_dmamap_unload(mem_desc->tag, mem_desc->dmamap);
5088 		bus_dmamem_free(mem_desc->tag, mem_desc->addr, mem_desc->dmamap);
5089 		mem_desc->addr = NULL;
5090 		if (mem_desc->tag != NULL)
5091 			bus_dma_tag_destroy(mem_desc->tag);
5092 	}
5093 
5094 	mem_desc = &sc->ioctl_resp_sge;
5095 	if (mem_desc->addr && mem_desc->dma_addr) {
5096 		bus_dmamap_unload(mem_desc->tag, mem_desc->dmamap);
5097 		bus_dmamem_free(mem_desc->tag, mem_desc->addr, mem_desc->dmamap);
5098 		mem_desc->addr = NULL;
5099 		if (mem_desc->tag != NULL)
5100 			bus_dma_tag_destroy(mem_desc->tag);
5101 	}
5102 
5103 	sc->ioctl_sges_allocated = false;
5104 }
5105 
5106 /**
5107  * mpi3mr_alloc_ioctl_dma_memory - Alloc memory for ioctl dma
5108  * @sc: Adapter instance reference
5109  *
5110  * This function allocates dmaable memory required to handle the
5111  * application issued MPI3 IOCTL requests.
5112  *
5113  * Return: None
5114  */
5115 void mpi3mr_alloc_ioctl_dma_memory(struct mpi3mr_softc *sc)
5116 {
5117 	struct dma_memory_desc *mem_desc;
5118 	U16 i;
5119 
5120 	for (i=0; i<MPI3MR_NUM_IOCTL_SGE; i++) {
5121 		mem_desc = &sc->ioctl_sge[i];
5122 		mem_desc->size = MPI3MR_IOCTL_SGE_SIZE;
5123 
5124 		if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
5125 					4, 0,			/* algnmnt, boundary */
5126 					sc->dma_loaddr,		/* lowaddr */
5127 					BUS_SPACE_MAXADDR,	/* highaddr */
5128 					NULL, NULL,		/* filter, filterarg */
5129 					mem_desc->size,		/* maxsize */
5130 					1,			/* nsegments */
5131 					mem_desc->size,		/* maxsegsize */
5132 					0,			/* flags */
5133 					NULL, NULL,		/* lockfunc, lockarg */
5134 					&mem_desc->tag)) {
5135 			mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
5136 			goto out_failed;
5137 		}
5138 
5139 		if (bus_dmamem_alloc(mem_desc->tag, (void **)&mem_desc->addr,
5140 		    BUS_DMA_NOWAIT, &mem_desc->dmamap)) {
5141 			mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
5142 			goto out_failed;
5143 		}
5144 		bzero(mem_desc->addr, mem_desc->size);
5145 		bus_dmamap_load(mem_desc->tag, mem_desc->dmamap, mem_desc->addr, mem_desc->size,
5146 		    mpi3mr_memaddr_cb, &mem_desc->dma_addr, BUS_DMA_NOWAIT);
5147 
5148 		if (!mem_desc->addr)
5149 			goto out_failed;
5150 	}
5151 
5152 	mem_desc = &sc->ioctl_chain_sge;
5153 	mem_desc->size = MPI3MR_4K_PGSZ;
5154 	if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
5155 				4, 0,			/* algnmnt, boundary */
5156 				sc->dma_loaddr,		/* lowaddr */
5157 				BUS_SPACE_MAXADDR,	/* highaddr */
5158 				NULL, NULL,		/* filter, filterarg */
5159 				mem_desc->size,		/* maxsize */
5160 				1,			/* nsegments */
5161 				mem_desc->size,		/* maxsegsize */
5162 				0,			/* flags */
5163 				NULL, NULL,		/* lockfunc, lockarg */
5164 				&mem_desc->tag)) {
5165 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
5166 		goto out_failed;
5167 	}
5168 
5169 	if (bus_dmamem_alloc(mem_desc->tag, (void **)&mem_desc->addr,
5170 	    BUS_DMA_NOWAIT, &mem_desc->dmamap)) {
5171 		mpi3mr_dprint(sc, MPI3MR_ERROR, "%s: Cannot allocate replies memory\n", __func__);
5172 		goto out_failed;
5173 	}
5174 	bzero(mem_desc->addr, mem_desc->size);
5175 	bus_dmamap_load(mem_desc->tag, mem_desc->dmamap, mem_desc->addr, mem_desc->size,
5176 	    mpi3mr_memaddr_cb, &mem_desc->dma_addr, BUS_DMA_NOWAIT);
5177 
5178 	if (!mem_desc->addr)
5179 		goto out_failed;
5180 
5181 	mem_desc = &sc->ioctl_resp_sge;
5182 	mem_desc->size = MPI3MR_4K_PGSZ;
5183 	if (bus_dma_tag_create(sc->mpi3mr_parent_dmat,    /* parent */
5184 				4, 0,			/* algnmnt, boundary */
5185 				sc->dma_loaddr,		/* lowaddr */
5186 				BUS_SPACE_MAXADDR,	/* highaddr */
5187 				NULL, NULL,		/* filter, filterarg */
5188 				mem_desc->size,		/* maxsize */
5189 				1,			/* nsegments */
5190 				mem_desc->size,		/* maxsegsize */
5191 				0,			/* flags */
5192 				NULL, NULL,		/* lockfunc, lockarg */
5193 				&mem_desc->tag)) {
5194 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate request DMA tag\n");
5195 		goto out_failed;
5196 	}
5197 
5198 	if (bus_dmamem_alloc(mem_desc->tag, (void **)&mem_desc->addr,
5199 	    BUS_DMA_NOWAIT, &mem_desc->dmamap)) {
5200 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Cannot allocate replies memory\n");
5201 		goto out_failed;
5202 	}
5203 	bzero(mem_desc->addr, mem_desc->size);
5204 	bus_dmamap_load(mem_desc->tag, mem_desc->dmamap, mem_desc->addr, mem_desc->size,
5205 	    mpi3mr_memaddr_cb, &mem_desc->dma_addr, BUS_DMA_NOWAIT);
5206 
5207 	if (!mem_desc->addr)
5208 		goto out_failed;
5209 
5210 	sc->ioctl_sges_allocated = true;
5211 
5212 	return;
5213 out_failed:
5214 	printf("cannot allocate DMA memory for the mpt commands"
5215 	    "  from the applications, application interface for MPT command is disabled\n");
5216 	mpi3mr_free_ioctl_dma_memory(sc);
5217 }
5218 
5219 void
5220 mpi3mr_destory_mtx(struct mpi3mr_softc *sc)
5221 {
5222 	int i;
5223 	struct mpi3mr_op_req_queue *op_req_q;
5224 	struct mpi3mr_op_reply_queue *op_reply_q;
5225 
5226 	if (sc->admin_reply) {
5227 		if (mtx_initialized(&sc->admin_reply_lock))
5228 			mtx_destroy(&sc->admin_reply_lock);
5229 	}
5230 
5231 	if (sc->op_reply_q) {
5232 		for(i = 0; i < sc->num_queues; i++) {
5233 			op_reply_q = sc->op_reply_q + i;
5234 			if (mtx_initialized(&op_reply_q->q_lock))
5235 				mtx_destroy(&op_reply_q->q_lock);
5236 		}
5237 	}
5238 
5239 	if (sc->op_req_q) {
5240 		for(i = 0; i < sc->num_queues; i++) {
5241 			op_req_q = sc->op_req_q + i;
5242 			if (mtx_initialized(&op_req_q->q_lock))
5243 				mtx_destroy(&op_req_q->q_lock);
5244 		}
5245 	}
5246 
5247 	if (mtx_initialized(&sc->init_cmds.completion.lock))
5248 		mtx_destroy(&sc->init_cmds.completion.lock);
5249 
5250 	if (mtx_initialized(&sc->ioctl_cmds.completion.lock))
5251 		mtx_destroy(&sc->ioctl_cmds.completion.lock);
5252 
5253 	if (mtx_initialized(&sc->host_tm_cmds.completion.lock))
5254 		mtx_destroy(&sc->host_tm_cmds.completion.lock);
5255 
5256 	for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++) {
5257 		if (mtx_initialized(&sc->dev_rmhs_cmds[i].completion.lock))
5258 			mtx_destroy(&sc->dev_rmhs_cmds[i].completion.lock);
5259 	}
5260 
5261 	if (mtx_initialized(&sc->reset_mutex))
5262 		mtx_destroy(&sc->reset_mutex);
5263 
5264 	if (mtx_initialized(&sc->target_lock))
5265 		mtx_destroy(&sc->target_lock);
5266 
5267 	if (mtx_initialized(&sc->fwevt_lock))
5268 		mtx_destroy(&sc->fwevt_lock);
5269 
5270 	if (mtx_initialized(&sc->cmd_pool_lock))
5271 		mtx_destroy(&sc->cmd_pool_lock);
5272 
5273 	if (mtx_initialized(&sc->reply_free_q_lock))
5274 		mtx_destroy(&sc->reply_free_q_lock);
5275 
5276 	if (mtx_initialized(&sc->sense_buf_q_lock))
5277 		mtx_destroy(&sc->sense_buf_q_lock);
5278 
5279 	if (mtx_initialized(&sc->chain_buf_lock))
5280 		mtx_destroy(&sc->chain_buf_lock);
5281 
5282 	if (mtx_initialized(&sc->admin_req_lock))
5283 		mtx_destroy(&sc->admin_req_lock);
5284 
5285 	if (mtx_initialized(&sc->mpi3mr_mtx))
5286 		mtx_destroy(&sc->mpi3mr_mtx);
5287 }
5288 
5289 /**
5290  * mpi3mr_free_mem - Freeup adapter level data structures
5291  * @sc: Adapter reference
5292  *
5293  * Return: Nothing.
5294  */
5295 void
5296 mpi3mr_free_mem(struct mpi3mr_softc *sc)
5297 {
5298 	int i;
5299 	struct mpi3mr_op_req_queue *op_req_q;
5300 	struct mpi3mr_op_reply_queue *op_reply_q;
5301 	struct mpi3mr_irq_context *irq_ctx;
5302 
5303 	if (sc->cmd_list) {
5304 		for (i = 0; i < sc->max_host_ios; i++) {
5305 			free(sc->cmd_list[i], M_MPI3MR);
5306 		}
5307 		free(sc->cmd_list, M_MPI3MR);
5308 		sc->cmd_list = NULL;
5309 	}
5310 
5311 	if (sc->pel_seq_number && sc->pel_seq_number_dma) {
5312 		bus_dmamap_unload(sc->pel_seq_num_dmatag, sc->pel_seq_num_dmamap);
5313 		bus_dmamem_free(sc->pel_seq_num_dmatag, sc->pel_seq_number, sc->pel_seq_num_dmamap);
5314 		sc->pel_seq_number = NULL;
5315 		if (sc->pel_seq_num_dmatag != NULL)
5316 			bus_dma_tag_destroy(sc->pel_seq_num_dmatag);
5317 	}
5318 
5319 	if (sc->throttle_groups) {
5320 		free(sc->throttle_groups, M_MPI3MR);
5321 		sc->throttle_groups = NULL;
5322 	}
5323 
5324 	/* Free up operational queues*/
5325 	if (sc->op_req_q) {
5326 		for (i = 0; i < sc->num_queues; i++) {
5327 			op_req_q = sc->op_req_q + i;
5328 			if (op_req_q->q_base && op_req_q->q_base_phys) {
5329 				bus_dmamap_unload(op_req_q->q_base_tag, op_req_q->q_base_dmamap);
5330 				bus_dmamem_free(op_req_q->q_base_tag, op_req_q->q_base, op_req_q->q_base_dmamap);
5331 				op_req_q->q_base = NULL;
5332 				if (op_req_q->q_base_tag != NULL)
5333 					bus_dma_tag_destroy(op_req_q->q_base_tag);
5334 			}
5335 		}
5336 		free(sc->op_req_q, M_MPI3MR);
5337 		sc->op_req_q = NULL;
5338 	}
5339 
5340 	if (sc->op_reply_q) {
5341 		for (i = 0; i < sc->num_queues; i++) {
5342 			op_reply_q = sc->op_reply_q + i;
5343 			if (op_reply_q->q_base && op_reply_q->q_base_phys) {
5344 				bus_dmamap_unload(op_reply_q->q_base_tag, op_reply_q->q_base_dmamap);
5345 				bus_dmamem_free(op_reply_q->q_base_tag, op_reply_q->q_base, op_reply_q->q_base_dmamap);
5346 				op_reply_q->q_base = NULL;
5347 				if (op_reply_q->q_base_tag != NULL)
5348 					bus_dma_tag_destroy(op_reply_q->q_base_tag);
5349 			}
5350 		}
5351 		free(sc->op_reply_q, M_MPI3MR);
5352 		sc->op_reply_q = NULL;
5353 	}
5354 
5355 	/* Free up chain buffers*/
5356 	if (sc->chain_sgl_list) {
5357 		for (i = 0; i < sc->chain_buf_count; i++) {
5358 			if (sc->chain_sgl_list[i].buf && sc->chain_sgl_list[i].buf_phys) {
5359 				bus_dmamap_unload(sc->chain_sgl_list_tag, sc->chain_sgl_list[i].buf_dmamap);
5360 				bus_dmamem_free(sc->chain_sgl_list_tag, sc->chain_sgl_list[i].buf,
5361 						sc->chain_sgl_list[i].buf_dmamap);
5362 				sc->chain_sgl_list[i].buf = NULL;
5363 			}
5364 		}
5365 		if (sc->chain_sgl_list_tag != NULL)
5366 			bus_dma_tag_destroy(sc->chain_sgl_list_tag);
5367 		free(sc->chain_sgl_list, M_MPI3MR);
5368 		sc->chain_sgl_list = NULL;
5369 	}
5370 
5371 	if (sc->chain_bitmap) {
5372 		free(sc->chain_bitmap, M_MPI3MR);
5373 		sc->chain_bitmap = NULL;
5374 	}
5375 
5376 	for (i = 0; i < sc->msix_count; i++) {
5377 		irq_ctx = sc->irq_ctx + i;
5378 		if (irq_ctx)
5379 			irq_ctx->op_reply_q = NULL;
5380 	}
5381 
5382 	/* Free reply_buf_tag */
5383 	if (sc->reply_buf && sc->reply_buf_phys) {
5384 		bus_dmamap_unload(sc->reply_buf_tag, sc->reply_buf_dmamap);
5385 		bus_dmamem_free(sc->reply_buf_tag, sc->reply_buf,
5386 				sc->reply_buf_dmamap);
5387 		sc->reply_buf = NULL;
5388 		if (sc->reply_buf_tag != NULL)
5389 			bus_dma_tag_destroy(sc->reply_buf_tag);
5390 	}
5391 
5392 	/* Free reply_free_q_tag */
5393 	if (sc->reply_free_q && sc->reply_free_q_phys) {
5394 		bus_dmamap_unload(sc->reply_free_q_tag, sc->reply_free_q_dmamap);
5395 		bus_dmamem_free(sc->reply_free_q_tag, sc->reply_free_q,
5396 				sc->reply_free_q_dmamap);
5397 		sc->reply_free_q = NULL;
5398 		if (sc->reply_free_q_tag != NULL)
5399 			bus_dma_tag_destroy(sc->reply_free_q_tag);
5400 	}
5401 
5402 	/* Free sense_buf_tag */
5403 	if (sc->sense_buf && sc->sense_buf_phys) {
5404 		bus_dmamap_unload(sc->sense_buf_tag, sc->sense_buf_dmamap);
5405 		bus_dmamem_free(sc->sense_buf_tag, sc->sense_buf,
5406 				sc->sense_buf_dmamap);
5407 		sc->sense_buf = NULL;
5408 		if (sc->sense_buf_tag != NULL)
5409 			bus_dma_tag_destroy(sc->sense_buf_tag);
5410 	}
5411 
5412 	/* Free sense_buf_q_tag */
5413 	if (sc->sense_buf_q && sc->sense_buf_q_phys) {
5414 		bus_dmamap_unload(sc->sense_buf_q_tag, sc->sense_buf_q_dmamap);
5415 		bus_dmamem_free(sc->sense_buf_q_tag, sc->sense_buf_q,
5416 				sc->sense_buf_q_dmamap);
5417 		sc->sense_buf_q = NULL;
5418 		if (sc->sense_buf_q_tag != NULL)
5419 			bus_dma_tag_destroy(sc->sense_buf_q_tag);
5420 	}
5421 
5422 	/* Free up internal(non-IO) commands*/
5423 	if (sc->init_cmds.reply) {
5424 		free(sc->init_cmds.reply, M_MPI3MR);
5425 		sc->init_cmds.reply = NULL;
5426 	}
5427 
5428 	if (sc->ioctl_cmds.reply) {
5429 		free(sc->ioctl_cmds.reply, M_MPI3MR);
5430 		sc->ioctl_cmds.reply = NULL;
5431 	}
5432 
5433 	if (sc->pel_cmds.reply) {
5434 		free(sc->pel_cmds.reply, M_MPI3MR);
5435 		sc->pel_cmds.reply = NULL;
5436 	}
5437 
5438 	if (sc->pel_abort_cmd.reply) {
5439 		free(sc->pel_abort_cmd.reply, M_MPI3MR);
5440 		sc->pel_abort_cmd.reply = NULL;
5441 	}
5442 
5443 	if (sc->host_tm_cmds.reply) {
5444 		free(sc->host_tm_cmds.reply, M_MPI3MR);
5445 		sc->host_tm_cmds.reply = NULL;
5446 	}
5447 
5448 	if (sc->log_data_buffer) {
5449 		free(sc->log_data_buffer, M_MPI3MR);
5450 		sc->log_data_buffer = NULL;
5451 	}
5452 
5453 	for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++) {
5454 		if (sc->dev_rmhs_cmds[i].reply) {
5455 			free(sc->dev_rmhs_cmds[i].reply, M_MPI3MR);
5456 			sc->dev_rmhs_cmds[i].reply = NULL;
5457 		}
5458 	}
5459 
5460 	for (i = 0; i < MPI3MR_NUM_EVTACKCMD; i++) {
5461 		if (sc->evtack_cmds[i].reply) {
5462 			free(sc->evtack_cmds[i].reply, M_MPI3MR);
5463 			sc->evtack_cmds[i].reply = NULL;
5464 		}
5465 	}
5466 
5467 	if (sc->removepend_bitmap) {
5468 		free(sc->removepend_bitmap, M_MPI3MR);
5469 		sc->removepend_bitmap = NULL;
5470 	}
5471 
5472 	if (sc->devrem_bitmap) {
5473 		free(sc->devrem_bitmap, M_MPI3MR);
5474 		sc->devrem_bitmap = NULL;
5475 	}
5476 
5477 	if (sc->evtack_cmds_bitmap) {
5478 		free(sc->evtack_cmds_bitmap, M_MPI3MR);
5479 		sc->evtack_cmds_bitmap = NULL;
5480 	}
5481 
5482 	/* Free Admin reply*/
5483 	if (sc->admin_reply && sc->admin_reply_phys) {
5484 		bus_dmamap_unload(sc->admin_reply_tag, sc->admin_reply_dmamap);
5485 		bus_dmamem_free(sc->admin_reply_tag, sc->admin_reply,
5486 				sc->admin_reply_dmamap);
5487 		sc->admin_reply = NULL;
5488 		if (sc->admin_reply_tag != NULL)
5489 			bus_dma_tag_destroy(sc->admin_reply_tag);
5490 	}
5491 
5492 	/* Free Admin request*/
5493 	if (sc->admin_req && sc->admin_req_phys) {
5494 		bus_dmamap_unload(sc->admin_req_tag, sc->admin_req_dmamap);
5495 		bus_dmamem_free(sc->admin_req_tag, sc->admin_req,
5496 				sc->admin_req_dmamap);
5497 		sc->admin_req = NULL;
5498 		if (sc->admin_req_tag != NULL)
5499 			bus_dma_tag_destroy(sc->admin_req_tag);
5500 	}
5501 	mpi3mr_free_ioctl_dma_memory(sc);
5502 
5503 }
5504 
5505 /**
5506  * mpi3mr_drv_cmd_comp_reset - Flush a internal driver command
5507  * @sc: Adapter instance reference
5508  * @cmdptr: Internal command tracker
5509  *
5510  * Complete an internal driver commands with state indicating it
5511  * is completed due to reset.
5512  *
5513  * Return: Nothing.
5514  */
5515 static inline void mpi3mr_drv_cmd_comp_reset(struct mpi3mr_softc *sc,
5516 	struct mpi3mr_drvr_cmd *cmdptr)
5517 {
5518 	if (cmdptr->state & MPI3MR_CMD_PENDING) {
5519 		cmdptr->state |= MPI3MR_CMD_RESET;
5520 		cmdptr->state &= ~MPI3MR_CMD_PENDING;
5521 		if (cmdptr->is_waiting) {
5522 			complete(&cmdptr->completion);
5523 			cmdptr->is_waiting = 0;
5524 		} else if (cmdptr->callback)
5525 			cmdptr->callback(sc, cmdptr);
5526 	}
5527 }
5528 
5529 /**
5530  * mpi3mr_flush_drv_cmds - Flush internal driver commands
5531  * @sc: Adapter instance reference
5532  *
5533  * Flush all internal driver commands post reset
5534  *
5535  * Return: Nothing.
5536  */
5537 static void mpi3mr_flush_drv_cmds(struct mpi3mr_softc *sc)
5538 {
5539 	int i = 0;
5540 	struct mpi3mr_drvr_cmd *cmdptr;
5541 
5542 	cmdptr = &sc->init_cmds;
5543 	mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5544 
5545 	cmdptr = &sc->ioctl_cmds;
5546 	mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5547 
5548 	cmdptr = &sc->host_tm_cmds;
5549 	mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5550 
5551 	for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++) {
5552 		cmdptr = &sc->dev_rmhs_cmds[i];
5553 		mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5554 	}
5555 
5556 	for (i = 0; i < MPI3MR_NUM_EVTACKCMD; i++) {
5557 		cmdptr = &sc->evtack_cmds[i];
5558 		mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5559 	}
5560 
5561 	cmdptr = &sc->pel_cmds;
5562 	mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5563 
5564 	cmdptr = &sc->pel_abort_cmd;
5565 	mpi3mr_drv_cmd_comp_reset(sc, cmdptr);
5566 }
5567 
5568 
5569 /**
5570  * mpi3mr_memset_buffers - memset memory for a controller
5571  * @sc: Adapter instance reference
5572  *
5573  * clear all the memory allocated for a controller, typically
5574  * called post reset to reuse the memory allocated during the
5575  * controller init.
5576  *
5577  * Return: Nothing.
5578  */
5579 static void mpi3mr_memset_buffers(struct mpi3mr_softc *sc)
5580 {
5581 	U16 i;
5582 	struct mpi3mr_throttle_group_info *tg;
5583 
5584 	memset(sc->admin_req, 0, sc->admin_req_q_sz);
5585 	memset(sc->admin_reply, 0, sc->admin_reply_q_sz);
5586 
5587 	memset(sc->init_cmds.reply, 0, sc->reply_sz);
5588 	memset(sc->ioctl_cmds.reply, 0, sc->reply_sz);
5589 	memset(sc->host_tm_cmds.reply, 0, sc->reply_sz);
5590 	memset(sc->pel_cmds.reply, 0, sc->reply_sz);
5591 	memset(sc->pel_abort_cmd.reply, 0, sc->reply_sz);
5592 	for (i = 0; i < MPI3MR_NUM_DEVRMCMD; i++)
5593 		memset(sc->dev_rmhs_cmds[i].reply, 0, sc->reply_sz);
5594 	for (i = 0; i < MPI3MR_NUM_EVTACKCMD; i++)
5595 		memset(sc->evtack_cmds[i].reply, 0, sc->reply_sz);
5596 	memset(sc->removepend_bitmap, 0, sc->dev_handle_bitmap_sz);
5597 	memset(sc->devrem_bitmap, 0, sc->devrem_bitmap_sz);
5598 	memset(sc->evtack_cmds_bitmap, 0, sc->evtack_cmds_bitmap_sz);
5599 
5600 	for (i = 0; i < sc->num_queues; i++) {
5601 		sc->op_reply_q[i].qid = 0;
5602 		sc->op_reply_q[i].ci = 0;
5603 		sc->op_reply_q[i].num_replies = 0;
5604 		sc->op_reply_q[i].ephase = 0;
5605 		mpi3mr_atomic_set(&sc->op_reply_q[i].pend_ios, 0);
5606 		memset(sc->op_reply_q[i].q_base, 0, sc->op_reply_q[i].qsz);
5607 
5608 		sc->op_req_q[i].ci = 0;
5609 		sc->op_req_q[i].pi = 0;
5610 		sc->op_req_q[i].num_reqs = 0;
5611 		sc->op_req_q[i].qid = 0;
5612 		sc->op_req_q[i].reply_qid = 0;
5613 		memset(sc->op_req_q[i].q_base, 0, sc->op_req_q[i].qsz);
5614 	}
5615 
5616 	mpi3mr_atomic_set(&sc->pend_large_data_sz, 0);
5617 	if (sc->throttle_groups) {
5618 		tg = sc->throttle_groups;
5619 		for (i = 0; i < sc->num_io_throttle_group; i++, tg++) {
5620 			tg->id = 0;
5621 			tg->fw_qd = 0;
5622 			tg->modified_qd = 0;
5623 			tg->io_divert= 0;
5624 			tg->high = 0;
5625 			tg->low = 0;
5626 			mpi3mr_atomic_set(&tg->pend_large_data_sz, 0);
5627 		}
5628  	}
5629 }
5630 
5631 /**
5632  * mpi3mr_invalidate_devhandles -Invalidate device handles
5633  * @sc: Adapter instance reference
5634  *
5635  * Invalidate the device handles in the target device structures
5636  * . Called post reset prior to reinitializing the controller.
5637  *
5638  * Return: Nothing.
5639  */
5640 static void mpi3mr_invalidate_devhandles(struct mpi3mr_softc *sc)
5641 {
5642 	struct mpi3mr_target *target = NULL;
5643 
5644 	mtx_lock_spin(&sc->target_lock);
5645 	TAILQ_FOREACH(target, &sc->cam_sc->tgt_list, tgt_next) {
5646 		if (target) {
5647 			target->dev_handle = MPI3MR_INVALID_DEV_HANDLE;
5648 			target->io_throttle_enabled = 0;
5649 			target->io_divert = 0;
5650 			target->throttle_group = NULL;
5651 		}
5652 	}
5653 	mtx_unlock_spin(&sc->target_lock);
5654 }
5655 
5656 /**
5657  * mpi3mr_rfresh_tgtdevs - Refresh target device exposure
5658  * @sc: Adapter instance reference
5659  *
5660  * This is executed post controller reset to identify any
5661  * missing devices during reset and remove from the upper layers
5662  * or expose any newly detected device to the upper layers.
5663  *
5664  * Return: Nothing.
5665  */
5666 
5667 static void mpi3mr_rfresh_tgtdevs(struct mpi3mr_softc *sc)
5668 {
5669 	struct mpi3mr_target *target = NULL;
5670 	struct mpi3mr_target *target_temp = NULL;
5671 
5672 	TAILQ_FOREACH_SAFE(target, &sc->cam_sc->tgt_list, tgt_next, target_temp) {
5673 		if (target->dev_handle == MPI3MR_INVALID_DEV_HANDLE) {
5674 			if (target->exposed_to_os)
5675 				mpi3mr_remove_device_from_os(sc, target->dev_handle);
5676 			mpi3mr_remove_device_from_list(sc, target, true);
5677 		} else if (target->is_hidden && target->exposed_to_os) {
5678 				mpi3mr_remove_device_from_os(sc, target->dev_handle);
5679 		}
5680 	}
5681 
5682 	TAILQ_FOREACH(target, &sc->cam_sc->tgt_list, tgt_next) {
5683 		if ((target->dev_handle != MPI3MR_INVALID_DEV_HANDLE) &&
5684 		    !target->is_hidden && !target->exposed_to_os) {
5685 			mpi3mr_add_device(sc, target->per_id);
5686 		}
5687 	}
5688 
5689 }
5690 
5691 static void mpi3mr_flush_io(struct mpi3mr_softc *sc)
5692 {
5693 	int i;
5694 	struct mpi3mr_cmd *cmd = NULL;
5695 	union ccb *ccb = NULL;
5696 
5697 	for (i = 0; i < sc->max_host_ios; i++) {
5698 		cmd = sc->cmd_list[i];
5699 
5700 		if (cmd && cmd->ccb) {
5701 			if (cmd->callout_owner) {
5702 				ccb = (union ccb *)(cmd->ccb);
5703 				ccb->ccb_h.status = CAM_SCSI_BUS_RESET;
5704 				mpi3mr_atomic_dec(&sc->fw_outstanding);
5705 				mpi3mr_atomic_dec(&cmd->targ->outstanding);
5706 				mpi3mr_cmd_done(sc, cmd);
5707 			} else {
5708 				cmd->ccb = NULL;
5709 				mpi3mr_release_command(cmd);
5710 			}
5711 		}
5712 	}
5713 }
5714 /**
5715  * mpi3mr_clear_reset_history - Clear reset history
5716  * @sc: Adapter instance reference
5717  *
5718  * Write the reset history bit in IOC Status to clear the bit,
5719  * if it is already set.
5720  *
5721  * Return: Nothing.
5722  */
5723 static inline void mpi3mr_clear_reset_history(struct mpi3mr_softc *sc)
5724 {
5725 	U32 ioc_status;
5726 
5727 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
5728 	if (ioc_status & MPI3_SYSIF_IOC_STATUS_RESET_HISTORY)
5729 		mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_STATUS_OFFSET, ioc_status);
5730 }
5731 
5732 /**
5733  * mpi3mr_set_diagsave - Set diag save bit for snapdump
5734  * @sc: Adapter reference
5735  *
5736  * Set diag save bit in IOC configuration register to enable
5737  * snapdump.
5738  *
5739  * Return: Nothing.
5740  */
5741 static inline void mpi3mr_set_diagsave(struct mpi3mr_softc *sc)
5742 {
5743 	U32 ioc_config;
5744 
5745 	ioc_config =
5746 	    mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
5747 	ioc_config |= MPI3_SYSIF_IOC_CONFIG_DIAG_SAVE;
5748 	mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET, ioc_config);
5749 }
5750 
5751 /**
5752  * mpi3mr_issue_reset - Issue reset to the controller
5753  * @sc: Adapter reference
5754  * @reset_type: Reset type
5755  * @reset_reason: Reset reason code
5756  *
5757  * Unlock the host diagnostic registers and write the specific
5758  * reset type to that, wait for reset acknowledgement from the
5759  * controller, if the reset is not successful retry for the
5760  * predefined number of times.
5761  *
5762  * Return: 0 on success, non-zero on failure.
5763  */
5764 static int mpi3mr_issue_reset(struct mpi3mr_softc *sc, U16 reset_type,
5765 	U16 reset_reason)
5766 {
5767 	int retval = -1;
5768 	U8 unlock_retry_count = 0;
5769 	U32 host_diagnostic, ioc_status, ioc_config, scratch_pad0;
5770 	U32 timeout = MPI3MR_RESET_ACK_TIMEOUT * 10;
5771 
5772 	if ((reset_type != MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET) &&
5773 	    (reset_type != MPI3_SYSIF_HOST_DIAG_RESET_ACTION_DIAG_FAULT))
5774 		return retval;
5775 	if (sc->unrecoverable)
5776 		return retval;
5777 
5778 	if (reset_reason == MPI3MR_RESET_FROM_FIRMWARE) {
5779 		retval = 0;
5780 		return retval;
5781 	}
5782 
5783 	mpi3mr_dprint(sc, MPI3MR_INFO, "%s reset due to %s(0x%x)\n",
5784 	    mpi3mr_reset_type_name(reset_type),
5785 	    mpi3mr_reset_rc_name(reset_reason), reset_reason);
5786 
5787 	mpi3mr_clear_reset_history(sc);
5788 	do {
5789 		mpi3mr_dprint(sc, MPI3MR_INFO,
5790 		    "Write magic sequence to unlock host diag register (retry=%d)\n",
5791 		    ++unlock_retry_count);
5792 		if (unlock_retry_count >= MPI3MR_HOSTDIAG_UNLOCK_RETRY_COUNT) {
5793 			mpi3mr_dprint(sc, MPI3MR_ERROR,
5794 			    "%s reset failed! due to host diag register unlock failure"
5795 			    "host_diagnostic(0x%08x)\n", mpi3mr_reset_type_name(reset_type),
5796 			    host_diagnostic);
5797 			sc->unrecoverable = 1;
5798 			return retval;
5799 		}
5800 
5801 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5802 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_FLUSH);
5803 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5804 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_1ST);
5805 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5806 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_2ND);
5807 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5808 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_3RD);
5809 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5810 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_4TH);
5811 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5812 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_5TH);
5813 		mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5814 			MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_6TH);
5815 
5816 		DELAY(1000); /* delay in usec */
5817 		host_diagnostic = mpi3mr_regread(sc, MPI3_SYSIF_HOST_DIAG_OFFSET);
5818 		mpi3mr_dprint(sc, MPI3MR_INFO,
5819 		    "wrote magic sequence: retry_count(%d), host_diagnostic(0x%08x)\n",
5820 		    unlock_retry_count, host_diagnostic);
5821 	} while (!(host_diagnostic & MPI3_SYSIF_HOST_DIAG_DIAG_WRITE_ENABLE));
5822 
5823 	scratch_pad0 = ((MPI3MR_RESET_REASON_OSTYPE_FREEBSD <<
5824 			MPI3MR_RESET_REASON_OSTYPE_SHIFT) |
5825 			(sc->facts.ioc_num <<
5826 			MPI3MR_RESET_REASON_IOCNUM_SHIFT) | reset_reason);
5827 	mpi3mr_regwrite(sc, MPI3_SYSIF_SCRATCHPAD0_OFFSET, scratch_pad0);
5828 	mpi3mr_regwrite(sc, MPI3_SYSIF_HOST_DIAG_OFFSET, host_diagnostic | reset_type);
5829 
5830 	if (reset_type == MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET) {
5831 		do {
5832 			ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
5833 			if (ioc_status &
5834 			    MPI3_SYSIF_IOC_STATUS_RESET_HISTORY) {
5835 				ioc_config =
5836 				    mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
5837 				if (mpi3mr_soft_reset_success(ioc_status,
5838 				    ioc_config)) {
5839 					mpi3mr_clear_reset_history(sc);
5840 					retval = 0;
5841 					break;
5842 				}
5843 			}
5844 			DELAY(100 * 1000);
5845 		} while (--timeout);
5846 	} else if (reset_type == MPI3_SYSIF_HOST_DIAG_RESET_ACTION_DIAG_FAULT) {
5847 		do {
5848 			ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
5849 			if (mpi3mr_diagfault_success(sc, ioc_status)) {
5850 				retval = 0;
5851 				break;
5852 			}
5853 			DELAY(100 * 1000);
5854 		} while (--timeout);
5855 	}
5856 
5857 	mpi3mr_regwrite(sc, MPI3_SYSIF_WRITE_SEQUENCE_OFFSET,
5858 		MPI3_SYSIF_WRITE_SEQUENCE_KEY_VALUE_2ND);
5859 
5860 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
5861 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
5862 
5863 	mpi3mr_dprint(sc, MPI3MR_INFO,
5864 	    "IOC Status/Config after %s reset is (0x%x)/(0x%x)\n",
5865 	    !retval ? "successful":"failed", ioc_status,
5866 	    ioc_config);
5867 
5868 	if (retval)
5869 		sc->unrecoverable = 1;
5870 
5871 	return retval;
5872 }
5873 
5874 inline void mpi3mr_cleanup_event_taskq(struct mpi3mr_softc *sc)
5875 {
5876 	/*
5877 	 * Block the taskqueue before draining.  This means any new tasks won't
5878 	 * be queued to the taskqueue worker thread.  But it doesn't stop the
5879 	 * current workers that are running.  taskqueue_drain waits for those
5880 	 * correctly in the case of thread backed taskqueues.  The while loop
5881 	 * ensures that all taskqueue threads have finished their current tasks.
5882 	 */
5883 	taskqueue_block(sc->cam_sc->ev_tq);
5884 	while (taskqueue_cancel(sc->cam_sc->ev_tq, &sc->cam_sc->ev_task, NULL) != 0) {
5885 		taskqueue_drain(sc->cam_sc->ev_tq, &sc->cam_sc->ev_task);
5886 	}
5887 }
5888 
5889 /**
5890  * mpi3mr_soft_reset_handler - Reset the controller
5891  * @sc: Adapter instance reference
5892  * @reset_reason: Reset reason code
5893  * @snapdump: snapdump enable/disbale bit
5894  *
5895  * This is an handler for recovering controller by issuing soft
5896  * reset or diag fault reset. This is a blocking function and
5897  * when one reset is executed if any other resets they will be
5898  * blocked. All IOCTLs/IO will be blocked during the reset. If
5899  * controller reset is successful then the controller will be
5900  * reinitalized, otherwise the controller will be marked as not
5901  * recoverable
5902  *
5903  * Return: 0 on success, non-zero on failure.
5904  */
5905 int mpi3mr_soft_reset_handler(struct mpi3mr_softc *sc,
5906 	U16 reset_reason, bool snapdump)
5907 {
5908 	int retval = 0, i = 0;
5909 	enum mpi3mr_iocstate ioc_state;
5910 
5911 	mpi3mr_dprint(sc, MPI3MR_INFO, "soft reset invoked: reason code: %s\n",
5912 	    mpi3mr_reset_rc_name(reset_reason));
5913 
5914 	if ((reset_reason == MPI3MR_RESET_FROM_IOCTL) &&
5915 	     (sc->reset.ioctl_reset_snapdump != true))
5916 		snapdump = false;
5917 
5918 	mpi3mr_dprint(sc, MPI3MR_INFO,
5919 	    "soft_reset_handler: wait if diag save is in progress\n");
5920 	while (sc->diagsave_timeout)
5921 		DELAY(1000 * 1000);
5922 
5923 	ioc_state = mpi3mr_get_iocstate(sc);
5924 	if (ioc_state == MRIOC_STATE_UNRECOVERABLE) {
5925 		mpi3mr_dprint(sc, MPI3MR_ERROR, "controller is in unrecoverable state, exit\n");
5926 		sc->reset.type = MPI3MR_NO_RESET;
5927 		sc->reset.reason = MPI3MR_DEFAULT_RESET_REASON;
5928 		sc->reset.status = -1;
5929 		sc->reset.ioctl_reset_snapdump = false;
5930 		return -1;
5931 	}
5932 
5933 	if (sc->reset_in_progress) {
5934 		mpi3mr_dprint(sc, MPI3MR_INFO, "reset is already in progress, exit\n");
5935 		return -1;
5936 	}
5937 
5938 	/* Pause IOs, drain and block the event taskqueue */
5939 	xpt_freeze_simq(sc->cam_sc->sim, 1);
5940 
5941 	mpi3mr_cleanup_event_taskq(sc);
5942 
5943 	sc->reset_in_progress = 1;
5944 	sc->block_ioctls = 1;
5945 
5946 	while (mpi3mr_atomic_read(&sc->pend_ioctls) && (i < PEND_IOCTLS_COMP_WAIT_TIME)) {
5947 		ioc_state = mpi3mr_get_iocstate(sc);
5948 		if (ioc_state == MRIOC_STATE_FAULT)
5949 			break;
5950 		i++;
5951 		if (!(i % 5)) {
5952 			mpi3mr_dprint(sc, MPI3MR_INFO,
5953 			    "[%2ds]waiting for IOCTL to be finished from %s\n", i, __func__);
5954 		}
5955 		DELAY(1000 * 1000);
5956 	}
5957 
5958 	if ((!snapdump) && (reset_reason != MPI3MR_RESET_FROM_FAULT_WATCH) &&
5959 	    (reset_reason != MPI3MR_RESET_FROM_FIRMWARE) &&
5960 	    (reset_reason != MPI3MR_RESET_FROM_CIACTIV_FAULT)) {
5961 
5962 		mpi3mr_dprint(sc, MPI3MR_INFO, "Turn off events prior to reset\n");
5963 
5964 		for (i = 0; i < MPI3_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
5965 			sc->event_masks[i] = -1;
5966 		mpi3mr_issue_event_notification(sc);
5967 	}
5968 
5969 	mpi3mr_disable_interrupts(sc);
5970 
5971 	if (snapdump)
5972 		mpi3mr_trigger_snapdump(sc, reset_reason);
5973 
5974 	retval = mpi3mr_issue_reset(sc,
5975 	    MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET, reset_reason);
5976 	if (retval) {
5977 		mpi3mr_dprint(sc, MPI3MR_ERROR, "Failed to issue soft reset to the ioc\n");
5978 		goto out;
5979 	}
5980 
5981 	mpi3mr_flush_drv_cmds(sc);
5982 	mpi3mr_flush_io(sc);
5983 	mpi3mr_invalidate_devhandles(sc);
5984 	mpi3mr_memset_buffers(sc);
5985 
5986 	if (sc->prepare_for_reset) {
5987 		sc->prepare_for_reset = 0;
5988 		sc->prepare_for_reset_timeout_counter = 0;
5989 	}
5990 
5991 	retval = mpi3mr_initialize_ioc(sc, MPI3MR_INIT_TYPE_RESET);
5992 	if (retval) {
5993 		mpi3mr_dprint(sc, MPI3MR_ERROR, "reinit after soft reset failed: reason %d\n",
5994 		    reset_reason);
5995 		goto out;
5996 	}
5997 
5998 	DELAY((1000 * 1000) * 10);
5999 out:
6000 	if (!retval) {
6001 		sc->diagsave_timeout = 0;
6002 		sc->reset_in_progress = 0;
6003 		mpi3mr_rfresh_tgtdevs(sc);
6004 		sc->ts_update_counter = 0;
6005 		sc->block_ioctls = 0;
6006 		sc->pel_abort_requested = 0;
6007 		if (sc->pel_wait_pend) {
6008 			sc->pel_cmds.retry_count = 0;
6009 			mpi3mr_issue_pel_wait(sc, &sc->pel_cmds);
6010 			mpi3mr_app_send_aen(sc);
6011 		}
6012 	} else {
6013 		mpi3mr_issue_reset(sc,
6014 		    MPI3_SYSIF_HOST_DIAG_RESET_ACTION_DIAG_FAULT, reset_reason);
6015 		sc->unrecoverable = 1;
6016 		sc->reset_in_progress = 0;
6017 	}
6018 
6019 	mpi3mr_dprint(sc, MPI3MR_INFO, "Soft Reset: %s\n", ((retval == 0) ? "SUCCESS" : "FAILED"));
6020 
6021 	taskqueue_unblock(sc->cam_sc->ev_tq);
6022 	xpt_release_simq(sc->cam_sc->sim, 1);
6023 
6024 	sc->reset.type = MPI3MR_NO_RESET;
6025 	sc->reset.reason = MPI3MR_DEFAULT_RESET_REASON;
6026 	sc->reset.status = retval;
6027 	sc->reset.ioctl_reset_snapdump = false;
6028 
6029 	return retval;
6030 }
6031 
6032 /**
6033  * mpi3mr_issue_ioc_shutdown - shutdown controller
6034  * @sc: Adapter instance reference
6035  *
6036  * Send shutodwn notification to the controller and wait for the
6037  * shutdown_timeout for it to be completed.
6038  *
6039  * Return: Nothing.
6040  */
6041 static void mpi3mr_issue_ioc_shutdown(struct mpi3mr_softc *sc)
6042 {
6043 	U32 ioc_config, ioc_status;
6044 	U8 retval = 1, retry = 0;
6045 	U32 timeout = MPI3MR_DEFAULT_SHUTDOWN_TIME * 10;
6046 
6047 	mpi3mr_dprint(sc, MPI3MR_INFO, "sending shutdown notification\n");
6048 	if (sc->unrecoverable) {
6049 		mpi3mr_dprint(sc, MPI3MR_ERROR,
6050 		    "controller is unrecoverable, shutdown not issued\n");
6051 		return;
6052 	}
6053 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
6054 	if ((ioc_status & MPI3_SYSIF_IOC_STATUS_SHUTDOWN_MASK)
6055 	    == MPI3_SYSIF_IOC_STATUS_SHUTDOWN_IN_PROGRESS) {
6056 		mpi3mr_dprint(sc, MPI3MR_ERROR, "shutdown already in progress\n");
6057 		return;
6058 	}
6059 
6060 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
6061 	ioc_config |= MPI3_SYSIF_IOC_CONFIG_SHUTDOWN_NORMAL;
6062 	ioc_config |= MPI3_SYSIF_IOC_CONFIG_DEVICE_SHUTDOWN_SEND_REQ;
6063 
6064 	mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET, ioc_config);
6065 
6066 	if (sc->facts.shutdown_timeout)
6067 		timeout = sc->facts.shutdown_timeout * 10;
6068 
6069 	do {
6070 		ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
6071 		if ((ioc_status & MPI3_SYSIF_IOC_STATUS_SHUTDOWN_MASK)
6072 		    == MPI3_SYSIF_IOC_STATUS_SHUTDOWN_COMPLETE) {
6073 			retval = 0;
6074 			break;
6075 		}
6076 
6077 		if (sc->unrecoverable)
6078 			break;
6079 
6080 		if ((ioc_status & MPI3_SYSIF_IOC_STATUS_FAULT)) {
6081 			mpi3mr_print_fault_info(sc);
6082 
6083 			if (retry >= MPI3MR_MAX_SHUTDOWN_RETRY_COUNT)
6084 				break;
6085 
6086 			if (mpi3mr_issue_reset(sc,
6087 			    MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET,
6088 			    MPI3MR_RESET_FROM_CTLR_CLEANUP))
6089 				break;
6090 
6091 			ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
6092 			ioc_config |= MPI3_SYSIF_IOC_CONFIG_SHUTDOWN_NORMAL;
6093 			ioc_config |= MPI3_SYSIF_IOC_CONFIG_DEVICE_SHUTDOWN_SEND_REQ;
6094 
6095 			mpi3mr_regwrite(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET, ioc_config);
6096 
6097 			if (sc->facts.shutdown_timeout)
6098 				timeout = sc->facts.shutdown_timeout * 10;
6099 
6100 			retry++;
6101 		}
6102 
6103                 DELAY(100 * 1000);
6104 
6105 	} while (--timeout);
6106 
6107 	ioc_status = mpi3mr_regread(sc, MPI3_SYSIF_IOC_STATUS_OFFSET);
6108 	ioc_config = mpi3mr_regread(sc, MPI3_SYSIF_IOC_CONFIG_OFFSET);
6109 
6110 	if (retval) {
6111 		if ((ioc_status & MPI3_SYSIF_IOC_STATUS_SHUTDOWN_MASK)
6112 		    == MPI3_SYSIF_IOC_STATUS_SHUTDOWN_IN_PROGRESS)
6113 			mpi3mr_dprint(sc, MPI3MR_ERROR,
6114 			    "shutdown still in progress after timeout\n");
6115 	}
6116 
6117 	mpi3mr_dprint(sc, MPI3MR_INFO,
6118 	    "ioc_status/ioc_config after %s shutdown is (0x%x)/(0x%x)\n",
6119 	    (!retval)?"successful":"failed", ioc_status,
6120 	    ioc_config);
6121 }
6122 
6123 /**
6124  * mpi3mr_cleanup_ioc - Cleanup controller
6125  * @sc: Adapter instance reference
6126 
6127  * controller cleanup handler, Message unit reset or soft reset
6128  * and shutdown notification is issued to the controller.
6129  *
6130  * Return: Nothing.
6131  */
6132 void mpi3mr_cleanup_ioc(struct mpi3mr_softc *sc)
6133 {
6134 	enum mpi3mr_iocstate ioc_state;
6135 
6136 	mpi3mr_dprint(sc, MPI3MR_INFO, "cleaning up the controller\n");
6137 	mpi3mr_disable_interrupts(sc);
6138 
6139 	ioc_state = mpi3mr_get_iocstate(sc);
6140 
6141 	if ((!sc->unrecoverable) && (!sc->reset_in_progress) &&
6142 	    (ioc_state == MRIOC_STATE_READY)) {
6143 		if (mpi3mr_mur_ioc(sc,
6144 		    MPI3MR_RESET_FROM_CTLR_CLEANUP))
6145 			mpi3mr_issue_reset(sc,
6146 			    MPI3_SYSIF_HOST_DIAG_RESET_ACTION_SOFT_RESET,
6147 			    MPI3MR_RESET_FROM_MUR_FAILURE);
6148 		mpi3mr_issue_ioc_shutdown(sc);
6149 	}
6150 
6151 	mpi3mr_dprint(sc, MPI3MR_INFO, "controller cleanup completed\n");
6152 }
6153