xref: /freebsd/sys/dev/mrsas/mrsas_cam.c (revision e17f5b1d)
1 /*
2  * Copyright (c) 2015, AVAGO Tech. All rights reserved. Author: Marian Choy
3  * Copyright (c) 2014, LSI Corp. All rights reserved. Author: Marian Choy
4  * Support: freebsdraid@avagotech.com
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  * 1. Redistributions of source code must retain the above copyright notice,
11  * this list of conditions and the following disclaimer. 2. Redistributions
12  * in binary form must reproduce the above copyright notice, this list of
13  * conditions and the following disclaimer in the documentation and/or other
14  * materials provided with the distribution. 3. Neither the name of the
15  * <ORGANIZATION> nor the names of its contributors may be used to endorse or
16  * promote products derived from this software without specific prior written
17  * permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "dev/mrsas/mrsas.h"
37 
38 #include <cam/cam.h>
39 #include <cam/cam_ccb.h>
40 #include <cam/cam_sim.h>
41 #include <cam/cam_xpt_sim.h>
42 #include <cam/cam_debug.h>
43 #include <cam/cam_periph.h>
44 #include <cam/cam_xpt_periph.h>
45 
46 #include <cam/scsi/scsi_all.h>
47 #include <cam/scsi/scsi_message.h>
48 #include <sys/taskqueue.h>
49 #include <sys/kernel.h>
50 
51 #include <sys/time.h>			/* XXX for pcpu.h */
52 #include <sys/pcpu.h>			/* XXX for PCPU_GET */
53 
54 #define	smp_processor_id()  PCPU_GET(cpuid)
55 
56 /*
57  * Function prototypes
58  */
59 int	mrsas_cam_attach(struct mrsas_softc *sc);
60 int	mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb);
61 int	mrsas_bus_scan(struct mrsas_softc *sc);
62 int	mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim);
63 int
64 mrsas_map_request(struct mrsas_softc *sc,
65     struct mrsas_mpt_cmd *cmd, union ccb *ccb);
66 int
67 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
68     union ccb *ccb);
69 int
70 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
71     union ccb *ccb);
72 int
73 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
74     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible);
75 int
76 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
77     union ccb *ccb, u_int32_t device_id,
78     MRSAS_RAID_SCSI_IO_REQUEST * io_request);
79 void	mrsas_xpt_freeze(struct mrsas_softc *sc);
80 void	mrsas_xpt_release(struct mrsas_softc *sc);
81 void	mrsas_cam_detach(struct mrsas_softc *sc);
82 void	mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd);
83 void	mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
84 void	mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
85 void
86 mrsas_fire_cmd(struct mrsas_softc *sc, u_int32_t req_desc_lo,
87     u_int32_t req_desc_hi);
88 void
89 mrsas_set_pd_lba(MRSAS_RAID_SCSI_IO_REQUEST * io_request,
90     u_int8_t cdb_len, struct IO_REQUEST_INFO *io_info, union ccb *ccb,
91     MR_DRV_RAID_MAP_ALL * local_map_ptr, u_int32_t ref_tag,
92     u_int32_t ld_block_size);
93 static void mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim);
94 static void mrsas_cam_poll(struct cam_sim *sim);
95 static void mrsas_action(struct cam_sim *sim, union ccb *ccb);
96 static void mrsas_scsiio_timeout(void *data);
97 static int mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t id, u_int32_t bus_id);
98 static void mrsas_tm_response_code(struct mrsas_softc *sc,
99     MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply);
100 static int mrsas_issue_tm(struct mrsas_softc *sc,
101     MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc);
102 static void
103 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs,
104     int nseg, int error);
105 static int32_t
106 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
107     union ccb *ccb);
108 
109 static boolean_t mrsas_is_prp_possible(struct mrsas_mpt_cmd *cmd,
110 	bus_dma_segment_t *segs, int nsegs);
111 static void mrsas_build_ieee_sgl(struct mrsas_mpt_cmd *cmd,
112 	bus_dma_segment_t *segs, int nseg);
113 static void mrsas_build_prp_nvme(struct mrsas_mpt_cmd *cmd,
114 	bus_dma_segment_t *segs, int nseg);
115 
116 struct mrsas_mpt_cmd *mrsas_get_mpt_cmd(struct mrsas_softc *sc);
117 MRSAS_REQUEST_DESCRIPTOR_UNION *
118 	mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index);
119 
120 extern int mrsas_reset_targets(struct mrsas_softc *sc);
121 extern u_int16_t MR_TargetIdToLdGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map);
122 extern u_int32_t
123 MR_LdBlockSizeGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map);
124 extern void mrsas_isr(void *arg);
125 extern void mrsas_aen_handler(struct mrsas_softc *sc);
126 extern u_int8_t
127 MR_BuildRaidContext(struct mrsas_softc *sc,
128     struct IO_REQUEST_INFO *io_info, RAID_CONTEXT * pRAID_Context,
129     MR_DRV_RAID_MAP_ALL * map);
130 extern u_int16_t
131 MR_LdSpanArrayGet(u_int32_t ld, u_int32_t span,
132     MR_DRV_RAID_MAP_ALL * map);
133 extern u_int16_t
134 mrsas_get_updated_dev_handle(struct mrsas_softc *sc,
135     PLD_LOAD_BALANCE_INFO lbInfo, struct IO_REQUEST_INFO *io_info);
136 extern int mrsas_complete_cmd(struct mrsas_softc *sc, u_int32_t MSIxIndex);
137 extern MR_LD_RAID *MR_LdRaidGet(u_int32_t ld, MR_DRV_RAID_MAP_ALL * map);
138 extern void mrsas_disable_intr(struct mrsas_softc *sc);
139 extern void mrsas_enable_intr(struct mrsas_softc *sc);
140 void mrsas_prepare_secondRaid1_IO(struct mrsas_softc *sc,
141     struct mrsas_mpt_cmd *cmd);
142 
143 /*
144  * mrsas_cam_attach:	Main entry to CAM subsystem
145  * input:				Adapter instance soft state
146  *
147  * This function is called from mrsas_attach() during initialization to perform
148  * SIM allocations and XPT bus registration.  If the kernel version is 7.4 or
149  * earlier, it would also initiate a bus scan.
150  */
151 int
152 mrsas_cam_attach(struct mrsas_softc *sc)
153 {
154 	struct cam_devq *devq;
155 	int mrsas_cam_depth;
156 
157 	mrsas_cam_depth = sc->max_scsi_cmds;
158 
159 	if ((devq = cam_simq_alloc(mrsas_cam_depth)) == NULL) {
160 		device_printf(sc->mrsas_dev, "Cannot allocate SIM queue\n");
161 		return (ENOMEM);
162 	}
163 	/*
164 	 * Create SIM for bus 0 and register, also create path
165 	 */
166 	sc->sim_0 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
167 	    device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
168 	    mrsas_cam_depth, devq);
169 	if (sc->sim_0 == NULL) {
170 		cam_simq_free(devq);
171 		device_printf(sc->mrsas_dev, "Cannot register SIM\n");
172 		return (ENXIO);
173 	}
174 	/* Initialize taskqueue for Event Handling */
175 	TASK_INIT(&sc->ev_task, 0, (void *)mrsas_aen_handler, sc);
176 	sc->ev_tq = taskqueue_create("mrsas_taskq", M_NOWAIT | M_ZERO,
177 	    taskqueue_thread_enqueue, &sc->ev_tq);
178 
179 	/* Run the task queue with lowest priority */
180 	taskqueue_start_threads(&sc->ev_tq, 1, 255, "%s taskq",
181 	    device_get_nameunit(sc->mrsas_dev));
182 	mtx_lock(&sc->sim_lock);
183 	if (xpt_bus_register(sc->sim_0, sc->mrsas_dev, 0) != CAM_SUCCESS) {
184 		cam_sim_free(sc->sim_0, TRUE);	/* passing true frees the devq */
185 		mtx_unlock(&sc->sim_lock);
186 		return (ENXIO);
187 	}
188 	if (xpt_create_path(&sc->path_0, NULL, cam_sim_path(sc->sim_0),
189 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
190 		xpt_bus_deregister(cam_sim_path(sc->sim_0));
191 		cam_sim_free(sc->sim_0, TRUE);	/* passing true will free the
192 						 * devq */
193 		mtx_unlock(&sc->sim_lock);
194 		return (ENXIO);
195 	}
196 	mtx_unlock(&sc->sim_lock);
197 
198 	/*
199 	 * Create SIM for bus 1 and register, also create path
200 	 */
201 	sc->sim_1 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
202 	    device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
203 	    mrsas_cam_depth, devq);
204 	if (sc->sim_1 == NULL) {
205 		cam_simq_free(devq);
206 		device_printf(sc->mrsas_dev, "Cannot register SIM\n");
207 		return (ENXIO);
208 	}
209 	mtx_lock(&sc->sim_lock);
210 	if (xpt_bus_register(sc->sim_1, sc->mrsas_dev, 1) != CAM_SUCCESS) {
211 		cam_sim_free(sc->sim_1, TRUE);	/* passing true frees the devq */
212 		mtx_unlock(&sc->sim_lock);
213 		return (ENXIO);
214 	}
215 	if (xpt_create_path(&sc->path_1, NULL, cam_sim_path(sc->sim_1),
216 	    CAM_TARGET_WILDCARD,
217 	    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
218 		xpt_bus_deregister(cam_sim_path(sc->sim_1));
219 		cam_sim_free(sc->sim_1, TRUE);
220 		mtx_unlock(&sc->sim_lock);
221 		return (ENXIO);
222 	}
223 	mtx_unlock(&sc->sim_lock);
224 
225 #if (__FreeBSD_version <= 704000)
226 	if (mrsas_bus_scan(sc)) {
227 		device_printf(sc->mrsas_dev, "Error in bus scan.\n");
228 		return (1);
229 	}
230 #endif
231 	return (0);
232 }
233 
234 /*
235  * mrsas_cam_detach:	De-allocates and teardown CAM
236  * input:				Adapter instance soft state
237  *
238  * De-registers and frees the paths and SIMs.
239  */
240 void
241 mrsas_cam_detach(struct mrsas_softc *sc)
242 {
243 	if (sc->ev_tq != NULL)
244 		taskqueue_free(sc->ev_tq);
245 	mtx_lock(&sc->sim_lock);
246 	if (sc->path_0)
247 		xpt_free_path(sc->path_0);
248 	if (sc->sim_0) {
249 		xpt_bus_deregister(cam_sim_path(sc->sim_0));
250 		cam_sim_free(sc->sim_0, FALSE);
251 	}
252 	if (sc->path_1)
253 		xpt_free_path(sc->path_1);
254 	if (sc->sim_1) {
255 		xpt_bus_deregister(cam_sim_path(sc->sim_1));
256 		cam_sim_free(sc->sim_1, TRUE);
257 	}
258 	mtx_unlock(&sc->sim_lock);
259 }
260 
261 /*
262  * mrsas_action:	SIM callback entry point
263  * input:			pointer to SIM pointer to CAM Control Block
264  *
265  * This function processes CAM subsystem requests. The type of request is stored
266  * in ccb->ccb_h.func_code.  The preprocessor #ifdef is necessary because
267  * ccb->cpi.maxio is not supported for FreeBSD version 7.4 or earlier.
268  */
269 static void
270 mrsas_action(struct cam_sim *sim, union ccb *ccb)
271 {
272 	struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
273 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
274 	u_int32_t device_id;
275 
276 	/*
277      * Check if the system going down
278      * or the adapter is in unrecoverable critical error
279      */
280     if (sc->remove_in_progress ||
281         (sc->adprecovery == MRSAS_HW_CRITICAL_ERROR)) {
282         ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
283         xpt_done(ccb);
284         return;
285     }
286 
287 	switch (ccb->ccb_h.func_code) {
288 	case XPT_SCSI_IO:
289 		{
290 			device_id = ccb_h->target_id;
291 
292 			/*
293 			 * bus 0 is LD, bus 1 is for system-PD
294 			 */
295 			if (cam_sim_bus(sim) == 1 &&
296 			    sc->pd_list[device_id].driveState != MR_PD_STATE_SYSTEM) {
297 				ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
298 				xpt_done(ccb);
299 			} else {
300 				if (mrsas_startio(sc, sim, ccb)) {
301 					ccb->ccb_h.status |= CAM_REQ_INVALID;
302 					xpt_done(ccb);
303 				}
304 			}
305 			break;
306 		}
307 	case XPT_ABORT:
308 		{
309 			ccb->ccb_h.status = CAM_UA_ABORT;
310 			xpt_done(ccb);
311 			break;
312 		}
313 	case XPT_RESET_BUS:
314 		{
315 			xpt_done(ccb);
316 			break;
317 		}
318 	case XPT_GET_TRAN_SETTINGS:
319 		{
320 			ccb->cts.protocol = PROTO_SCSI;
321 			ccb->cts.protocol_version = SCSI_REV_2;
322 			ccb->cts.transport = XPORT_SPI;
323 			ccb->cts.transport_version = 2;
324 			ccb->cts.xport_specific.spi.valid = CTS_SPI_VALID_DISC;
325 			ccb->cts.xport_specific.spi.flags = CTS_SPI_FLAGS_DISC_ENB;
326 			ccb->cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
327 			ccb->cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
328 			ccb->ccb_h.status = CAM_REQ_CMP;
329 			xpt_done(ccb);
330 			break;
331 		}
332 	case XPT_SET_TRAN_SETTINGS:
333 		{
334 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
335 			xpt_done(ccb);
336 			break;
337 		}
338 	case XPT_CALC_GEOMETRY:
339 		{
340 			cam_calc_geometry(&ccb->ccg, 1);
341 			xpt_done(ccb);
342 			break;
343 		}
344 	case XPT_PATH_INQ:
345 		{
346 			ccb->cpi.version_num = 1;
347 			ccb->cpi.hba_inquiry = 0;
348 			ccb->cpi.target_sprt = 0;
349 #if (__FreeBSD_version >= 902001)
350 			ccb->cpi.hba_misc = PIM_UNMAPPED;
351 #else
352 			ccb->cpi.hba_misc = 0;
353 #endif
354 			ccb->cpi.hba_eng_cnt = 0;
355 			ccb->cpi.max_lun = MRSAS_SCSI_MAX_LUNS;
356 			ccb->cpi.unit_number = cam_sim_unit(sim);
357 			ccb->cpi.bus_id = cam_sim_bus(sim);
358 			ccb->cpi.initiator_id = MRSAS_SCSI_INITIATOR_ID;
359 			ccb->cpi.base_transfer_speed = 150000;
360 			strlcpy(ccb->cpi.sim_vid, "FreeBSD", SIM_IDLEN);
361 			strlcpy(ccb->cpi.hba_vid, "AVAGO", HBA_IDLEN);
362 			strlcpy(ccb->cpi.dev_name, cam_sim_name(sim), DEV_IDLEN);
363 			ccb->cpi.transport = XPORT_SPI;
364 			ccb->cpi.transport_version = 2;
365 			ccb->cpi.protocol = PROTO_SCSI;
366 			ccb->cpi.protocol_version = SCSI_REV_2;
367 			if (ccb->cpi.bus_id == 0)
368 				ccb->cpi.max_target = MRSAS_MAX_PD - 1;
369 			else
370 				ccb->cpi.max_target = MRSAS_MAX_LD_IDS - 1;
371 #if (__FreeBSD_version > 704000)
372 			ccb->cpi.maxio = sc->max_num_sge * MRSAS_PAGE_SIZE;
373 #endif
374 			ccb->ccb_h.status = CAM_REQ_CMP;
375 			xpt_done(ccb);
376 			break;
377 		}
378 	default:
379 		{
380 			ccb->ccb_h.status = CAM_REQ_INVALID;
381 			xpt_done(ccb);
382 			break;
383 		}
384 	}
385 }
386 
387 /*
388  * mrsas_scsiio_timeout:	Callback function for IO timed out
389  * input:					mpt command context
390  *
391  * This function will execute after timeout value provided by ccb header from
392  * CAM layer, if timer expires. Driver will run timer for all DCDM and LDIO
393  * coming from CAM layer. This function is callback function for IO timeout
394  * and it runs in no-sleep context. Set do_timedout_reset in Adapter context
395  * so that it will execute OCR/Kill adpter from ocr_thread context.
396  */
397 static void
398 mrsas_scsiio_timeout(void *data)
399 {
400 	struct mrsas_mpt_cmd *cmd;
401 	struct mrsas_softc *sc;
402 	u_int32_t target_id;
403 
404 	if (!data)
405 		return;
406 
407 	cmd = (struct mrsas_mpt_cmd *)data;
408 	sc = cmd->sc;
409 
410 	if (cmd->ccb_ptr == NULL) {
411 		printf("command timeout with NULL ccb\n");
412 		return;
413 	}
414 
415 	/*
416 	 * Below callout is dummy entry so that it will be cancelled from
417 	 * mrsas_cmd_done(). Now Controller will go to OCR/Kill Adapter based
418 	 * on OCR enable/disable property of Controller from ocr_thread
419 	 * context.
420 	 */
421 #if (__FreeBSD_version >= 1000510)
422 	callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
423 	    mrsas_scsiio_timeout, cmd, 0);
424 #else
425 	callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
426 	    mrsas_scsiio_timeout, cmd);
427 #endif
428 
429 	if (cmd->ccb_ptr->cpi.bus_id == 0)
430 		target_id = cmd->ccb_ptr->ccb_h.target_id;
431 	else
432 		target_id = (cmd->ccb_ptr->ccb_h.target_id + (MRSAS_MAX_PD - 1));
433 
434 	/* Save the cmd to be processed for TM, if it is not there in the array */
435 	if (sc->target_reset_pool[target_id] == NULL) {
436 		sc->target_reset_pool[target_id] = cmd;
437 		mrsas_atomic_inc(&sc->target_reset_outstanding);
438 	}
439 
440 	return;
441 }
442 
443 /*
444  * mrsas_startio:	SCSI IO entry point
445  * input:			Adapter instance soft state
446  * 					pointer to CAM Control Block
447  *
448  * This function is the SCSI IO entry point and it initiates IO processing. It
449  * copies the IO and depending if the IO is read/write or inquiry, it would
450  * call mrsas_build_ldio() or mrsas_build_dcdb(), respectively.  It returns 0
451  * if the command is sent to firmware successfully, otherwise it returns 1.
452  */
453 static int32_t
454 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
455     union ccb *ccb)
456 {
457 	struct mrsas_mpt_cmd *cmd, *r1_cmd = NULL;
458 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
459 	struct ccb_scsiio *csio = &(ccb->csio);
460 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
461 	u_int8_t cmd_type;
462 
463 	if ((csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE &&
464 		(!sc->fw_sync_cache_support)) {
465 		ccb->ccb_h.status = CAM_REQ_CMP;
466 		xpt_done(ccb);
467 		return (0);
468 	}
469 	ccb_h->status |= CAM_SIM_QUEUED;
470 
471 	if (mrsas_atomic_inc_return(&sc->fw_outstanding) > sc->max_scsi_cmds) {
472 		ccb_h->status |= CAM_REQUEUE_REQ;
473 		xpt_done(ccb);
474 		mrsas_atomic_dec(&sc->fw_outstanding);
475 		return (0);
476 	}
477 
478 	cmd = mrsas_get_mpt_cmd(sc);
479 
480 	if (!cmd) {
481 		ccb_h->status |= CAM_REQUEUE_REQ;
482 		xpt_done(ccb);
483 		mrsas_atomic_dec(&sc->fw_outstanding);
484 		return (0);
485 	}
486 
487 	if ((ccb_h->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
488 		if (ccb_h->flags & CAM_DIR_IN)
489 			cmd->flags |= MRSAS_DIR_IN;
490 		if (ccb_h->flags & CAM_DIR_OUT)
491 			cmd->flags |= MRSAS_DIR_OUT;
492 	} else
493 		cmd->flags = MRSAS_DIR_NONE;	/* no data */
494 
495 /* For FreeBSD 9.2 and higher */
496 #if (__FreeBSD_version >= 902001)
497 	/*
498 	 * XXX We don't yet support physical addresses here.
499 	 */
500 	switch ((ccb->ccb_h.flags & CAM_DATA_MASK)) {
501 	case CAM_DATA_PADDR:
502 	case CAM_DATA_SG_PADDR:
503 		device_printf(sc->mrsas_dev, "%s: physical addresses not supported\n",
504 		    __func__);
505 		mrsas_release_mpt_cmd(cmd);
506 		ccb_h->status = CAM_REQ_INVALID;
507 		ccb_h->status &= ~CAM_SIM_QUEUED;
508 		goto done;
509 	case CAM_DATA_SG:
510 		device_printf(sc->mrsas_dev, "%s: scatter gather is not supported\n",
511 		    __func__);
512 		mrsas_release_mpt_cmd(cmd);
513 		ccb_h->status = CAM_REQ_INVALID;
514 		goto done;
515 	case CAM_DATA_VADDR:
516 		if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
517 			mrsas_release_mpt_cmd(cmd);
518 			ccb_h->status = CAM_REQ_TOO_BIG;
519 			goto done;
520 		}
521 		cmd->length = csio->dxfer_len;
522 		if (cmd->length)
523 			cmd->data = csio->data_ptr;
524 		break;
525 	case CAM_DATA_BIO:
526 		if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
527 			mrsas_release_mpt_cmd(cmd);
528 			ccb_h->status = CAM_REQ_TOO_BIG;
529 			goto done;
530 		}
531 		cmd->length = csio->dxfer_len;
532 		if (cmd->length)
533 			cmd->data = csio->data_ptr;
534 		break;
535 	default:
536 		ccb->ccb_h.status = CAM_REQ_INVALID;
537 		goto done;
538 	}
539 #else
540 	if (!(ccb_h->flags & CAM_DATA_PHYS)) {	/* Virtual data address */
541 		if (!(ccb_h->flags & CAM_SCATTER_VALID)) {
542 			if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
543 				mrsas_release_mpt_cmd(cmd);
544 				ccb_h->status = CAM_REQ_TOO_BIG;
545 				goto done;
546 			}
547 			cmd->length = csio->dxfer_len;
548 			if (cmd->length)
549 				cmd->data = csio->data_ptr;
550 		} else {
551 			mrsas_release_mpt_cmd(cmd);
552 			ccb_h->status = CAM_REQ_INVALID;
553 			goto done;
554 		}
555 	} else {			/* Data addresses are physical. */
556 		mrsas_release_mpt_cmd(cmd);
557 		ccb_h->status = CAM_REQ_INVALID;
558 		ccb_h->status &= ~CAM_SIM_QUEUED;
559 		goto done;
560 	}
561 #endif
562 	/* save ccb ptr */
563 	cmd->ccb_ptr = ccb;
564 
565 	req_desc = mrsas_get_request_desc(sc, (cmd->index) - 1);
566 	if (!req_desc) {
567 		device_printf(sc->mrsas_dev, "Cannot get request_descriptor.\n");
568 		return (FAIL);
569 	}
570 	memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
571 	cmd->request_desc = req_desc;
572 
573 	if (ccb_h->flags & CAM_CDB_POINTER)
574 		bcopy(csio->cdb_io.cdb_ptr, cmd->io_request->CDB.CDB32, csio->cdb_len);
575 	else
576 		bcopy(csio->cdb_io.cdb_bytes, cmd->io_request->CDB.CDB32, csio->cdb_len);
577 	mtx_lock(&sc->raidmap_lock);
578 
579 	/* Check for IO type READ-WRITE targeted for Logical Volume */
580 	cmd_type = mrsas_find_io_type(sim, ccb);
581 	switch (cmd_type) {
582 	case READ_WRITE_LDIO:
583 		/* Build READ-WRITE IO for Logical Volume  */
584 		if (mrsas_build_ldio_rw(sc, cmd, ccb)) {
585 			device_printf(sc->mrsas_dev, "Build RW LDIO failed.\n");
586 			mtx_unlock(&sc->raidmap_lock);
587 			mrsas_release_mpt_cmd(cmd);
588 			return (1);
589 		}
590 		break;
591 	case NON_READ_WRITE_LDIO:
592 		/* Build NON READ-WRITE IO for Logical Volume  */
593 		if (mrsas_build_ldio_nonrw(sc, cmd, ccb)) {
594 			device_printf(sc->mrsas_dev, "Build NON-RW LDIO failed.\n");
595 			mtx_unlock(&sc->raidmap_lock);
596 			mrsas_release_mpt_cmd(cmd);
597 			return (1);
598 		}
599 		break;
600 	case READ_WRITE_SYSPDIO:
601 	case NON_READ_WRITE_SYSPDIO:
602 		if (sc->secure_jbod_support &&
603 		    (cmd_type == NON_READ_WRITE_SYSPDIO)) {
604 			/* Build NON-RW IO for JBOD */
605 			if (mrsas_build_syspdio(sc, cmd, ccb, sim, 0)) {
606 				device_printf(sc->mrsas_dev,
607 				    "Build SYSPDIO failed.\n");
608 				mtx_unlock(&sc->raidmap_lock);
609 				mrsas_release_mpt_cmd(cmd);
610 				return (1);
611 			}
612 		} else {
613 			/* Build RW IO for JBOD */
614 			if (mrsas_build_syspdio(sc, cmd, ccb, sim, 1)) {
615 				device_printf(sc->mrsas_dev,
616 				    "Build SYSPDIO failed.\n");
617 				mtx_unlock(&sc->raidmap_lock);
618 				mrsas_release_mpt_cmd(cmd);
619 				return (1);
620 			}
621 		}
622 	}
623 	mtx_unlock(&sc->raidmap_lock);
624 
625 	if (cmd->flags == MRSAS_DIR_IN)	/* from device */
626 		cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_READ;
627 	else if (cmd->flags == MRSAS_DIR_OUT)	/* to device */
628 		cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_WRITE;
629 
630 	cmd->io_request->SGLFlags = MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
631 	cmd->io_request->SGLOffset0 = offsetof(MRSAS_RAID_SCSI_IO_REQUEST, SGL) / 4;
632 	cmd->io_request->SenseBufferLowAddress = cmd->sense_phys_addr;
633 	cmd->io_request->SenseBufferLength = MRSAS_SCSI_SENSE_BUFFERSIZE;
634 
635 	req_desc = cmd->request_desc;
636 	req_desc->SCSIIO.SMID = cmd->index;
637 
638 	/*
639 	 * Start timer for IO timeout. Default timeout value is 90 second.
640 	 */
641 	cmd->callout_owner = true;
642 #if (__FreeBSD_version >= 1000510)
643 	callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
644 	    mrsas_scsiio_timeout, cmd, 0);
645 #else
646 	callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
647 	    mrsas_scsiio_timeout, cmd);
648 #endif
649 
650 	if (mrsas_atomic_read(&sc->fw_outstanding) > sc->io_cmds_highwater)
651 		sc->io_cmds_highwater++;
652 
653 	/*
654 	 *  if it is raid 1/10 fp write capable.
655 	 *  try to get second command from pool and construct it.
656 	 *  From FW, it has confirmed that lba values of two PDs corresponds to
657 	 *  single R1/10 LD are always same
658 	 *
659 	 */
660 	/*
661 	 * driver side count always should be less than max_fw_cmds to get
662 	 * new command
663 	 */
664 	if (cmd->r1_alt_dev_handle != MR_DEVHANDLE_INVALID) {
665 		mrsas_prepare_secondRaid1_IO(sc, cmd);
666 		mrsas_fire_cmd(sc, req_desc->addr.u.low,
667 			req_desc->addr.u.high);
668 		r1_cmd = cmd->peer_cmd;
669 		mrsas_fire_cmd(sc, r1_cmd->request_desc->addr.u.low,
670 				r1_cmd->request_desc->addr.u.high);
671 	} else {
672 		mrsas_fire_cmd(sc, req_desc->addr.u.low,
673 			req_desc->addr.u.high);
674 	}
675 
676 	return (0);
677 
678 done:
679 	xpt_done(ccb);
680 	mrsas_atomic_dec(&sc->fw_outstanding);
681 	return (0);
682 }
683 
684 /*
685  * mrsas_find_io_type:	Determines if IO is read/write or inquiry
686  * input:			pointer to CAM Control Block
687  *
688  * This function determines if the IO is read/write or inquiry.  It returns a 1
689  * if the IO is read/write and 0 if it is inquiry.
690  */
691 int
692 mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb)
693 {
694 	struct ccb_scsiio *csio = &(ccb->csio);
695 
696 	switch (csio->cdb_io.cdb_bytes[0]) {
697 	case READ_10:
698 	case WRITE_10:
699 	case READ_12:
700 	case WRITE_12:
701 	case READ_6:
702 	case WRITE_6:
703 	case READ_16:
704 	case WRITE_16:
705 		return (cam_sim_bus(sim) ?
706 		    READ_WRITE_SYSPDIO : READ_WRITE_LDIO);
707 	default:
708 		return (cam_sim_bus(sim) ?
709 		    NON_READ_WRITE_SYSPDIO : NON_READ_WRITE_LDIO);
710 	}
711 }
712 
713 /*
714  * mrsas_get_mpt_cmd:	Get a cmd from free command pool
715  * input:				Adapter instance soft state
716  *
717  * This function removes an MPT command from the command free list and
718  * initializes it.
719  */
720 struct mrsas_mpt_cmd *
721 mrsas_get_mpt_cmd(struct mrsas_softc *sc)
722 {
723 	struct mrsas_mpt_cmd *cmd = NULL;
724 
725 	mtx_lock(&sc->mpt_cmd_pool_lock);
726 	if (!TAILQ_EMPTY(&sc->mrsas_mpt_cmd_list_head)) {
727 		cmd = TAILQ_FIRST(&sc->mrsas_mpt_cmd_list_head);
728 		TAILQ_REMOVE(&sc->mrsas_mpt_cmd_list_head, cmd, next);
729 	} else {
730 		goto out;
731 	}
732 
733 	memset((uint8_t *)cmd->io_request, 0, MRSAS_MPI2_RAID_DEFAULT_IO_FRAME_SIZE);
734 	cmd->data = NULL;
735 	cmd->length = 0;
736 	cmd->flags = 0;
737 	cmd->error_code = 0;
738 	cmd->load_balance = 0;
739 	cmd->ccb_ptr = NULL;
740 out:
741 	mtx_unlock(&sc->mpt_cmd_pool_lock);
742 	return cmd;
743 }
744 
745 /*
746  * mrsas_release_mpt_cmd:	Return a cmd to free command pool
747  * input:					Command packet for return to free command pool
748  *
749  * This function returns an MPT command to the free command list.
750  */
751 void
752 mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd)
753 {
754 	struct mrsas_softc *sc = cmd->sc;
755 
756 	mtx_lock(&sc->mpt_cmd_pool_lock);
757 	cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
758 	cmd->sync_cmd_idx = (u_int32_t)MRSAS_ULONG_MAX;
759 	cmd->peer_cmd = NULL;
760 	cmd->cmd_completed = 0;
761 	memset((uint8_t *)cmd->io_request, 0,
762 		sizeof(MRSAS_RAID_SCSI_IO_REQUEST));
763 	TAILQ_INSERT_HEAD(&(sc->mrsas_mpt_cmd_list_head), cmd, next);
764 	mtx_unlock(&sc->mpt_cmd_pool_lock);
765 
766 	return;
767 }
768 
769 /*
770  * mrsas_get_request_desc:	Get request descriptor from array
771  * input:					Adapter instance soft state
772  * 							SMID index
773  *
774  * This function returns a pointer to the request descriptor.
775  */
776 MRSAS_REQUEST_DESCRIPTOR_UNION *
777 mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index)
778 {
779 	u_int8_t *p;
780 
781 	KASSERT(index < sc->max_fw_cmds, ("req_desc is out of range"));
782 	p = sc->req_desc + sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION) * index;
783 
784 	return (MRSAS_REQUEST_DESCRIPTOR_UNION *) p;
785 }
786 
787 
788 
789 
790 /* mrsas_prepare_secondRaid1_IO
791  * It prepares the raid 1 second IO
792  */
793 void
794 mrsas_prepare_secondRaid1_IO(struct mrsas_softc *sc,
795     struct mrsas_mpt_cmd *cmd)
796 {
797 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc, *req_desc2 = NULL;
798 	struct mrsas_mpt_cmd *r1_cmd;
799 
800 	r1_cmd = cmd->peer_cmd;
801 	req_desc = cmd->request_desc;
802 
803 	/*
804 	 * copy the io request frame as well as 8 SGEs data for r1
805 	 * command
806 	 */
807 	memcpy(r1_cmd->io_request, cmd->io_request,
808 	    (sizeof(MRSAS_RAID_SCSI_IO_REQUEST)));
809 	memcpy(&r1_cmd->io_request->SGL, &cmd->io_request->SGL,
810 	    (sc->max_sge_in_main_msg * sizeof(MPI2_SGE_IO_UNION)));
811 
812 	/* sense buffer is different for r1 command */
813 	r1_cmd->io_request->SenseBufferLowAddress = r1_cmd->sense_phys_addr;
814 	r1_cmd->ccb_ptr = cmd->ccb_ptr;
815 
816 	req_desc2 = mrsas_get_request_desc(sc, r1_cmd->index - 1);
817 	req_desc2->addr.Words = 0;
818 	r1_cmd->request_desc = req_desc2;
819 	req_desc2->SCSIIO.SMID = r1_cmd->index;
820 	req_desc2->SCSIIO.RequestFlags = req_desc->SCSIIO.RequestFlags;
821 	r1_cmd->request_desc->SCSIIO.DevHandle = cmd->r1_alt_dev_handle;
822 	r1_cmd->r1_alt_dev_handle =  cmd->io_request->DevHandle;
823 	r1_cmd->io_request->DevHandle = cmd->r1_alt_dev_handle;
824 	cmd->io_request->RaidContext.raid_context_g35.smid.peerSMID =
825 	    r1_cmd->index;
826 	r1_cmd->io_request->RaidContext.raid_context_g35.smid.peerSMID =
827 		cmd->index;
828 	/*
829 	 * MSIxIndex of both commands request descriptors
830 	 * should be same
831 	 */
832 	r1_cmd->request_desc->SCSIIO.MSIxIndex = cmd->request_desc->SCSIIO.MSIxIndex;
833 	/* span arm is different for r1 cmd */
834 	r1_cmd->io_request->RaidContext.raid_context_g35.spanArm =
835 	    cmd->io_request->RaidContext.raid_context_g35.spanArm + 1;
836 
837 }
838 
839 
840 /*
841  * mrsas_build_ldio_rw:	Builds an LDIO command
842  * input:				Adapter instance soft state
843  * 						Pointer to command packet
844  * 						Pointer to CCB
845  *
846  * This function builds the LDIO command packet.  It returns 0 if the command is
847  * built successfully, otherwise it returns a 1.
848  */
849 int
850 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
851     union ccb *ccb)
852 {
853 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
854 	struct ccb_scsiio *csio = &(ccb->csio);
855 	u_int32_t device_id;
856 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
857 
858 	device_id = ccb_h->target_id;
859 
860 	io_request = cmd->io_request;
861 	io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
862 	io_request->RaidContext.raid_context.status = 0;
863 	io_request->RaidContext.raid_context.exStatus = 0;
864 
865 	/* just the cdb len, other flags zero, and ORed-in later for FP */
866 	io_request->IoFlags = csio->cdb_len;
867 
868 	if (mrsas_setup_io(sc, cmd, ccb, device_id, io_request) != SUCCESS)
869 		device_printf(sc->mrsas_dev, "Build ldio or fpio error\n");
870 
871 	io_request->DataLength = cmd->length;
872 
873 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
874 		if (cmd->sge_count > sc->max_num_sge) {
875 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
876 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
877 			return (FAIL);
878 		}
879 		if (sc->is_ventura || sc->is_aero)
880 			io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
881 		else {
882 			/*
883 			 * numSGE store lower 8 bit of sge_count. numSGEExt store
884 			 * higher 8 bit of sge_count
885 			 */
886 			io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
887 			io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
888 		}
889 
890 	} else {
891 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
892 		return (FAIL);
893 	}
894 	return (0);
895 }
896 
897 /* stream detection on read and and write IOs */
898 static void
899 mrsas_stream_detect(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
900     struct IO_REQUEST_INFO *io_info)
901 {
902 	u_int32_t device_id = io_info->ldTgtId;
903 	LD_STREAM_DETECT *current_ld_SD = sc->streamDetectByLD[device_id];
904 	u_int32_t *track_stream = &current_ld_SD->mruBitMap;
905 	u_int32_t streamNum, shiftedValues, unshiftedValues;
906 	u_int32_t indexValueMask, shiftedValuesMask;
907 	int i;
908 	boolean_t isReadAhead = false;
909 	STREAM_DETECT *current_SD;
910 
911 	/* find possible stream */
912 	for (i = 0; i < MAX_STREAMS_TRACKED; ++i) {
913 		streamNum = (*track_stream >> (i * BITS_PER_INDEX_STREAM)) &
914 				STREAM_MASK;
915 		current_SD = &current_ld_SD->streamTrack[streamNum];
916 		/*
917 		 * if we found a stream, update the raid context and
918 		 * also update the mruBitMap
919 		 */
920 		if (current_SD->nextSeqLBA &&
921 		    io_info->ldStartBlock >= current_SD->nextSeqLBA &&
922 		    (io_info->ldStartBlock <= (current_SD->nextSeqLBA+32)) &&
923 		    (current_SD->isRead == io_info->isRead)) {
924 			if (io_info->ldStartBlock != current_SD->nextSeqLBA &&
925 			    (!io_info->isRead || !isReadAhead)) {
926 				/*
927 				 * Once the API availible we need to change this.
928 				 * At this point we are not allowing any gap
929 				 */
930 				continue;
931 			}
932 			cmd->io_request->RaidContext.raid_context_g35.streamDetected = TRUE;
933 			current_SD->nextSeqLBA = io_info->ldStartBlock + io_info->numBlocks;
934 			/*
935 			 * update the mruBitMap LRU
936 			 */
937 			shiftedValuesMask = (1 << i * BITS_PER_INDEX_STREAM) - 1 ;
938 			shiftedValues = ((*track_stream & shiftedValuesMask) <<
939 			    BITS_PER_INDEX_STREAM);
940 			indexValueMask = STREAM_MASK << i * BITS_PER_INDEX_STREAM;
941 			unshiftedValues = (*track_stream) &
942 			    (~(shiftedValuesMask | indexValueMask));
943 			*track_stream =
944 			    (unshiftedValues | shiftedValues | streamNum);
945 			return;
946 		}
947 	}
948 	/*
949 	 * if we did not find any stream, create a new one from the least recently used
950 	 */
951 	streamNum = (*track_stream >>
952 	    ((MAX_STREAMS_TRACKED - 1) * BITS_PER_INDEX_STREAM)) & STREAM_MASK;
953 	current_SD = &current_ld_SD->streamTrack[streamNum];
954 	current_SD->isRead = io_info->isRead;
955 	current_SD->nextSeqLBA = io_info->ldStartBlock + io_info->numBlocks;
956 	*track_stream = (((*track_stream & ZERO_LAST_STREAM) << 4) | streamNum);
957 	return;
958 }
959 
960 
961 /*
962  * mrsas_setup_io:	Set up data including Fast Path I/O
963  * input:			Adapter instance soft state
964  * 					Pointer to command packet
965  * 					Pointer to CCB
966  *
967  * This function builds the DCDB inquiry command.  It returns 0 if the command
968  * is built successfully, otherwise it returns a 1.
969  */
970 int
971 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
972     union ccb *ccb, u_int32_t device_id,
973     MRSAS_RAID_SCSI_IO_REQUEST * io_request)
974 {
975 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
976 	struct ccb_scsiio *csio = &(ccb->csio);
977 	struct IO_REQUEST_INFO io_info;
978 	MR_DRV_RAID_MAP_ALL *map_ptr;
979 	struct mrsas_mpt_cmd *r1_cmd = NULL;
980 
981 	MR_LD_RAID *raid;
982 	u_int8_t fp_possible;
983 	u_int32_t start_lba_hi, start_lba_lo, ld_block_size, ld;
984 	u_int32_t datalength = 0;
985 
986 	io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
987 
988 	start_lba_lo = 0;
989 	start_lba_hi = 0;
990 	fp_possible = 0;
991 
992 	/*
993 	 * READ_6 (0x08) or WRITE_6 (0x0A) cdb
994 	 */
995 	if (csio->cdb_len == 6) {
996 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[4];
997 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[1] << 16) |
998 		    ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 8) |
999 		    (u_int32_t)csio->cdb_io.cdb_bytes[3];
1000 		start_lba_lo &= 0x1FFFFF;
1001 	}
1002 	/*
1003 	 * READ_10 (0x28) or WRITE_6 (0x2A) cdb
1004 	 */
1005 	else if (csio->cdb_len == 10) {
1006 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[8] |
1007 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 8);
1008 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1009 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1010 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1011 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1012 	}
1013 	/*
1014 	 * READ_12 (0xA8) or WRITE_12 (0xAA) cdb
1015 	 */
1016 	else if (csio->cdb_len == 12) {
1017 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[6] << 24 |
1018 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
1019 		    ((u_int32_t)csio->cdb_io.cdb_bytes[8] << 8) |
1020 		    ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
1021 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1022 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1023 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1024 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1025 	}
1026 	/*
1027 	 * READ_16 (0x88) or WRITE_16 (0xx8A) cdb
1028 	 */
1029 	else if (csio->cdb_len == 16) {
1030 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[10] << 24 |
1031 		    ((u_int32_t)csio->cdb_io.cdb_bytes[11] << 16) |
1032 		    ((u_int32_t)csio->cdb_io.cdb_bytes[12] << 8) |
1033 		    ((u_int32_t)csio->cdb_io.cdb_bytes[13]);
1034 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[6] << 24) |
1035 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
1036 		    (u_int32_t)csio->cdb_io.cdb_bytes[8] << 8 |
1037 		    ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
1038 		start_lba_hi = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
1039 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
1040 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
1041 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
1042 	}
1043 	memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
1044 	io_info.ldStartBlock = ((u_int64_t)start_lba_hi << 32) | start_lba_lo;
1045 	io_info.numBlocks = datalength;
1046 	io_info.ldTgtId = device_id;
1047 	io_info.r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
1048 
1049 	io_request->DataLength = cmd->length;
1050 
1051 	switch (ccb_h->flags & CAM_DIR_MASK) {
1052 	case CAM_DIR_IN:
1053 		io_info.isRead = 1;
1054 		break;
1055 	case CAM_DIR_OUT:
1056 		io_info.isRead = 0;
1057 		break;
1058 	case CAM_DIR_NONE:
1059 	default:
1060 		mrsas_dprint(sc, MRSAS_TRACE, "From %s : DMA Flag is %d \n", __func__, ccb_h->flags & CAM_DIR_MASK);
1061 		break;
1062 	}
1063 
1064 	map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1065 	ld_block_size = MR_LdBlockSizeGet(device_id, map_ptr);
1066 
1067 	ld = MR_TargetIdToLdGet(device_id, map_ptr);
1068 	if ((ld >= MAX_LOGICAL_DRIVES_EXT) || (!sc->fast_path_io)) {
1069 		io_request->RaidContext.raid_context.regLockFlags = 0;
1070 		fp_possible = 0;
1071 	} else {
1072 		if (MR_BuildRaidContext(sc, &io_info, &io_request->RaidContext.raid_context, map_ptr))
1073 			fp_possible = io_info.fpOkForIo;
1074 	}
1075 
1076 	raid = MR_LdRaidGet(ld, map_ptr);
1077 	/* Store the TM capability value in cmd */
1078 	cmd->tmCapable = raid->capability.tmCapable;
1079 
1080 	cmd->request_desc->SCSIIO.MSIxIndex =
1081 	    sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
1082 
1083 	if (sc->is_ventura || sc->is_aero) {
1084 		if (sc->streamDetectByLD) {
1085 			mtx_lock(&sc->stream_lock);
1086 			mrsas_stream_detect(sc, cmd, &io_info);
1087 			mtx_unlock(&sc->stream_lock);
1088 			/* In ventura if stream detected for a read and
1089 			 * it is read ahead capable make this IO as LDIO */
1090 			if (io_request->RaidContext.raid_context_g35.streamDetected &&
1091 					io_info.isRead && io_info.raCapable)
1092 				fp_possible = FALSE;
1093 		}
1094 
1095 		/* Set raid 1/10 fast path write capable bit in io_info.
1096 		 * Note - reset peer_cmd and r1_alt_dev_handle if fp_possible
1097 		 * disabled after this point. Try not to add more check for
1098 		 * fp_possible toggle after this.
1099 		 */
1100 		if (fp_possible &&
1101 				(io_info.r1_alt_dev_handle != MR_DEVHANDLE_INVALID) &&
1102 				(raid->level == 1) && !io_info.isRead) {
1103 			r1_cmd = mrsas_get_mpt_cmd(sc);
1104 			if (mrsas_atomic_inc_return(&sc->fw_outstanding) > sc->max_scsi_cmds) {
1105 				fp_possible = FALSE;
1106 				mrsas_atomic_dec(&sc->fw_outstanding);
1107 			} else {
1108 				r1_cmd = mrsas_get_mpt_cmd(sc);
1109 				if (!r1_cmd) {
1110 					fp_possible = FALSE;
1111 					mrsas_atomic_dec(&sc->fw_outstanding);
1112 				}
1113 				else {
1114 					cmd->peer_cmd = r1_cmd;
1115 					r1_cmd->peer_cmd = cmd;
1116 				}
1117  			}
1118 		}
1119 	}
1120 
1121 	if (fp_possible) {
1122 		mrsas_set_pd_lba(io_request, csio->cdb_len, &io_info, ccb, map_ptr,
1123 		    start_lba_lo, ld_block_size);
1124 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1125 		cmd->request_desc->SCSIIO.RequestFlags =
1126 		    (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
1127 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1128 		if (sc->mrsas_gen3_ctrl) {
1129 			if (io_request->RaidContext.raid_context.regLockFlags == REGION_TYPE_UNUSED)
1130 				cmd->request_desc->SCSIIO.RequestFlags =
1131 				    (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
1132 				    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1133 			io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1134 			io_request->RaidContext.raid_context.nseg = 0x1;
1135 			io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1136 			io_request->RaidContext.raid_context.regLockFlags |=
1137 			    (MR_RL_FLAGS_GRANT_DESTINATION_CUDA |
1138 			    MR_RL_FLAGS_SEQ_NUM_ENABLE);
1139 		} else if (sc->is_ventura || sc->is_aero) {
1140 			io_request->RaidContext.raid_context_g35.Type = MPI2_TYPE_CUDA;
1141 			io_request->RaidContext.raid_context_g35.nseg = 0x1;
1142 			io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1143 			io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1144 			if (io_request->RaidContext.raid_context_g35.routingFlags.bits.sld) {
1145 					io_request->RaidContext.raid_context_g35.RAIDFlags =
1146 					(MR_RAID_FLAGS_IO_SUB_TYPE_CACHE_BYPASS
1147 					<< MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT);
1148 			}
1149 		}
1150 		if ((sc->load_balance_info[device_id].loadBalanceFlag) &&
1151 		    (io_info.isRead)) {
1152 			io_info.devHandle =
1153 			    mrsas_get_updated_dev_handle(sc,
1154 			    &sc->load_balance_info[device_id], &io_info);
1155 			cmd->load_balance = MRSAS_LOAD_BALANCE_FLAG;
1156 			cmd->pd_r1_lb = io_info.pd_after_lb;
1157 			if (sc->is_ventura || sc->is_aero)
1158 				io_request->RaidContext.raid_context_g35.spanArm = io_info.span_arm;
1159 			else
1160 				io_request->RaidContext.raid_context.spanArm = io_info.span_arm;
1161 		} else
1162 			cmd->load_balance = 0;
1163 
1164 		if (sc->is_ventura || sc->is_aero)
1165 				cmd->r1_alt_dev_handle = io_info.r1_alt_dev_handle;
1166 		else
1167 				cmd->r1_alt_dev_handle = MR_DEVHANDLE_INVALID;
1168 
1169 		cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
1170 		io_request->DevHandle = io_info.devHandle;
1171 		cmd->pdInterface = io_info.pdInterface;
1172 	} else {
1173 		/* Not FP IO */
1174 		io_request->RaidContext.raid_context.timeoutValue = map_ptr->raidMap.fpPdIoTimeoutSec;
1175 		cmd->request_desc->SCSIIO.RequestFlags =
1176 		    (MRSAS_REQ_DESCRIPT_FLAGS_LD_IO <<
1177 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1178 		if (sc->mrsas_gen3_ctrl) {
1179 			if (io_request->RaidContext.raid_context.regLockFlags == REGION_TYPE_UNUSED)
1180 				cmd->request_desc->SCSIIO.RequestFlags =
1181 				    (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
1182 				    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1183 			io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1184 			io_request->RaidContext.raid_context.regLockFlags |=
1185 			    (MR_RL_FLAGS_GRANT_DESTINATION_CPU0 |
1186 			    MR_RL_FLAGS_SEQ_NUM_ENABLE);
1187 			io_request->RaidContext.raid_context.nseg = 0x1;
1188 		} else if (sc->is_ventura || sc->is_aero) {
1189 			io_request->RaidContext.raid_context_g35.Type = MPI2_TYPE_CUDA;
1190 			io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1191 			io_request->RaidContext.raid_context_g35.nseg = 0x1;
1192 		}
1193 		io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1194 		io_request->DevHandle = device_id;
1195 	}
1196 	return (0);
1197 }
1198 
1199 /*
1200  * mrsas_build_ldio_nonrw:	Builds an LDIO command
1201  * input:				Adapter instance soft state
1202  * 						Pointer to command packet
1203  * 						Pointer to CCB
1204  *
1205  * This function builds the LDIO command packet.  It returns 0 if the command is
1206  * built successfully, otherwise it returns a 1.
1207  */
1208 int
1209 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
1210     union ccb *ccb)
1211 {
1212 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
1213 	u_int32_t device_id, ld;
1214 	MR_DRV_RAID_MAP_ALL *map_ptr;
1215 	MR_LD_RAID *raid;
1216 	RAID_CONTEXT *pRAID_Context;
1217 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1218 
1219 	io_request = cmd->io_request;
1220 	device_id = ccb_h->target_id;
1221 
1222 	map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1223 	ld = MR_TargetIdToLdGet(device_id, map_ptr);
1224 	raid = MR_LdRaidGet(ld, map_ptr);
1225 	/* get RAID_Context pointer */
1226 	pRAID_Context = &io_request->RaidContext.raid_context;
1227 	/* Store the TM capability value in cmd */
1228 	cmd->tmCapable = raid->capability.tmCapable;
1229 
1230 	/* FW path for LD Non-RW (SCSI management commands) */
1231 	io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1232 	io_request->DevHandle = device_id;
1233 	cmd->request_desc->SCSIIO.RequestFlags =
1234 	    (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1235 	    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1236 
1237 	io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1238 	io_request->LUN[1] = ccb_h->target_lun & 0xF;
1239 	io_request->DataLength = cmd->length;
1240 
1241 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1242 		if (cmd->sge_count > sc->max_num_sge) {
1243 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1244 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1245 			return (1);
1246 		}
1247 		if (sc->is_ventura || sc->is_aero)
1248 			io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
1249 		else {
1250 			/*
1251 			 * numSGE store lower 8 bit of sge_count. numSGEExt store
1252 			 * higher 8 bit of sge_count
1253 			 */
1254 			io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
1255 			io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1256 		}
1257 	} else {
1258 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1259 		return (1);
1260 	}
1261 	return (0);
1262 }
1263 
1264 /*
1265  * mrsas_build_syspdio:	Builds an DCDB command
1266  * input:				Adapter instance soft state
1267  * 						Pointer to command packet
1268  * 						Pointer to CCB
1269  *
1270  * This function builds the DCDB inquiry command.  It returns 0 if the command
1271  * is built successfully, otherwise it returns a 1.
1272  */
1273 int
1274 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
1275     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible)
1276 {
1277 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
1278 	u_int32_t device_id;
1279 	MR_DRV_RAID_MAP_ALL *local_map_ptr;
1280 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1281 	RAID_CONTEXT *pRAID_Context;
1282 	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1283 
1284 	io_request = cmd->io_request;
1285 	/* get RAID_Context pointer */
1286 	pRAID_Context = &io_request->RaidContext.raid_context;
1287 	device_id = ccb_h->target_id;
1288 	local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1289 	io_request->RaidContext.raid_context.RAIDFlags = MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD
1290 	    << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
1291 	io_request->RaidContext.raid_context.regLockFlags = 0;
1292 	io_request->RaidContext.raid_context.regLockRowLBA = 0;
1293 	io_request->RaidContext.raid_context.regLockLength = 0;
1294 
1295 	cmd->pdInterface = sc->target_list[device_id].interface_type;
1296 
1297 	/* If FW supports PD sequence number */
1298 	if (sc->use_seqnum_jbod_fp &&
1299 	    sc->pd_list[device_id].driveType == 0x00) {
1300 		//printf("Using Drv seq num\n");
1301 		pd_sync = (void *)sc->jbodmap_mem[(sc->pd_seq_map_id - 1) & 1];
1302 		cmd->tmCapable = pd_sync->seq[device_id].capability.tmCapable;
1303 		/* More than 256 PD/JBOD support for Ventura */
1304 		if (sc->support_morethan256jbod)
1305 			io_request->RaidContext.raid_context.VirtualDiskTgtId =
1306 				pd_sync->seq[device_id].pdTargetId;
1307 		else
1308 			io_request->RaidContext.raid_context.VirtualDiskTgtId =
1309 				device_id + 255;
1310 		io_request->RaidContext.raid_context.configSeqNum = pd_sync->seq[device_id].seqNum;
1311 		io_request->DevHandle = pd_sync->seq[device_id].devHandle;
1312 		if (sc->is_ventura || sc->is_aero)
1313 			io_request->RaidContext.raid_context_g35.routingFlags.bits.sqn = 1;
1314 		else
1315 			io_request->RaidContext.raid_context.regLockFlags |=
1316 			    (MR_RL_FLAGS_SEQ_NUM_ENABLE | MR_RL_FLAGS_GRANT_DESTINATION_CUDA);
1317 		/* raid_context.Type = MPI2_TYPE_CUDA is valid only,
1318 		 * if FW support Jbod Sequence number
1319 		 */
1320 		io_request->RaidContext.raid_context.Type = MPI2_TYPE_CUDA;
1321 		io_request->RaidContext.raid_context.nseg = 0x1;
1322 	} else if (sc->fast_path_io) {
1323 		//printf("Using LD RAID map\n");
1324 		io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1325 		io_request->RaidContext.raid_context.configSeqNum = 0;
1326 		local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1327 		io_request->DevHandle =
1328 		    local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
1329 	} else {
1330 		//printf("Using FW PATH\n");
1331 		/* Want to send all IO via FW path */
1332 		io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1333 		io_request->RaidContext.raid_context.configSeqNum = 0;
1334 		io_request->DevHandle = MR_DEVHANDLE_INVALID;
1335 	}
1336 
1337 	cmd->request_desc->SCSIIO.DevHandle = io_request->DevHandle;
1338 	cmd->request_desc->SCSIIO.MSIxIndex =
1339 	    sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
1340 
1341 	if (!fp_possible) {
1342 		/* system pd firmware path */
1343 		io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1344 		cmd->request_desc->SCSIIO.RequestFlags =
1345 		    (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1346 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1347 		io_request->RaidContext.raid_context.timeoutValue =
1348 		    local_map_ptr->raidMap.fpPdIoTimeoutSec;
1349 		io_request->RaidContext.raid_context.VirtualDiskTgtId = device_id;
1350 	} else {
1351 		/* system pd fast path */
1352 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1353 		io_request->RaidContext.raid_context.timeoutValue = local_map_ptr->raidMap.fpPdIoTimeoutSec;
1354 
1355 		/*
1356 		 * NOTE - For system pd RW cmds only IoFlags will be FAST_PATH
1357 		 * Because the NON RW cmds will now go via FW Queue
1358 		 * and not the Exception queue
1359 		 */
1360 		if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero)
1361 			io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1362 
1363 		cmd->request_desc->SCSIIO.RequestFlags =
1364 		    (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
1365 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1366 	}
1367 
1368 	io_request->LUN[1] = ccb_h->target_lun & 0xF;
1369 	io_request->DataLength = cmd->length;
1370 
1371 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1372 		if (cmd->sge_count > sc->max_num_sge) {
1373 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1374 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1375 			return (1);
1376 		}
1377 		if (sc->is_ventura || sc->is_aero)
1378 			io_request->RaidContext.raid_context_g35.numSGE = cmd->sge_count;
1379 		else {
1380 			/*
1381 			 * numSGE store lower 8 bit of sge_count. numSGEExt store
1382 			 * higher 8 bit of sge_count
1383 			 */
1384 			io_request->RaidContext.raid_context.numSGE = cmd->sge_count;
1385 			io_request->RaidContext.raid_context.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1386 		}
1387 	} else {
1388 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1389 		return (1);
1390 	}
1391 	return (0);
1392 }
1393 
1394 /*
1395  * mrsas_is_prp_possible:	This function will tell whether PRPs should be built or not
1396  * sc:						Adapter instance soft state
1397  * cmd:						MPT command frame pointer
1398  * nsesg:					Number of OS SGEs
1399  *
1400  * This function will check whether IO is qualified to build PRPs
1401  * return:				true: if PRP should be built
1402  *						false: if IEEE SGLs should be built
1403  */
1404 static boolean_t mrsas_is_prp_possible(struct mrsas_mpt_cmd *cmd,
1405 	bus_dma_segment_t *segs, int nsegs)
1406 {
1407 	struct mrsas_softc *sc = cmd->sc;
1408 	int i;
1409 	u_int32_t data_length = 0;
1410 	bool build_prp = false;
1411 	u_int32_t mr_nvme_pg_size;
1412 
1413 	mr_nvme_pg_size = max(sc->nvme_page_size, MR_DEFAULT_NVME_PAGE_SIZE);
1414 	data_length = cmd->length;
1415 
1416 	if (data_length > (mr_nvme_pg_size * 5))
1417 		build_prp = true;
1418 	else if ((data_length > (mr_nvme_pg_size * 4)) &&
1419 		(data_length <= (mr_nvme_pg_size * 5)))  {
1420 		/* check if 1st SG entry size is < residual beyond 4 pages */
1421 		if ((segs[0].ds_len) < (data_length - (mr_nvme_pg_size * 4)))
1422 			build_prp = true;
1423 	}
1424 
1425 	/*check for SGE holes here*/
1426 	for (i = 0; i < nsegs; i++) {
1427 		/* check for mid SGEs */
1428 		if ((i != 0) && (i != (nsegs - 1))) {
1429 				if ((segs[i].ds_addr % mr_nvme_pg_size) ||
1430 					(segs[i].ds_len % mr_nvme_pg_size)) {
1431 					build_prp = false;
1432 					mrsas_atomic_inc(&sc->sge_holes);
1433 					break;
1434 				}
1435 		}
1436 
1437 		/* check for first SGE*/
1438 		if ((nsegs > 1) && (i == 0)) {
1439 				if ((segs[i].ds_addr + segs[i].ds_len) % mr_nvme_pg_size) {
1440 					build_prp = false;
1441 					mrsas_atomic_inc(&sc->sge_holes);
1442 					break;
1443 				}
1444 		}
1445 
1446 		/* check for Last SGE*/
1447 		if ((nsegs > 1) && (i == (nsegs - 1))) {
1448 				if (segs[i].ds_addr % mr_nvme_pg_size) {
1449 					build_prp = false;
1450 					mrsas_atomic_inc(&sc->sge_holes);
1451 					break;
1452 				}
1453 		}
1454 
1455 	}
1456 
1457 	return build_prp;
1458 }
1459 
1460 /*
1461  * mrsas_map_request:	Map and load data
1462  * input:				Adapter instance soft state
1463  * 						Pointer to command packet
1464  *
1465  * For data from OS, map and load the data buffer into bus space.  The SG list
1466  * is built in the callback.  If the  bus dmamap load is not successful,
1467  * cmd->error_code will contain the  error code and a 1 is returned.
1468  */
1469 int
1470 mrsas_map_request(struct mrsas_softc *sc,
1471     struct mrsas_mpt_cmd *cmd, union ccb *ccb)
1472 {
1473 	u_int32_t retcode = 0;
1474 	struct cam_sim *sim;
1475 
1476 	sim = xpt_path_sim(cmd->ccb_ptr->ccb_h.path);
1477 
1478 	if (cmd->data != NULL) {
1479 		/* Map data buffer into bus space */
1480 		mtx_lock(&sc->io_lock);
1481 #if (__FreeBSD_version >= 902001)
1482 		retcode = bus_dmamap_load_ccb(sc->data_tag, cmd->data_dmamap, ccb,
1483 		    mrsas_data_load_cb, cmd, 0);
1484 #else
1485 		retcode = bus_dmamap_load(sc->data_tag, cmd->data_dmamap, cmd->data,
1486 		    cmd->length, mrsas_data_load_cb, cmd, BUS_DMA_NOWAIT);
1487 #endif
1488 		mtx_unlock(&sc->io_lock);
1489 		if (retcode)
1490 			device_printf(sc->mrsas_dev, "bus_dmamap_load(): retcode = %d\n", retcode);
1491 		if (retcode == EINPROGRESS) {
1492 			device_printf(sc->mrsas_dev, "request load in progress\n");
1493 			mrsas_freeze_simq(cmd, sim);
1494 		}
1495 	}
1496 	if (cmd->error_code)
1497 		return (1);
1498 	return (retcode);
1499 }
1500 
1501 /*
1502  * mrsas_unmap_request:	Unmap and unload data
1503  * input:				Adapter instance soft state
1504  * 						Pointer to command packet
1505  *
1506  * This function unmaps and unloads data from OS.
1507  */
1508 void
1509 mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1510 {
1511 	if (cmd->data != NULL) {
1512 		if (cmd->flags & MRSAS_DIR_IN)
1513 			bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTREAD);
1514 		if (cmd->flags & MRSAS_DIR_OUT)
1515 			bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTWRITE);
1516 		mtx_lock(&sc->io_lock);
1517 		bus_dmamap_unload(sc->data_tag, cmd->data_dmamap);
1518 		mtx_unlock(&sc->io_lock);
1519 	}
1520 }
1521 
1522 /**
1523  * mrsas_build_ieee_sgl -	Prepare IEEE SGLs
1524  * @sc:						Adapter soft state
1525  * @segs:					OS SGEs pointers
1526  * @nseg:					Number of OS SGEs
1527  * @cmd:					Fusion command frame
1528  * return:					void
1529  */
1530 static void mrsas_build_ieee_sgl(struct mrsas_mpt_cmd *cmd, bus_dma_segment_t *segs, int nseg)
1531 {
1532 	struct mrsas_softc *sc = cmd->sc;
1533 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1534 	pMpi25IeeeSgeChain64_t sgl_ptr;
1535 	int i = 0, sg_processed = 0;
1536 
1537 	io_request = cmd->io_request;
1538 	sgl_ptr = (pMpi25IeeeSgeChain64_t)&io_request->SGL;
1539 
1540 	if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1541 		pMpi25IeeeSgeChain64_t sgl_ptr_end = sgl_ptr;
1542 
1543 		sgl_ptr_end += sc->max_sge_in_main_msg - 1;
1544 		sgl_ptr_end->Flags = 0;
1545 	}
1546 	if (nseg != 0) {
1547 		for (i = 0; i < nseg; i++) {
1548 			sgl_ptr->Address = segs[i].ds_addr;
1549 			sgl_ptr->Length = segs[i].ds_len;
1550 			sgl_ptr->Flags = 0;
1551 			if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1552 				if (i == nseg - 1)
1553 					sgl_ptr->Flags = IEEE_SGE_FLAGS_END_OF_LIST;
1554 			}
1555 			sgl_ptr++;
1556 			sg_processed = i + 1;
1557 			if ((sg_processed == (sc->max_sge_in_main_msg - 1)) &&
1558 				(nseg > sc->max_sge_in_main_msg)) {
1559 				pMpi25IeeeSgeChain64_t sg_chain;
1560 
1561 				if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero) {
1562 					if ((cmd->io_request->IoFlags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1563 						!= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1564 						cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1565 					else
1566 						cmd->io_request->ChainOffset = 0;
1567 				} else
1568 					cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1569 				sg_chain = sgl_ptr;
1570 				if (sc->mrsas_gen3_ctrl || sc->is_ventura || sc->is_aero)
1571 					sg_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT;
1572 				else
1573 					sg_chain->Flags = (IEEE_SGE_FLAGS_CHAIN_ELEMENT | MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
1574 				sg_chain->Length = (sizeof(MPI2_SGE_IO_UNION) * (nseg - sg_processed));
1575 				sg_chain->Address = cmd->chain_frame_phys_addr;
1576 				sgl_ptr = (pMpi25IeeeSgeChain64_t)cmd->chain_frame;
1577 			}
1578 		}
1579 	}
1580 }
1581 
1582 /**
1583  * mrsas_build_prp_nvme - Prepare PRPs(Physical Region Page)- SGLs specific to NVMe drives only
1584  * @sc:						Adapter soft state
1585  * @segs:					OS SGEs pointers
1586  * @nseg:					Number of OS SGEs
1587  * @cmd:					Fusion command frame
1588  * return:					void
1589  */
1590 static void mrsas_build_prp_nvme(struct mrsas_mpt_cmd *cmd, bus_dma_segment_t *segs, int nseg)
1591 {
1592 	struct mrsas_softc *sc = cmd->sc;
1593 	int sge_len, offset, num_prp_in_chain = 0;
1594 	pMpi25IeeeSgeChain64_t main_chain_element, ptr_first_sgl, sgl_ptr;
1595 	u_int64_t *ptr_sgl;
1596 	bus_addr_t ptr_sgl_phys;
1597 	u_int64_t sge_addr;
1598 	u_int32_t page_mask, page_mask_result, i = 0;
1599 	u_int32_t first_prp_len;
1600 	int data_len = cmd->length;
1601 	u_int32_t mr_nvme_pg_size = max(sc->nvme_page_size,
1602 					MR_DEFAULT_NVME_PAGE_SIZE);
1603 
1604 	sgl_ptr = (pMpi25IeeeSgeChain64_t) &cmd->io_request->SGL;
1605 	/*
1606 	 * NVMe has a very convoluted PRP format.  One PRP is required
1607 	 * for each page or partial page.  We need to split up OS SG
1608 	 * entries if they are longer than one page or cross a page
1609 	 * boundary.  We also have to insert a PRP list pointer entry as
1610 	 * the last entry in each physical page of the PRP list.
1611 	 *
1612 	 * NOTE: The first PRP "entry" is actually placed in the first
1613 	 * SGL entry in the main message in IEEE 64 format.  The 2nd
1614 	 * entry in the main message is the chain element, and the rest
1615 	 * of the PRP entries are built in the contiguous PCIe buffer.
1616 	 */
1617 	page_mask = mr_nvme_pg_size - 1;
1618 	ptr_sgl = (u_int64_t *) cmd->chain_frame;
1619 	ptr_sgl_phys = cmd->chain_frame_phys_addr;
1620 	memset(ptr_sgl, 0, sc->max_chain_frame_sz);
1621 
1622 	/* Build chain frame element which holds all PRPs except first*/
1623 	main_chain_element = (pMpi25IeeeSgeChain64_t)
1624 	    ((u_int8_t *)sgl_ptr + sizeof(MPI25_IEEE_SGE_CHAIN64));
1625 
1626 
1627 	main_chain_element->Address = cmd->chain_frame_phys_addr;
1628 	main_chain_element->NextChainOffset = 0;
1629 	main_chain_element->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT |
1630 					IEEE_SGE_FLAGS_SYSTEM_ADDR |
1631 					MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
1632 
1633 
1634 	/* Build first PRP, SGE need not to be PAGE aligned*/
1635 	ptr_first_sgl = sgl_ptr;
1636 	sge_addr = segs[i].ds_addr;
1637 	sge_len = segs[i].ds_len;
1638 	i++;
1639 
1640 	offset = (u_int32_t) (sge_addr & page_mask);
1641 	first_prp_len = mr_nvme_pg_size - offset;
1642 
1643 	ptr_first_sgl->Address = sge_addr;
1644 	ptr_first_sgl->Length = first_prp_len;
1645 
1646 	data_len -= first_prp_len;
1647 
1648 	if (sge_len > first_prp_len) {
1649 		sge_addr += first_prp_len;
1650 		sge_len -= first_prp_len;
1651 	} else if (sge_len == first_prp_len) {
1652 		sge_addr = segs[i].ds_addr;
1653 		sge_len = segs[i].ds_len;
1654 		i++;
1655 	}
1656 
1657 	for (;;) {
1658 
1659 		offset = (u_int32_t) (sge_addr & page_mask);
1660 
1661 		/* Put PRP pointer due to page boundary*/
1662 		page_mask_result = (uintptr_t)(ptr_sgl + 1) & page_mask;
1663 		if (!page_mask_result) {
1664 			device_printf(sc->mrsas_dev, "BRCM: Put prp pointer as we are at page boundary"
1665 					" ptr_sgl: 0x%p\n", ptr_sgl);
1666 			ptr_sgl_phys++;
1667 			*ptr_sgl = (uintptr_t)ptr_sgl_phys;
1668 			ptr_sgl++;
1669 			num_prp_in_chain++;
1670 		}
1671 
1672 		*ptr_sgl = sge_addr;
1673 		ptr_sgl++;
1674 		ptr_sgl_phys++;
1675 		num_prp_in_chain++;
1676 
1677 
1678 		sge_addr += mr_nvme_pg_size;
1679 		sge_len -= mr_nvme_pg_size;
1680 		data_len -= mr_nvme_pg_size;
1681 
1682 		if (data_len <= 0)
1683 			break;
1684 
1685 		if (sge_len > 0)
1686 			continue;
1687 
1688 		sge_addr = segs[i].ds_addr;
1689 		sge_len = segs[i].ds_len;
1690 		i++;
1691 	}
1692 
1693 	main_chain_element->Length = num_prp_in_chain * sizeof(u_int64_t);
1694 	mrsas_atomic_inc(&sc->prp_count);
1695 
1696 }
1697 
1698 /*
1699  * mrsas_data_load_cb:	Callback entry point to build SGLs
1700  * input:				Pointer to command packet as argument
1701  *						Pointer to segment
1702  *						Number of segments Error
1703  *
1704  * This is the callback function of the bus dma map load.  It builds SG list
1705  */
1706 static void
1707 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1708 {
1709 	struct mrsas_mpt_cmd *cmd = (struct mrsas_mpt_cmd *)arg;
1710 	struct mrsas_softc *sc = cmd->sc;
1711 	boolean_t build_prp = false;
1712 
1713 	if (error) {
1714 		cmd->error_code = error;
1715 		device_printf(sc->mrsas_dev, "mrsas_data_load_cb_prp: error=%d\n", error);
1716 		if (error == EFBIG) {
1717 			cmd->ccb_ptr->ccb_h.status = CAM_REQ_TOO_BIG;
1718 			return;
1719 		}
1720 	}
1721 	if (cmd->flags & MRSAS_DIR_IN)
1722 		bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1723 		    BUS_DMASYNC_PREREAD);
1724 	if (cmd->flags & MRSAS_DIR_OUT)
1725 		bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1726 		    BUS_DMASYNC_PREWRITE);
1727 	if (nseg > sc->max_num_sge) {
1728 		device_printf(sc->mrsas_dev, "SGE count is too large or 0.\n");
1729 		return;
1730 	}
1731 
1732 	/* Check for whether PRPs should be built or IEEE SGLs*/
1733 	if ((cmd->io_request->IoFlags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH) &&
1734 			(cmd->pdInterface == NVME_PD))
1735 		build_prp = mrsas_is_prp_possible(cmd, segs, nseg);
1736 
1737 	if (build_prp == true)
1738 		mrsas_build_prp_nvme(cmd, segs, nseg);
1739 	else
1740 		mrsas_build_ieee_sgl(cmd, segs, nseg);
1741 
1742 	cmd->sge_count = nseg;
1743 }
1744 
1745 /*
1746  * mrsas_freeze_simq:	Freeze SIM queue
1747  * input:				Pointer to command packet
1748  * 						Pointer to SIM
1749  *
1750  * This function freezes the sim queue.
1751  */
1752 static void
1753 mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim)
1754 {
1755 	union ccb *ccb = (union ccb *)(cmd->ccb_ptr);
1756 
1757 	xpt_freeze_simq(sim, 1);
1758 	ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1759 	ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1760 }
1761 
1762 void
1763 mrsas_xpt_freeze(struct mrsas_softc *sc)
1764 {
1765 	xpt_freeze_simq(sc->sim_0, 1);
1766 	xpt_freeze_simq(sc->sim_1, 1);
1767 }
1768 
1769 void
1770 mrsas_xpt_release(struct mrsas_softc *sc)
1771 {
1772 	xpt_release_simq(sc->sim_0, 1);
1773 	xpt_release_simq(sc->sim_1, 1);
1774 }
1775 
1776 /*
1777  * mrsas_cmd_done:	Perform remaining command completion
1778  * input:			Adapter instance soft state  Pointer to command packet
1779  *
1780  * This function calls ummap request and releases the MPT command.
1781  */
1782 void
1783 mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1784 {
1785 	mrsas_unmap_request(sc, cmd);
1786 
1787 	mtx_lock(&sc->sim_lock);
1788 	if (cmd->callout_owner) {
1789 		callout_stop(&cmd->cm_callout);
1790 		cmd->callout_owner  = false;
1791 	}
1792 	xpt_done(cmd->ccb_ptr);
1793 	cmd->ccb_ptr = NULL;
1794 	mtx_unlock(&sc->sim_lock);
1795 	mrsas_release_mpt_cmd(cmd);
1796 }
1797 
1798 /*
1799  * mrsas_cam_poll:	Polling entry point
1800  * input:			Pointer to SIM
1801  *
1802  * This is currently a stub function.
1803  */
1804 static void
1805 mrsas_cam_poll(struct cam_sim *sim)
1806 {
1807 	int i;
1808 	struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
1809 
1810 	if (sc->msix_vectors != 0){
1811 		for (i=0; i<sc->msix_vectors; i++){
1812 			mrsas_complete_cmd(sc, i);
1813 		}
1814 	} else {
1815 		mrsas_complete_cmd(sc, 0);
1816 	}
1817 }
1818 
1819 /*
1820  * mrsas_bus_scan:	Perform bus scan
1821  * input:			Adapter instance soft state
1822  *
1823  * This mrsas_bus_scan function is needed for FreeBSD 7.x.  Also, it should not
1824  * be called in FreeBSD 8.x and later versions, where the bus scan is
1825  * automatic.
1826  */
1827 int
1828 mrsas_bus_scan(struct mrsas_softc *sc)
1829 {
1830 	union ccb *ccb_0;
1831 	union ccb *ccb_1;
1832 
1833 	if ((ccb_0 = xpt_alloc_ccb()) == NULL) {
1834 		return (ENOMEM);
1835 	}
1836 	if ((ccb_1 = xpt_alloc_ccb()) == NULL) {
1837 		xpt_free_ccb(ccb_0);
1838 		return (ENOMEM);
1839 	}
1840 	mtx_lock(&sc->sim_lock);
1841 	if (xpt_create_path(&ccb_0->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_0),
1842 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1843 		xpt_free_ccb(ccb_0);
1844 		xpt_free_ccb(ccb_1);
1845 		mtx_unlock(&sc->sim_lock);
1846 		return (EIO);
1847 	}
1848 	if (xpt_create_path(&ccb_1->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_1),
1849 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1850 		xpt_free_ccb(ccb_0);
1851 		xpt_free_ccb(ccb_1);
1852 		mtx_unlock(&sc->sim_lock);
1853 		return (EIO);
1854 	}
1855 	mtx_unlock(&sc->sim_lock);
1856 	xpt_rescan(ccb_0);
1857 	xpt_rescan(ccb_1);
1858 
1859 	return (0);
1860 }
1861 
1862 /*
1863  * mrsas_bus_scan_sim:	Perform bus scan per SIM
1864  * input:				adapter instance soft state
1865  *
1866  * This function will be called from Event handler on LD creation/deletion,
1867  * JBOD on/off.
1868  */
1869 int
1870 mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim)
1871 {
1872 	union ccb *ccb;
1873 
1874 	if ((ccb = xpt_alloc_ccb()) == NULL) {
1875 		return (ENOMEM);
1876 	}
1877 	mtx_lock(&sc->sim_lock);
1878 	if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, cam_sim_path(sim),
1879 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1880 		xpt_free_ccb(ccb);
1881 		mtx_unlock(&sc->sim_lock);
1882 		return (EIO);
1883 	}
1884 	mtx_unlock(&sc->sim_lock);
1885 	xpt_rescan(ccb);
1886 
1887 	return (0);
1888 }
1889 
1890 /*
1891  * mrsas_track_scsiio:  Track IOs for a given target in the mpt_cmd_list
1892  * input:           Adapter instance soft state
1893  *                  Target ID of target
1894  *                  Bus ID of the target
1895  *
1896  * This function checks for any pending IO in the whole mpt_cmd_list pool
1897  * with the bus_id and target_id passed in arguments. If some IO is found
1898  * that means target reset is not successfully completed.
1899  *
1900  * Returns FAIL if IOs pending to the target device, else return SUCCESS
1901  */
1902 static int
1903 mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t tgt_id, u_int32_t bus_id)
1904 {
1905 	int i;
1906 	struct mrsas_mpt_cmd *mpt_cmd = NULL;
1907 
1908 	for (i = 0 ; i < sc->max_fw_cmds; i++) {
1909 		mpt_cmd = sc->mpt_cmd_list[i];
1910 
1911 		/*
1912 		 * Check if the target_id and bus_id is same as the timeout IO
1913 		 */
1914 		if (mpt_cmd->ccb_ptr) {
1915 			/* bus_id = 1 denotes a VD */
1916 			if (bus_id == 1)
1917 				tgt_id =
1918 				    (mpt_cmd->ccb_ptr->ccb_h.target_id - (MRSAS_MAX_PD - 1));
1919 
1920 			if (mpt_cmd->ccb_ptr->cpi.bus_id == bus_id &&
1921 			    mpt_cmd->ccb_ptr->ccb_h.target_id == tgt_id) {
1922 				device_printf(sc->mrsas_dev,
1923 				    "IO commands pending to target id %d\n", tgt_id);
1924 				return FAIL;
1925 			}
1926 		}
1927 	}
1928 
1929 	return SUCCESS;
1930 }
1931 
1932 #if TM_DEBUG
1933 /*
1934  * mrsas_tm_response_code: Prints TM response code received from FW
1935  * input:           Adapter instance soft state
1936  *                  MPI reply returned from firmware
1937  *
1938  * Returns nothing.
1939  */
1940 static void
1941 mrsas_tm_response_code(struct mrsas_softc *sc,
1942 	MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply)
1943 {
1944 	char *desc;
1945 
1946 	switch (mpi_reply->ResponseCode) {
1947 	case MPI2_SCSITASKMGMT_RSP_TM_COMPLETE:
1948 		desc = "task management request completed";
1949 		break;
1950 	case MPI2_SCSITASKMGMT_RSP_INVALID_FRAME:
1951 		desc = "invalid frame";
1952 		break;
1953 	case MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED:
1954 		desc = "task management request not supported";
1955 		break;
1956 	case MPI2_SCSITASKMGMT_RSP_TM_FAILED:
1957 		desc = "task management request failed";
1958 		break;
1959 	case MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED:
1960 		desc = "task management request succeeded";
1961 		break;
1962 	case MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN:
1963 		desc = "invalid lun";
1964 		break;
1965 	case 0xA:
1966 		desc = "overlapped tag attempted";
1967 		break;
1968 	case MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC:
1969 		desc = "task queued, however not sent to target";
1970 		break;
1971 	default:
1972 		desc = "unknown";
1973 		break;
1974 	}
1975 	device_printf(sc->mrsas_dev, "response_code(%01x): %s\n",
1976 	    mpi_reply->ResponseCode, desc);
1977 	device_printf(sc->mrsas_dev,
1978 	    "TerminationCount/DevHandle/Function/TaskType/IOCStat/IOCLoginfo\n"
1979 	    "0x%x/0x%x/0x%x/0x%x/0x%x/0x%x\n",
1980 	    mpi_reply->TerminationCount, mpi_reply->DevHandle,
1981 	    mpi_reply->Function, mpi_reply->TaskType,
1982 	    mpi_reply->IOCStatus, mpi_reply->IOCLogInfo);
1983 }
1984 #endif
1985 
1986 /*
1987  * mrsas_issue_tm:  Fires the TM command to FW and waits for completion
1988  * input:           Adapter instance soft state
1989  *                  reqest descriptor compiled by mrsas_reset_targets
1990  *
1991  * Returns FAIL if TM command TIMEDOUT from FW else SUCCESS.
1992  */
1993 static int
1994 mrsas_issue_tm(struct mrsas_softc *sc,
1995 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc)
1996 {
1997 	int sleep_stat;
1998 
1999 	mrsas_fire_cmd(sc, req_desc->addr.u.low, req_desc->addr.u.high);
2000 	sleep_stat = msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "tm_sleep", 50*hz);
2001 
2002 	if (sleep_stat == EWOULDBLOCK) {
2003 		device_printf(sc->mrsas_dev, "tm cmd TIMEDOUT\n");
2004 		return FAIL;
2005 	}
2006 
2007 	return SUCCESS;
2008 }
2009 
2010 /*
2011  * mrsas_reset_targets : Gathers info to fire a target reset command
2012  * input:           Adapter instance soft state
2013  *
2014  * This function compiles data for a target reset command to be fired to the FW
2015  * and then traverse the target_reset_pool to see targets with TIMEDOUT IOs.
2016  *
2017  * Returns SUCCESS or FAIL
2018  */
2019 int mrsas_reset_targets(struct mrsas_softc *sc)
2020 {
2021 	struct mrsas_mpt_cmd *tm_mpt_cmd = NULL;
2022 	struct mrsas_mpt_cmd *tgt_mpt_cmd = NULL;
2023 	MR_TASK_MANAGE_REQUEST *mr_request;
2024 	MPI2_SCSI_TASK_MANAGE_REQUEST *tm_mpi_request;
2025 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
2026 	int retCode = FAIL, count, i, outstanding;
2027 	u_int32_t MSIxIndex, bus_id;
2028 	target_id_t tgt_id;
2029 #if TM_DEBUG
2030 	MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply;
2031 #endif
2032 
2033 	outstanding = mrsas_atomic_read(&sc->fw_outstanding);
2034 
2035 	if (!outstanding) {
2036 		device_printf(sc->mrsas_dev, "NO IOs pending...\n");
2037 		mrsas_atomic_set(&sc->target_reset_outstanding, 0);
2038 		retCode = SUCCESS;
2039 		goto return_status;
2040 	} else if (sc->adprecovery != MRSAS_HBA_OPERATIONAL) {
2041 		device_printf(sc->mrsas_dev, "Controller is not operational\n");
2042 		goto return_status;
2043 	} else {
2044 		/* Some more error checks will be added in future */
2045 	}
2046 
2047 	/* Get an mpt frame and an index to fire the TM cmd */
2048 	tm_mpt_cmd = mrsas_get_mpt_cmd(sc);
2049 	if (!tm_mpt_cmd) {
2050 		retCode = FAIL;
2051 		goto return_status;
2052 	}
2053 
2054 	req_desc = mrsas_get_request_desc(sc, (tm_mpt_cmd->index) - 1);
2055 	if (!req_desc) {
2056 		device_printf(sc->mrsas_dev, "Cannot get request_descriptor for tm.\n");
2057 		retCode = FAIL;
2058 		goto release_mpt;
2059 	}
2060 	memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
2061 
2062 	req_desc->HighPriority.SMID = tm_mpt_cmd->index;
2063 	req_desc->HighPriority.RequestFlags =
2064 	    (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
2065 	    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
2066 	req_desc->HighPriority.MSIxIndex =  0;
2067 	req_desc->HighPriority.LMID = 0;
2068 	req_desc->HighPriority.Reserved1 = 0;
2069 	tm_mpt_cmd->request_desc = req_desc;
2070 
2071 	mr_request = (MR_TASK_MANAGE_REQUEST *) tm_mpt_cmd->io_request;
2072 	memset(mr_request, 0, sizeof(MR_TASK_MANAGE_REQUEST));
2073 
2074 	tm_mpi_request = (MPI2_SCSI_TASK_MANAGE_REQUEST *) &mr_request->TmRequest;
2075 	tm_mpi_request->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
2076 	tm_mpi_request->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
2077 	tm_mpi_request->TaskMID = 0; /* smid task */
2078 	tm_mpi_request->LUN[1] = 0;
2079 
2080 	/* Traverse the tm_mpt pool to get valid entries */
2081 	for (i = 0 ; i < MRSAS_MAX_TM_TARGETS; i++) {
2082 		if(!sc->target_reset_pool[i]) {
2083 			continue;
2084 		} else {
2085 			tgt_mpt_cmd = sc->target_reset_pool[i];
2086 		}
2087 
2088 		tgt_id = i;
2089 
2090 		/* See if the target is tm capable or NOT */
2091 		if (!tgt_mpt_cmd->tmCapable) {
2092 			device_printf(sc->mrsas_dev, "Task management NOT SUPPORTED for "
2093 			    "CAM target:%d\n", tgt_id);
2094 
2095 			retCode = FAIL;
2096 			goto release_mpt;
2097 		}
2098 
2099 		tm_mpi_request->DevHandle = tgt_mpt_cmd->io_request->DevHandle;
2100 
2101 		if (i < (MRSAS_MAX_PD - 1)) {
2102 			mr_request->uTmReqReply.tmReqFlags.isTMForPD = 1;
2103 			bus_id = 0;
2104 		} else {
2105 			mr_request->uTmReqReply.tmReqFlags.isTMForLD = 1;
2106 			bus_id = 1;
2107 		}
2108 
2109 		device_printf(sc->mrsas_dev, "TM will be fired for "
2110 		    "CAM target:%d and bus_id %d\n", tgt_id, bus_id);
2111 
2112 		sc->ocr_chan = (void *)&tm_mpt_cmd;
2113 		retCode = mrsas_issue_tm(sc, req_desc);
2114 		if (retCode == FAIL)
2115 			goto release_mpt;
2116 
2117 #if TM_DEBUG
2118 		mpi_reply =
2119 		    (MPI2_SCSI_TASK_MANAGE_REPLY *) &mr_request->uTmReqReply.TMReply;
2120 		mrsas_tm_response_code(sc, mpi_reply);
2121 #endif
2122 		mrsas_atomic_dec(&sc->target_reset_outstanding);
2123 		sc->target_reset_pool[i] = NULL;
2124 
2125 		/* Check for pending cmds in the mpt_cmd_pool with the tgt_id */
2126 		mrsas_disable_intr(sc);
2127 		/* Wait for 1 second to complete parallel ISR calling same
2128 		 * mrsas_complete_cmd()
2129 		 */
2130 		msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "mrsas_reset_wakeup",
2131 		   1 * hz);
2132 		count = sc->msix_vectors > 0 ? sc->msix_vectors : 1;
2133 		mtx_unlock(&sc->sim_lock);
2134 		for (MSIxIndex = 0; MSIxIndex < count; MSIxIndex++)
2135 		    mrsas_complete_cmd(sc, MSIxIndex);
2136 		mtx_lock(&sc->sim_lock);
2137 		retCode = mrsas_track_scsiio(sc, tgt_id, bus_id);
2138 		mrsas_enable_intr(sc);
2139 
2140 		if (retCode == FAIL)
2141 			goto release_mpt;
2142 	}
2143 
2144 	device_printf(sc->mrsas_dev, "Number of targets outstanding "
2145 	    "after reset: %d\n", mrsas_atomic_read(&sc->target_reset_outstanding));
2146 
2147 release_mpt:
2148 	mrsas_release_mpt_cmd(tm_mpt_cmd);
2149 return_status:
2150 	device_printf(sc->mrsas_dev, "target reset %s!!\n",
2151 		(retCode == SUCCESS) ? "SUCCESS" : "FAIL");
2152 
2153 	return retCode;
2154 }
2155 
2156