xref: /freebsd/sys/dev/mrsas/mrsas_cam.c (revision 1b99d52f261bfacfb9bb149d33ed6444364ac219)
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 
52 #include <sys/time.h>			/* XXX for pcpu.h */
53 #include <sys/pcpu.h>			/* XXX for PCPU_GET */
54 
55 #define	smp_processor_id()  PCPU_GET(cpuid)
56 
57 /*
58  * Function prototypes
59  */
60 int	mrsas_cam_attach(struct mrsas_softc *sc);
61 int	mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb);
62 int	mrsas_bus_scan(struct mrsas_softc *sc);
63 int	mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim);
64 int
65 mrsas_map_request(struct mrsas_softc *sc,
66     struct mrsas_mpt_cmd *cmd, union ccb *ccb);
67 int
68 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
69     union ccb *ccb);
70 int
71 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
72     union ccb *ccb);
73 int
74 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
75     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible);
76 int
77 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
78     union ccb *ccb, u_int32_t device_id,
79     MRSAS_RAID_SCSI_IO_REQUEST * io_request);
80 void	mrsas_xpt_freeze(struct mrsas_softc *sc);
81 void	mrsas_xpt_release(struct mrsas_softc *sc);
82 void	mrsas_cam_detach(struct mrsas_softc *sc);
83 void	mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd);
84 void	mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
85 void	mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd);
86 void
87 mrsas_fire_cmd(struct mrsas_softc *sc, u_int32_t req_desc_lo,
88     u_int32_t req_desc_hi);
89 void
90 mrsas_set_pd_lba(MRSAS_RAID_SCSI_IO_REQUEST * io_request,
91     u_int8_t cdb_len, struct IO_REQUEST_INFO *io_info, union ccb *ccb,
92     MR_DRV_RAID_MAP_ALL * local_map_ptr, u_int32_t ref_tag,
93     u_int32_t ld_block_size);
94 static void mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim);
95 static void mrsas_cam_poll(struct cam_sim *sim);
96 static void mrsas_action(struct cam_sim *sim, union ccb *ccb);
97 static void mrsas_scsiio_timeout(void *data);
98 static int mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t id, u_int32_t bus_id);
99 static void mrsas_tm_response_code(struct mrsas_softc *sc,
100     MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply);
101 static int mrsas_issue_tm(struct mrsas_softc *sc,
102     MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc);
103 static void
104 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs,
105     int nseg, int error);
106 static int32_t
107 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
108     union ccb *ccb);
109 struct mrsas_mpt_cmd *mrsas_get_mpt_cmd(struct mrsas_softc *sc);
110 MRSAS_REQUEST_DESCRIPTOR_UNION *
111 	mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index);
112 
113 extern void
114 mrsas_map_mpt_cmd_status(struct mrsas_mpt_cmd *cmd, u_int8_t status,
115     u_int8_t extStatus);
116 extern int mrsas_reset_targets(struct mrsas_softc *sc);
117 extern u_int16_t MR_TargetIdToLdGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map);
118 extern u_int32_t
119 MR_LdBlockSizeGet(u_int32_t ldTgtId, MR_DRV_RAID_MAP_ALL * map,
120     struct mrsas_softc *sc);
121 extern void mrsas_isr(void *arg);
122 extern void mrsas_aen_handler(struct mrsas_softc *sc);
123 extern u_int8_t
124 MR_BuildRaidContext(struct mrsas_softc *sc,
125     struct IO_REQUEST_INFO *io_info, RAID_CONTEXT * pRAID_Context,
126     MR_DRV_RAID_MAP_ALL * map);
127 extern u_int16_t
128 MR_LdSpanArrayGet(u_int32_t ld, u_int32_t span,
129     MR_DRV_RAID_MAP_ALL * map);
130 extern u_int16_t
131 mrsas_get_updated_dev_handle(struct mrsas_softc *sc,
132     PLD_LOAD_BALANCE_INFO lbInfo, struct IO_REQUEST_INFO *io_info);
133 extern u_int8_t
134 megasas_get_best_arm(PLD_LOAD_BALANCE_INFO lbInfo, u_int8_t arm,
135     u_int64_t block, u_int32_t count);
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 
141 
142 /*
143  * mrsas_cam_attach:	Main entry to CAM subsystem
144  * input:				Adapter instance soft state
145  *
146  * This function is called from mrsas_attach() during initialization to perform
147  * SIM allocations and XPT bus registration.  If the kernel version is 7.4 or
148  * earlier, it would also initiate a bus scan.
149  */
150 int
151 mrsas_cam_attach(struct mrsas_softc *sc)
152 {
153 	struct cam_devq *devq;
154 	int mrsas_cam_depth;
155 
156 	mrsas_cam_depth = sc->max_fw_cmds - MRSAS_INTERNAL_CMDS;
157 
158 	if ((devq = cam_simq_alloc(mrsas_cam_depth)) == NULL) {
159 		device_printf(sc->mrsas_dev, "Cannot allocate SIM queue\n");
160 		return (ENOMEM);
161 	}
162 	/*
163 	 * Create SIM for bus 0 and register, also create path
164 	 */
165 	sc->sim_0 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
166 	    device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
167 	    mrsas_cam_depth, devq);
168 	if (sc->sim_0 == NULL) {
169 		cam_simq_free(devq);
170 		device_printf(sc->mrsas_dev, "Cannot register SIM\n");
171 		return (ENXIO);
172 	}
173 	/* Initialize taskqueue for Event Handling */
174 	TASK_INIT(&sc->ev_task, 0, (void *)mrsas_aen_handler, sc);
175 	sc->ev_tq = taskqueue_create("mrsas_taskq", M_NOWAIT | M_ZERO,
176 	    taskqueue_thread_enqueue, &sc->ev_tq);
177 
178 	/* Run the task queue with lowest priority */
179 	taskqueue_start_threads(&sc->ev_tq, 1, 255, "%s taskq",
180 	    device_get_nameunit(sc->mrsas_dev));
181 	mtx_lock(&sc->sim_lock);
182 	if (xpt_bus_register(sc->sim_0, sc->mrsas_dev, 0) != CAM_SUCCESS) {
183 		cam_sim_free(sc->sim_0, TRUE);	/* passing true frees the devq */
184 		mtx_unlock(&sc->sim_lock);
185 		return (ENXIO);
186 	}
187 	if (xpt_create_path(&sc->path_0, NULL, cam_sim_path(sc->sim_0),
188 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
189 		xpt_bus_deregister(cam_sim_path(sc->sim_0));
190 		cam_sim_free(sc->sim_0, TRUE);	/* passing true will free the
191 						 * devq */
192 		mtx_unlock(&sc->sim_lock);
193 		return (ENXIO);
194 	}
195 	mtx_unlock(&sc->sim_lock);
196 
197 	/*
198 	 * Create SIM for bus 1 and register, also create path
199 	 */
200 	sc->sim_1 = cam_sim_alloc(mrsas_action, mrsas_cam_poll, "mrsas", sc,
201 	    device_get_unit(sc->mrsas_dev), &sc->sim_lock, mrsas_cam_depth,
202 	    mrsas_cam_depth, devq);
203 	if (sc->sim_1 == NULL) {
204 		cam_simq_free(devq);
205 		device_printf(sc->mrsas_dev, "Cannot register SIM\n");
206 		return (ENXIO);
207 	}
208 	mtx_lock(&sc->sim_lock);
209 	if (xpt_bus_register(sc->sim_1, sc->mrsas_dev, 1) != CAM_SUCCESS) {
210 		cam_sim_free(sc->sim_1, TRUE);	/* passing true frees the devq */
211 		mtx_unlock(&sc->sim_lock);
212 		return (ENXIO);
213 	}
214 	if (xpt_create_path(&sc->path_1, NULL, cam_sim_path(sc->sim_1),
215 	    CAM_TARGET_WILDCARD,
216 	    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
217 		xpt_bus_deregister(cam_sim_path(sc->sim_1));
218 		cam_sim_free(sc->sim_1, TRUE);
219 		mtx_unlock(&sc->sim_lock);
220 		return (ENXIO);
221 	}
222 	mtx_unlock(&sc->sim_lock);
223 
224 #if (__FreeBSD_version <= 704000)
225 	if (mrsas_bus_scan(sc)) {
226 		device_printf(sc->mrsas_dev, "Error in bus scan.\n");
227 		return (1);
228 	}
229 #endif
230 	return (0);
231 }
232 
233 /*
234  * mrsas_cam_detach:	De-allocates and teardown CAM
235  * input:				Adapter instance soft state
236  *
237  * De-registers and frees the paths and SIMs.
238  */
239 void
240 mrsas_cam_detach(struct mrsas_softc *sc)
241 {
242 	if (sc->ev_tq != NULL)
243 		taskqueue_free(sc->ev_tq);
244 	mtx_lock(&sc->sim_lock);
245 	if (sc->path_0)
246 		xpt_free_path(sc->path_0);
247 	if (sc->sim_0) {
248 		xpt_bus_deregister(cam_sim_path(sc->sim_0));
249 		cam_sim_free(sc->sim_0, FALSE);
250 	}
251 	if (sc->path_1)
252 		xpt_free_path(sc->path_1);
253 	if (sc->sim_1) {
254 		xpt_bus_deregister(cam_sim_path(sc->sim_1));
255 		cam_sim_free(sc->sim_1, TRUE);
256 	}
257 	mtx_unlock(&sc->sim_lock);
258 }
259 
260 /*
261  * mrsas_action:	SIM callback entry point
262  * input:			pointer to SIM pointer to CAM Control Block
263  *
264  * This function processes CAM subsystem requests. The type of request is stored
265  * in ccb->ccb_h.func_code.  The preprocessor #ifdef is necessary because
266  * ccb->cpi.maxio is not supported for FreeBSD version 7.4 or earlier.
267  */
268 static void
269 mrsas_action(struct cam_sim *sim, union ccb *ccb)
270 {
271 	struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
272 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
273 	u_int32_t device_id;
274 
275 	/*
276      * Check if the system going down
277      * or the adapter is in unrecoverable critical error
278      */
279     if (sc->remove_in_progress ||
280         (sc->adprecovery == MRSAS_HW_CRITICAL_ERROR)) {
281         ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
282         xpt_done(ccb);
283         return;
284     }
285 
286 	switch (ccb->ccb_h.func_code) {
287 	case XPT_SCSI_IO:
288 		{
289 			device_id = ccb_h->target_id;
290 
291 			/*
292 			 * bus 0 is LD, bus 1 is for system-PD
293 			 */
294 			if (cam_sim_bus(sim) == 1 &&
295 			    sc->pd_list[device_id].driveState != MR_PD_STATE_SYSTEM) {
296 				ccb->ccb_h.status |= CAM_DEV_NOT_THERE;
297 				xpt_done(ccb);
298 			} else {
299 				if (mrsas_startio(sc, sim, ccb)) {
300 					ccb->ccb_h.status |= CAM_REQ_INVALID;
301 					xpt_done(ccb);
302 				}
303 			}
304 			break;
305 		}
306 	case XPT_ABORT:
307 		{
308 			ccb->ccb_h.status = CAM_UA_ABORT;
309 			xpt_done(ccb);
310 			break;
311 		}
312 	case XPT_RESET_BUS:
313 		{
314 			xpt_done(ccb);
315 			break;
316 		}
317 	case XPT_GET_TRAN_SETTINGS:
318 		{
319 			ccb->cts.protocol = PROTO_SCSI;
320 			ccb->cts.protocol_version = SCSI_REV_2;
321 			ccb->cts.transport = XPORT_SPI;
322 			ccb->cts.transport_version = 2;
323 			ccb->cts.xport_specific.spi.valid = CTS_SPI_VALID_DISC;
324 			ccb->cts.xport_specific.spi.flags = CTS_SPI_FLAGS_DISC_ENB;
325 			ccb->cts.proto_specific.scsi.valid = CTS_SCSI_VALID_TQ;
326 			ccb->cts.proto_specific.scsi.flags = CTS_SCSI_FLAGS_TAG_ENB;
327 			ccb->ccb_h.status = CAM_REQ_CMP;
328 			xpt_done(ccb);
329 			break;
330 		}
331 	case XPT_SET_TRAN_SETTINGS:
332 		{
333 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
334 			xpt_done(ccb);
335 			break;
336 		}
337 	case XPT_CALC_GEOMETRY:
338 		{
339 			cam_calc_geometry(&ccb->ccg, 1);
340 			xpt_done(ccb);
341 			break;
342 		}
343 	case XPT_PATH_INQ:
344 		{
345 			ccb->cpi.version_num = 1;
346 			ccb->cpi.hba_inquiry = 0;
347 			ccb->cpi.target_sprt = 0;
348 #if (__FreeBSD_version >= 902001)
349 			ccb->cpi.hba_misc = PIM_UNMAPPED;
350 #else
351 			ccb->cpi.hba_misc = 0;
352 #endif
353 			ccb->cpi.hba_eng_cnt = 0;
354 			ccb->cpi.max_lun = MRSAS_SCSI_MAX_LUNS;
355 			ccb->cpi.unit_number = cam_sim_unit(sim);
356 			ccb->cpi.bus_id = cam_sim_bus(sim);
357 			ccb->cpi.initiator_id = MRSAS_SCSI_INITIATOR_ID;
358 			ccb->cpi.base_transfer_speed = 150000;
359 			strlcpy(ccb->cpi.sim_vid, "FreeBSD", SIM_IDLEN);
360 			strlcpy(ccb->cpi.hba_vid, "AVAGO", HBA_IDLEN);
361 			strlcpy(ccb->cpi.dev_name, cam_sim_name(sim), DEV_IDLEN);
362 			ccb->cpi.transport = XPORT_SPI;
363 			ccb->cpi.transport_version = 2;
364 			ccb->cpi.protocol = PROTO_SCSI;
365 			ccb->cpi.protocol_version = SCSI_REV_2;
366 			if (ccb->cpi.bus_id == 0)
367 				ccb->cpi.max_target = MRSAS_MAX_PD - 1;
368 			else
369 				ccb->cpi.max_target = MRSAS_MAX_LD_IDS - 1;
370 #if (__FreeBSD_version > 704000)
371 			ccb->cpi.maxio = sc->max_num_sge * MRSAS_PAGE_SIZE;
372 #endif
373 			ccb->ccb_h.status = CAM_REQ_CMP;
374 			xpt_done(ccb);
375 			break;
376 		}
377 	default:
378 		{
379 			ccb->ccb_h.status = CAM_REQ_INVALID;
380 			xpt_done(ccb);
381 			break;
382 		}
383 	}
384 }
385 
386 /*
387  * mrsas_scsiio_timeout:	Callback function for IO timed out
388  * input:					mpt command context
389  *
390  * This function will execute after timeout value provided by ccb header from
391  * CAM layer, if timer expires. Driver will run timer for all DCDM and LDIO
392  * coming from CAM layer. This function is callback function for IO timeout
393  * and it runs in no-sleep context. Set do_timedout_reset in Adapter context
394  * so that it will execute OCR/Kill adpter from ocr_thread context.
395  */
396 static void
397 mrsas_scsiio_timeout(void *data)
398 {
399 	struct mrsas_mpt_cmd *cmd;
400 	struct mrsas_softc *sc;
401 	u_int32_t target_id;
402 
403 	if (!data)
404 		return;
405 
406 	cmd = (struct mrsas_mpt_cmd *)data;
407 	sc = cmd->sc;
408 
409 	if (cmd->ccb_ptr == NULL) {
410 		printf("command timeout with NULL ccb\n");
411 		return;
412 	}
413 
414 	/*
415 	 * Below callout is dummy entry so that it will be cancelled from
416 	 * mrsas_cmd_done(). Now Controller will go to OCR/Kill Adapter based
417 	 * on OCR enable/disable property of Controller from ocr_thread
418 	 * context.
419 	 */
420 #if (__FreeBSD_version >= 1000510)
421 	callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
422 	    mrsas_scsiio_timeout, cmd, 0);
423 #else
424 	callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
425 	    mrsas_scsiio_timeout, cmd);
426 #endif
427 
428 	if (cmd->ccb_ptr->cpi.bus_id == 0)
429 		target_id = cmd->ccb_ptr->ccb_h.target_id;
430 	else
431 		target_id = (cmd->ccb_ptr->ccb_h.target_id + (MRSAS_MAX_PD - 1));
432 
433 	/* Save the cmd to be processed for TM, if it is not there in the array */
434 	if (sc->target_reset_pool[target_id] == NULL) {
435 		sc->target_reset_pool[target_id] = cmd;
436 		mrsas_atomic_inc(&sc->target_reset_outstanding);
437 	}
438 
439 	return;
440 }
441 
442 /*
443  * mrsas_startio:	SCSI IO entry point
444  * input:			Adapter instance soft state
445  * 					pointer to CAM Control Block
446  *
447  * This function is the SCSI IO entry point and it initiates IO processing. It
448  * copies the IO and depending if the IO is read/write or inquiry, it would
449  * call mrsas_build_ldio() or mrsas_build_dcdb(), respectively.  It returns 0
450  * if the command is sent to firmware successfully, otherwise it returns 1.
451  */
452 static int32_t
453 mrsas_startio(struct mrsas_softc *sc, struct cam_sim *sim,
454     union ccb *ccb)
455 {
456 	struct mrsas_mpt_cmd *cmd;
457 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
458 	struct ccb_scsiio *csio = &(ccb->csio);
459 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
460 	u_int8_t cmd_type;
461 
462 	if ((csio->cdb_io.cdb_bytes[0]) == SYNCHRONIZE_CACHE &&
463 		(!sc->fw_sync_cache_support)) {
464 		ccb->ccb_h.status = CAM_REQ_CMP;
465 		xpt_done(ccb);
466 		return (0);
467 	}
468 	ccb_h->status |= CAM_SIM_QUEUED;
469 	cmd = mrsas_get_mpt_cmd(sc);
470 
471 	if (!cmd) {
472 		ccb_h->status |= CAM_REQUEUE_REQ;
473 		xpt_done(ccb);
474 		return (0);
475 	}
476 	if ((ccb_h->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
477 		if (ccb_h->flags & CAM_DIR_IN)
478 			cmd->flags |= MRSAS_DIR_IN;
479 		if (ccb_h->flags & CAM_DIR_OUT)
480 			cmd->flags |= MRSAS_DIR_OUT;
481 	} else
482 		cmd->flags = MRSAS_DIR_NONE;	/* no data */
483 
484 /* For FreeBSD 9.2 and higher */
485 #if (__FreeBSD_version >= 902001)
486 	/*
487 	 * XXX We don't yet support physical addresses here.
488 	 */
489 	switch ((ccb->ccb_h.flags & CAM_DATA_MASK)) {
490 	case CAM_DATA_PADDR:
491 	case CAM_DATA_SG_PADDR:
492 		device_printf(sc->mrsas_dev, "%s: physical addresses not supported\n",
493 		    __func__);
494 		mrsas_release_mpt_cmd(cmd);
495 		ccb_h->status = CAM_REQ_INVALID;
496 		ccb_h->status &= ~CAM_SIM_QUEUED;
497 		goto done;
498 	case CAM_DATA_SG:
499 		device_printf(sc->mrsas_dev, "%s: scatter gather is not supported\n",
500 		    __func__);
501 		mrsas_release_mpt_cmd(cmd);
502 		ccb_h->status = CAM_REQ_INVALID;
503 		goto done;
504 	case CAM_DATA_VADDR:
505 		if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
506 			mrsas_release_mpt_cmd(cmd);
507 			ccb_h->status = CAM_REQ_TOO_BIG;
508 			goto done;
509 		}
510 		cmd->length = csio->dxfer_len;
511 		if (cmd->length)
512 			cmd->data = csio->data_ptr;
513 		break;
514 	case CAM_DATA_BIO:
515 		if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
516 			mrsas_release_mpt_cmd(cmd);
517 			ccb_h->status = CAM_REQ_TOO_BIG;
518 			goto done;
519 		}
520 		cmd->length = csio->dxfer_len;
521 		if (cmd->length)
522 			cmd->data = csio->data_ptr;
523 		break;
524 	default:
525 		ccb->ccb_h.status = CAM_REQ_INVALID;
526 		goto done;
527 	}
528 #else
529 	if (!(ccb_h->flags & CAM_DATA_PHYS)) {	/* Virtual data address */
530 		if (!(ccb_h->flags & CAM_SCATTER_VALID)) {
531 			if (csio->dxfer_len > (sc->max_num_sge * MRSAS_PAGE_SIZE)) {
532 				mrsas_release_mpt_cmd(cmd);
533 				ccb_h->status = CAM_REQ_TOO_BIG;
534 				goto done;
535 			}
536 			cmd->length = csio->dxfer_len;
537 			if (cmd->length)
538 				cmd->data = csio->data_ptr;
539 		} else {
540 			mrsas_release_mpt_cmd(cmd);
541 			ccb_h->status = CAM_REQ_INVALID;
542 			goto done;
543 		}
544 	} else {			/* Data addresses are physical. */
545 		mrsas_release_mpt_cmd(cmd);
546 		ccb_h->status = CAM_REQ_INVALID;
547 		ccb_h->status &= ~CAM_SIM_QUEUED;
548 		goto done;
549 	}
550 #endif
551 	/* save ccb ptr */
552 	cmd->ccb_ptr = ccb;
553 
554 	req_desc = mrsas_get_request_desc(sc, (cmd->index) - 1);
555 	if (!req_desc) {
556 		device_printf(sc->mrsas_dev, "Cannot get request_descriptor.\n");
557 		return (FAIL);
558 	}
559 	memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
560 	cmd->request_desc = req_desc;
561 
562 	if (ccb_h->flags & CAM_CDB_POINTER)
563 		bcopy(csio->cdb_io.cdb_ptr, cmd->io_request->CDB.CDB32, csio->cdb_len);
564 	else
565 		bcopy(csio->cdb_io.cdb_bytes, cmd->io_request->CDB.CDB32, csio->cdb_len);
566 	mtx_lock(&sc->raidmap_lock);
567 
568 	/* Check for IO type READ-WRITE targeted for Logical Volume */
569 	cmd_type = mrsas_find_io_type(sim, ccb);
570 	switch (cmd_type) {
571 	case READ_WRITE_LDIO:
572 		/* Build READ-WRITE IO for Logical Volume  */
573 		if (mrsas_build_ldio_rw(sc, cmd, ccb)) {
574 			device_printf(sc->mrsas_dev, "Build RW LDIO failed.\n");
575 			mtx_unlock(&sc->raidmap_lock);
576 			return (1);
577 		}
578 		break;
579 	case NON_READ_WRITE_LDIO:
580 		/* Build NON READ-WRITE IO for Logical Volume  */
581 		if (mrsas_build_ldio_nonrw(sc, cmd, ccb)) {
582 			device_printf(sc->mrsas_dev, "Build NON-RW LDIO failed.\n");
583 			mtx_unlock(&sc->raidmap_lock);
584 			return (1);
585 		}
586 		break;
587 	case READ_WRITE_SYSPDIO:
588 	case NON_READ_WRITE_SYSPDIO:
589 		if (sc->secure_jbod_support &&
590 		    (cmd_type == NON_READ_WRITE_SYSPDIO)) {
591 			/* Build NON-RW IO for JBOD */
592 			if (mrsas_build_syspdio(sc, cmd, ccb, sim, 0)) {
593 				device_printf(sc->mrsas_dev,
594 				    "Build SYSPDIO failed.\n");
595 				mtx_unlock(&sc->raidmap_lock);
596 				return (1);
597 			}
598 		} else {
599 			/* Build RW IO for JBOD */
600 			if (mrsas_build_syspdio(sc, cmd, ccb, sim, 1)) {
601 				device_printf(sc->mrsas_dev,
602 				    "Build SYSPDIO failed.\n");
603 				mtx_unlock(&sc->raidmap_lock);
604 				return (1);
605 			}
606 		}
607 	}
608 	mtx_unlock(&sc->raidmap_lock);
609 
610 	if (cmd->flags == MRSAS_DIR_IN)	/* from device */
611 		cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_READ;
612 	else if (cmd->flags == MRSAS_DIR_OUT)	/* to device */
613 		cmd->io_request->Control |= MPI2_SCSIIO_CONTROL_WRITE;
614 
615 	cmd->io_request->SGLFlags = MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
616 	cmd->io_request->SGLOffset0 = offsetof(MRSAS_RAID_SCSI_IO_REQUEST, SGL) / 4;
617 	cmd->io_request->SenseBufferLowAddress = cmd->sense_phys_addr;
618 	cmd->io_request->SenseBufferLength = MRSAS_SCSI_SENSE_BUFFERSIZE;
619 
620 	req_desc = cmd->request_desc;
621 	req_desc->SCSIIO.SMID = cmd->index;
622 
623 	/*
624 	 * Start timer for IO timeout. Default timeout value is 90 second.
625 	 */
626 #if (__FreeBSD_version >= 1000510)
627 	callout_reset_sbt(&cmd->cm_callout, SBT_1S * 180, 0,
628 	    mrsas_scsiio_timeout, cmd, 0);
629 #else
630 	callout_reset(&cmd->cm_callout, (180000 * hz) / 1000,
631 	    mrsas_scsiio_timeout, cmd);
632 #endif
633 	mrsas_atomic_inc(&sc->fw_outstanding);
634 
635 	if (mrsas_atomic_read(&sc->fw_outstanding) > sc->io_cmds_highwater)
636 		sc->io_cmds_highwater++;
637 
638 	mrsas_fire_cmd(sc, req_desc->addr.u.low, req_desc->addr.u.high);
639 	return (0);
640 
641 done:
642 	xpt_done(ccb);
643 	return (0);
644 }
645 
646 /*
647  * mrsas_find_io_type:	Determines if IO is read/write or inquiry
648  * input:			pointer to CAM Control Block
649  *
650  * This function determines if the IO is read/write or inquiry.  It returns a 1
651  * if the IO is read/write and 0 if it is inquiry.
652  */
653 int
654 mrsas_find_io_type(struct cam_sim *sim, union ccb *ccb)
655 {
656 	struct ccb_scsiio *csio = &(ccb->csio);
657 
658 	switch (csio->cdb_io.cdb_bytes[0]) {
659 	case READ_10:
660 	case WRITE_10:
661 	case READ_12:
662 	case WRITE_12:
663 	case READ_6:
664 	case WRITE_6:
665 	case READ_16:
666 	case WRITE_16:
667 		return (cam_sim_bus(sim) ?
668 		    READ_WRITE_SYSPDIO : READ_WRITE_LDIO);
669 	default:
670 		return (cam_sim_bus(sim) ?
671 		    NON_READ_WRITE_SYSPDIO : NON_READ_WRITE_LDIO);
672 	}
673 }
674 
675 /*
676  * mrsas_get_mpt_cmd:	Get a cmd from free command pool
677  * input:				Adapter instance soft state
678  *
679  * This function removes an MPT command from the command free list and
680  * initializes it.
681  */
682 struct mrsas_mpt_cmd *
683 mrsas_get_mpt_cmd(struct mrsas_softc *sc)
684 {
685 	struct mrsas_mpt_cmd *cmd = NULL;
686 
687 	mtx_lock(&sc->mpt_cmd_pool_lock);
688 	if (!TAILQ_EMPTY(&sc->mrsas_mpt_cmd_list_head)) {
689 		cmd = TAILQ_FIRST(&sc->mrsas_mpt_cmd_list_head);
690 		TAILQ_REMOVE(&sc->mrsas_mpt_cmd_list_head, cmd, next);
691 	} else {
692 		goto out;
693 	}
694 
695 	memset((uint8_t *)cmd->io_request, 0, MRSAS_MPI2_RAID_DEFAULT_IO_FRAME_SIZE);
696 	cmd->data = NULL;
697 	cmd->length = 0;
698 	cmd->flags = 0;
699 	cmd->error_code = 0;
700 	cmd->load_balance = 0;
701 	cmd->ccb_ptr = NULL;
702 
703 out:
704 	mtx_unlock(&sc->mpt_cmd_pool_lock);
705 	return cmd;
706 }
707 
708 /*
709  * mrsas_release_mpt_cmd:	Return a cmd to free command pool
710  * input:					Command packet for return to free command pool
711  *
712  * This function returns an MPT command to the free command list.
713  */
714 void
715 mrsas_release_mpt_cmd(struct mrsas_mpt_cmd *cmd)
716 {
717 	struct mrsas_softc *sc = cmd->sc;
718 
719 	mtx_lock(&sc->mpt_cmd_pool_lock);
720 	cmd->sync_cmd_idx = (u_int32_t)MRSAS_ULONG_MAX;
721 	TAILQ_INSERT_HEAD(&(sc->mrsas_mpt_cmd_list_head), cmd, next);
722 	mtx_unlock(&sc->mpt_cmd_pool_lock);
723 
724 	return;
725 }
726 
727 /*
728  * mrsas_get_request_desc:	Get request descriptor from array
729  * input:					Adapter instance soft state
730  * 							SMID index
731  *
732  * This function returns a pointer to the request descriptor.
733  */
734 MRSAS_REQUEST_DESCRIPTOR_UNION *
735 mrsas_get_request_desc(struct mrsas_softc *sc, u_int16_t index)
736 {
737 	u_int8_t *p;
738 
739 	if (index >= sc->max_fw_cmds) {
740 		device_printf(sc->mrsas_dev, "Invalid SMID (0x%x)request for desc\n", index);
741 		return NULL;
742 	}
743 	p = sc->req_desc + sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION) * index;
744 
745 	return (MRSAS_REQUEST_DESCRIPTOR_UNION *) p;
746 }
747 
748 /*
749  * mrsas_build_ldio_rw:	Builds an LDIO command
750  * input:				Adapter instance soft state
751  * 						Pointer to command packet
752  * 						Pointer to CCB
753  *
754  * This function builds the LDIO command packet.  It returns 0 if the command is
755  * built successfully, otherwise it returns a 1.
756  */
757 int
758 mrsas_build_ldio_rw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
759     union ccb *ccb)
760 {
761 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
762 	struct ccb_scsiio *csio = &(ccb->csio);
763 	u_int32_t device_id;
764 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
765 
766 	device_id = ccb_h->target_id;
767 
768 	io_request = cmd->io_request;
769 	io_request->RaidContext.VirtualDiskTgtId = device_id;
770 	io_request->RaidContext.status = 0;
771 	io_request->RaidContext.exStatus = 0;
772 
773 	/* just the cdb len, other flags zero, and ORed-in later for FP */
774 	io_request->IoFlags = csio->cdb_len;
775 
776 	if (mrsas_setup_io(sc, cmd, ccb, device_id, io_request) != SUCCESS)
777 		device_printf(sc->mrsas_dev, "Build ldio or fpio error\n");
778 
779 	io_request->DataLength = cmd->length;
780 
781 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
782 		if (cmd->sge_count > sc->max_num_sge) {
783 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
784 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
785 			return (FAIL);
786 		}
787 		/*
788 		 * numSGE store lower 8 bit of sge_count. numSGEExt store
789 		 * higher 8 bit of sge_count
790 		 */
791 		io_request->RaidContext.numSGE = cmd->sge_count;
792 		io_request->RaidContext.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
793 
794 	} else {
795 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
796 		return (FAIL);
797 	}
798 	return (0);
799 }
800 
801 /*
802  * mrsas_setup_io:	Set up data including Fast Path I/O
803  * input:			Adapter instance soft state
804  * 					Pointer to command packet
805  * 					Pointer to CCB
806  *
807  * This function builds the DCDB inquiry command.  It returns 0 if the command
808  * is built successfully, otherwise it returns a 1.
809  */
810 int
811 mrsas_setup_io(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
812     union ccb *ccb, u_int32_t device_id,
813     MRSAS_RAID_SCSI_IO_REQUEST * io_request)
814 {
815 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
816 	struct ccb_scsiio *csio = &(ccb->csio);
817 	struct IO_REQUEST_INFO io_info;
818 	MR_DRV_RAID_MAP_ALL *map_ptr;
819 	MR_LD_RAID *raid;
820 	u_int8_t fp_possible;
821 	u_int32_t start_lba_hi, start_lba_lo, ld_block_size, ld;
822 	u_int32_t datalength = 0;
823 
824 	start_lba_lo = 0;
825 	start_lba_hi = 0;
826 	fp_possible = 0;
827 
828 	/*
829 	 * READ_6 (0x08) or WRITE_6 (0x0A) cdb
830 	 */
831 	if (csio->cdb_len == 6) {
832 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[4];
833 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[1] << 16) |
834 		    ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 8) |
835 		    (u_int32_t)csio->cdb_io.cdb_bytes[3];
836 		start_lba_lo &= 0x1FFFFF;
837 	}
838 	/*
839 	 * READ_10 (0x28) or WRITE_6 (0x2A) cdb
840 	 */
841 	else if (csio->cdb_len == 10) {
842 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[8] |
843 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 8);
844 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
845 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
846 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
847 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
848 	}
849 	/*
850 	 * READ_12 (0xA8) or WRITE_12 (0xAA) cdb
851 	 */
852 	else if (csio->cdb_len == 12) {
853 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[6] << 24 |
854 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
855 		    ((u_int32_t)csio->cdb_io.cdb_bytes[8] << 8) |
856 		    ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
857 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
858 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
859 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
860 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
861 	}
862 	/*
863 	 * READ_16 (0x88) or WRITE_16 (0xx8A) cdb
864 	 */
865 	else if (csio->cdb_len == 16) {
866 		datalength = (u_int32_t)csio->cdb_io.cdb_bytes[10] << 24 |
867 		    ((u_int32_t)csio->cdb_io.cdb_bytes[11] << 16) |
868 		    ((u_int32_t)csio->cdb_io.cdb_bytes[12] << 8) |
869 		    ((u_int32_t)csio->cdb_io.cdb_bytes[13]);
870 		start_lba_lo = ((u_int32_t)csio->cdb_io.cdb_bytes[6] << 24) |
871 		    ((u_int32_t)csio->cdb_io.cdb_bytes[7] << 16) |
872 		    (u_int32_t)csio->cdb_io.cdb_bytes[8] << 8 |
873 		    ((u_int32_t)csio->cdb_io.cdb_bytes[9]);
874 		start_lba_hi = ((u_int32_t)csio->cdb_io.cdb_bytes[2] << 24) |
875 		    ((u_int32_t)csio->cdb_io.cdb_bytes[3] << 16) |
876 		    (u_int32_t)csio->cdb_io.cdb_bytes[4] << 8 |
877 		    ((u_int32_t)csio->cdb_io.cdb_bytes[5]);
878 	}
879 	memset(&io_info, 0, sizeof(struct IO_REQUEST_INFO));
880 	io_info.ldStartBlock = ((u_int64_t)start_lba_hi << 32) | start_lba_lo;
881 	io_info.numBlocks = datalength;
882 	io_info.ldTgtId = device_id;
883 
884 	switch (ccb_h->flags & CAM_DIR_MASK) {
885 	case CAM_DIR_IN:
886 		io_info.isRead = 1;
887 		break;
888 	case CAM_DIR_OUT:
889 		io_info.isRead = 0;
890 		break;
891 	case CAM_DIR_NONE:
892 	default:
893 		mrsas_dprint(sc, MRSAS_TRACE, "From %s : DMA Flag is %d \n", __func__, ccb_h->flags & CAM_DIR_MASK);
894 		break;
895 	}
896 
897 	map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
898 	ld_block_size = MR_LdBlockSizeGet(device_id, map_ptr, sc);
899 
900 	ld = MR_TargetIdToLdGet(device_id, map_ptr);
901 	if ((ld >= MAX_LOGICAL_DRIVES_EXT) || (!sc->fast_path_io)) {
902 		io_request->RaidContext.regLockFlags = 0;
903 		fp_possible = 0;
904 	} else {
905 		if (MR_BuildRaidContext(sc, &io_info, &io_request->RaidContext, map_ptr))
906 			fp_possible = io_info.fpOkForIo;
907 	}
908 
909 	raid = MR_LdRaidGet(ld, map_ptr);
910 	/* Store the TM capability value in cmd */
911 	cmd->tmCapable = raid->capability.tmCapable;
912 
913 	cmd->request_desc->SCSIIO.MSIxIndex =
914 	    sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
915 
916 
917 	if (fp_possible) {
918 		mrsas_set_pd_lba(io_request, csio->cdb_len, &io_info, ccb, map_ptr,
919 		    start_lba_lo, ld_block_size);
920 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
921 		cmd->request_desc->SCSIIO.RequestFlags =
922 		    (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
923 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
924 		if (sc->mrsas_gen3_ctrl) {
925 			if (io_request->RaidContext.regLockFlags == REGION_TYPE_UNUSED)
926 				cmd->request_desc->SCSIIO.RequestFlags =
927 				    (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
928 				    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
929 			io_request->RaidContext.Type = MPI2_TYPE_CUDA;
930 			io_request->RaidContext.nseg = 0x1;
931 			io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
932 			io_request->RaidContext.regLockFlags |=
933 			    (MR_RL_FLAGS_GRANT_DESTINATION_CUDA |
934 			    MR_RL_FLAGS_SEQ_NUM_ENABLE);
935 		}
936 		if ((sc->load_balance_info[device_id].loadBalanceFlag) &&
937 		    (io_info.isRead)) {
938 			io_info.devHandle =
939 			    mrsas_get_updated_dev_handle(sc,
940 			    &sc->load_balance_info[device_id], &io_info);
941 			cmd->load_balance = MRSAS_LOAD_BALANCE_FLAG;
942 			cmd->pd_r1_lb = io_info.pd_after_lb;
943 		} else
944 			cmd->load_balance = 0;
945 		cmd->request_desc->SCSIIO.DevHandle = io_info.devHandle;
946 		io_request->DevHandle = io_info.devHandle;
947 	} else {
948 		/* Not FP IO */
949 		io_request->RaidContext.timeoutValue = map_ptr->raidMap.fpPdIoTimeoutSec;
950 		cmd->request_desc->SCSIIO.RequestFlags =
951 		    (MRSAS_REQ_DESCRIPT_FLAGS_LD_IO <<
952 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
953 		if (sc->mrsas_gen3_ctrl) {
954 			if (io_request->RaidContext.regLockFlags == REGION_TYPE_UNUSED)
955 				cmd->request_desc->SCSIIO.RequestFlags =
956 				    (MRSAS_REQ_DESCRIPT_FLAGS_NO_LOCK <<
957 				    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
958 			io_request->RaidContext.Type = MPI2_TYPE_CUDA;
959 			io_request->RaidContext.regLockFlags |=
960 			    (MR_RL_FLAGS_GRANT_DESTINATION_CPU0 |
961 			    MR_RL_FLAGS_SEQ_NUM_ENABLE);
962 			io_request->RaidContext.nseg = 0x1;
963 		}
964 		io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
965 		io_request->DevHandle = device_id;
966 	}
967 	return (0);
968 }
969 
970 /*
971  * mrsas_build_ldio_nonrw:	Builds an LDIO command
972  * input:				Adapter instance soft state
973  * 						Pointer to command packet
974  * 						Pointer to CCB
975  *
976  * This function builds the LDIO command packet.  It returns 0 if the command is
977  * built successfully, otherwise it returns a 1.
978  */
979 int
980 mrsas_build_ldio_nonrw(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
981     union ccb *ccb)
982 {
983 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
984 	u_int32_t device_id, ld;
985 	MR_DRV_RAID_MAP_ALL *map_ptr;
986 	MR_LD_RAID *raid;
987 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
988 
989 	io_request = cmd->io_request;
990 	device_id = ccb_h->target_id;
991 
992 	map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
993 	ld = MR_TargetIdToLdGet(device_id, map_ptr);
994 	raid = MR_LdRaidGet(ld, map_ptr);
995 	/* Store the TM capability value in cmd */
996 	cmd->tmCapable = raid->capability.tmCapable;
997 
998 	/* FW path for LD Non-RW (SCSI management commands) */
999 	io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1000 	io_request->DevHandle = device_id;
1001 	cmd->request_desc->SCSIIO.RequestFlags =
1002 	    (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1003 	    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1004 
1005 	io_request->RaidContext.VirtualDiskTgtId = device_id;
1006 	io_request->LUN[1] = ccb_h->target_lun & 0xF;
1007 	io_request->DataLength = cmd->length;
1008 
1009 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1010 		if (cmd->sge_count > sc->max_num_sge) {
1011 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1012 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1013 			return (1);
1014 		}
1015 		/*
1016 		 * numSGE store lower 8 bit of sge_count. numSGEExt store
1017 		 * higher 8 bit of sge_count
1018 		 */
1019 		io_request->RaidContext.numSGE = cmd->sge_count;
1020 		io_request->RaidContext.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1021 	} else {
1022 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1023 		return (1);
1024 	}
1025 	return (0);
1026 }
1027 
1028 /*
1029  * mrsas_build_syspdio:	Builds an DCDB command
1030  * input:				Adapter instance soft state
1031  * 						Pointer to command packet
1032  * 						Pointer to CCB
1033  *
1034  * This function builds the DCDB inquiry command.  It returns 0 if the command
1035  * is built successfully, otherwise it returns a 1.
1036  */
1037 int
1038 mrsas_build_syspdio(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd,
1039     union ccb *ccb, struct cam_sim *sim, u_int8_t fp_possible)
1040 {
1041 	struct ccb_hdr *ccb_h = &(ccb->ccb_h);
1042 	u_int32_t device_id;
1043 	MR_DRV_RAID_MAP_ALL *local_map_ptr;
1044 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1045 	struct MR_PD_CFG_SEQ_NUM_SYNC *pd_sync;
1046 
1047 	io_request = cmd->io_request;
1048 	device_id = ccb_h->target_id;
1049 	local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1050 	io_request->RaidContext.RAIDFlags = MR_RAID_FLAGS_IO_SUB_TYPE_SYSTEM_PD
1051 	    << MR_RAID_CTX_RAID_FLAGS_IO_SUB_TYPE_SHIFT;
1052 	io_request->RaidContext.regLockFlags = 0;
1053 	io_request->RaidContext.regLockRowLBA = 0;
1054 	io_request->RaidContext.regLockLength = 0;
1055 
1056 	/* If FW supports PD sequence number */
1057 	if (sc->use_seqnum_jbod_fp &&
1058 	    sc->pd_list[device_id].driveType == 0x00) {
1059 		//printf("Using Drv seq num\n");
1060 		pd_sync = (void *)sc->jbodmap_mem[(sc->pd_seq_map_id - 1) & 1];
1061 		cmd->tmCapable = pd_sync->seq[device_id].capability.tmCapable;
1062 		io_request->RaidContext.VirtualDiskTgtId = device_id + 255;
1063 		io_request->RaidContext.configSeqNum = pd_sync->seq[device_id].seqNum;
1064 		io_request->DevHandle = pd_sync->seq[device_id].devHandle;
1065 		io_request->RaidContext.regLockFlags |=
1066 		    (MR_RL_FLAGS_SEQ_NUM_ENABLE | MR_RL_FLAGS_GRANT_DESTINATION_CUDA);
1067 		io_request->RaidContext.Type = MPI2_TYPE_CUDA;
1068 		io_request->RaidContext.nseg = 0x1;
1069 	} else if (sc->fast_path_io) {
1070 		//printf("Using LD RAID map\n");
1071 		io_request->RaidContext.VirtualDiskTgtId = device_id;
1072 		io_request->RaidContext.configSeqNum = 0;
1073 		local_map_ptr = sc->ld_drv_map[(sc->map_id & 1)];
1074 		io_request->DevHandle =
1075 		    local_map_ptr->raidMap.devHndlInfo[device_id].curDevHdl;
1076 	} else {
1077 		//printf("Using FW PATH\n");
1078 		/* Want to send all IO via FW path */
1079 		io_request->RaidContext.VirtualDiskTgtId = device_id;
1080 		io_request->RaidContext.configSeqNum = 0;
1081 		io_request->DevHandle = 0xFFFF;
1082 	}
1083 
1084 	cmd->request_desc->SCSIIO.DevHandle = io_request->DevHandle;
1085 	cmd->request_desc->SCSIIO.MSIxIndex =
1086 	    sc->msix_vectors ? smp_processor_id() % sc->msix_vectors : 0;
1087 
1088 	if (!fp_possible) {
1089 		/* system pd firmware path */
1090 		io_request->Function = MRSAS_MPI2_FUNCTION_LD_IO_REQUEST;
1091 		cmd->request_desc->SCSIIO.RequestFlags =
1092 		    (MPI2_REQ_DESCRIPT_FLAGS_SCSI_IO <<
1093 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1094 		io_request->RaidContext.timeoutValue =
1095 		    local_map_ptr->raidMap.fpPdIoTimeoutSec;
1096 		io_request->RaidContext.VirtualDiskTgtId = device_id;
1097 	} else {
1098 		/* system pd fast path */
1099 		io_request->Function = MPI2_FUNCTION_SCSI_IO_REQUEST;
1100 		io_request->RaidContext.timeoutValue = local_map_ptr->raidMap.fpPdIoTimeoutSec;
1101 
1102 		/*
1103 		 * NOTE - For system pd RW cmds only IoFlags will be FAST_PATH
1104 		 * Because the NON RW cmds will now go via FW Queue
1105 		 * and not the Exception queue
1106 		 */
1107 		io_request->IoFlags |= MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH;
1108 
1109 		cmd->request_desc->SCSIIO.RequestFlags =
1110 		    (MPI2_REQ_DESCRIPT_FLAGS_FP_IO <<
1111 		    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1112 	}
1113 
1114 	io_request->LUN[1] = ccb_h->target_lun & 0xF;
1115 	io_request->DataLength = cmd->length;
1116 
1117 	if (mrsas_map_request(sc, cmd, ccb) == SUCCESS) {
1118 		if (cmd->sge_count > sc->max_num_sge) {
1119 			device_printf(sc->mrsas_dev, "Error: sge_count (0x%x) exceeds"
1120 			    "max (0x%x) allowed\n", cmd->sge_count, sc->max_num_sge);
1121 			return (1);
1122 		}
1123 		/*
1124 		 * numSGE store lower 8 bit of sge_count. numSGEExt store
1125 		 * higher 8 bit of sge_count
1126 		 */
1127 		io_request->RaidContext.numSGE = cmd->sge_count;
1128 		io_request->RaidContext.numSGEExt = (uint8_t)(cmd->sge_count >> 8);
1129 	} else {
1130 		device_printf(sc->mrsas_dev, "Data map/load failed.\n");
1131 		return (1);
1132 	}
1133 	return (0);
1134 }
1135 
1136 /*
1137  * mrsas_map_request:	Map and load data
1138  * input:				Adapter instance soft state
1139  * 						Pointer to command packet
1140  *
1141  * For data from OS, map and load the data buffer into bus space.  The SG list
1142  * is built in the callback.  If the  bus dmamap load is not successful,
1143  * cmd->error_code will contain the  error code and a 1 is returned.
1144  */
1145 int
1146 mrsas_map_request(struct mrsas_softc *sc,
1147     struct mrsas_mpt_cmd *cmd, union ccb *ccb)
1148 {
1149 	u_int32_t retcode = 0;
1150 	struct cam_sim *sim;
1151 
1152 	sim = xpt_path_sim(cmd->ccb_ptr->ccb_h.path);
1153 
1154 	if (cmd->data != NULL) {
1155 		/* Map data buffer into bus space */
1156 		mtx_lock(&sc->io_lock);
1157 #if (__FreeBSD_version >= 902001)
1158 		retcode = bus_dmamap_load_ccb(sc->data_tag, cmd->data_dmamap, ccb,
1159 		    mrsas_data_load_cb, cmd, 0);
1160 #else
1161 		retcode = bus_dmamap_load(sc->data_tag, cmd->data_dmamap, cmd->data,
1162 		    cmd->length, mrsas_data_load_cb, cmd, BUS_DMA_NOWAIT);
1163 #endif
1164 		mtx_unlock(&sc->io_lock);
1165 		if (retcode)
1166 			device_printf(sc->mrsas_dev, "bus_dmamap_load(): retcode = %d\n", retcode);
1167 		if (retcode == EINPROGRESS) {
1168 			device_printf(sc->mrsas_dev, "request load in progress\n");
1169 			mrsas_freeze_simq(cmd, sim);
1170 		}
1171 	}
1172 	if (cmd->error_code)
1173 		return (1);
1174 	return (retcode);
1175 }
1176 
1177 /*
1178  * mrsas_unmap_request:	Unmap and unload data
1179  * input:				Adapter instance soft state
1180  * 						Pointer to command packet
1181  *
1182  * This function unmaps and unloads data from OS.
1183  */
1184 void
1185 mrsas_unmap_request(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1186 {
1187 	if (cmd->data != NULL) {
1188 		if (cmd->flags & MRSAS_DIR_IN)
1189 			bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTREAD);
1190 		if (cmd->flags & MRSAS_DIR_OUT)
1191 			bus_dmamap_sync(sc->data_tag, cmd->data_dmamap, BUS_DMASYNC_POSTWRITE);
1192 		mtx_lock(&sc->io_lock);
1193 		bus_dmamap_unload(sc->data_tag, cmd->data_dmamap);
1194 		mtx_unlock(&sc->io_lock);
1195 	}
1196 }
1197 
1198 /*
1199  * mrsas_data_load_cb:	Callback entry point
1200  * input:				Pointer to command packet as argument
1201  * 						Pointer to segment
1202  * 						Number of segments Error
1203  *
1204  * This is the callback function of the bus dma map load.  It builds the SG
1205  * list.
1206  */
1207 static void
1208 mrsas_data_load_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1209 {
1210 	struct mrsas_mpt_cmd *cmd = (struct mrsas_mpt_cmd *)arg;
1211 	struct mrsas_softc *sc = cmd->sc;
1212 	MRSAS_RAID_SCSI_IO_REQUEST *io_request;
1213 	pMpi25IeeeSgeChain64_t sgl_ptr;
1214 	int i = 0, sg_processed = 0;
1215 
1216 	if (error) {
1217 		cmd->error_code = error;
1218 		device_printf(sc->mrsas_dev, "mrsas_data_load_cb: error=%d\n", error);
1219 		if (error == EFBIG) {
1220 			cmd->ccb_ptr->ccb_h.status = CAM_REQ_TOO_BIG;
1221 			return;
1222 		}
1223 	}
1224 	if (cmd->flags & MRSAS_DIR_IN)
1225 		bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1226 		    BUS_DMASYNC_PREREAD);
1227 	if (cmd->flags & MRSAS_DIR_OUT)
1228 		bus_dmamap_sync(cmd->sc->data_tag, cmd->data_dmamap,
1229 		    BUS_DMASYNC_PREWRITE);
1230 	if (nseg > sc->max_num_sge) {
1231 		device_printf(sc->mrsas_dev, "SGE count is too large or 0.\n");
1232 		return;
1233 	}
1234 	io_request = cmd->io_request;
1235 	sgl_ptr = (pMpi25IeeeSgeChain64_t)&io_request->SGL;
1236 
1237 	if (sc->mrsas_gen3_ctrl) {
1238 		pMpi25IeeeSgeChain64_t sgl_ptr_end = sgl_ptr;
1239 
1240 		sgl_ptr_end += sc->max_sge_in_main_msg - 1;
1241 		sgl_ptr_end->Flags = 0;
1242 	}
1243 	if (nseg != 0) {
1244 		for (i = 0; i < nseg; i++) {
1245 			sgl_ptr->Address = segs[i].ds_addr;
1246 			sgl_ptr->Length = segs[i].ds_len;
1247 			sgl_ptr->Flags = 0;
1248 			if (sc->mrsas_gen3_ctrl) {
1249 				if (i == nseg - 1)
1250 					sgl_ptr->Flags = IEEE_SGE_FLAGS_END_OF_LIST;
1251 			}
1252 			sgl_ptr++;
1253 			sg_processed = i + 1;
1254 			if ((sg_processed == (sc->max_sge_in_main_msg - 1)) &&
1255 			    (nseg > sc->max_sge_in_main_msg)) {
1256 				pMpi25IeeeSgeChain64_t sg_chain;
1257 
1258 				if (sc->mrsas_gen3_ctrl) {
1259 					if ((cmd->io_request->IoFlags & MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1260 					    != MPI25_SAS_DEVICE0_FLAGS_ENABLED_FAST_PATH)
1261 						cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1262 					else
1263 						cmd->io_request->ChainOffset = 0;
1264 				} else
1265 					cmd->io_request->ChainOffset = sc->chain_offset_io_request;
1266 				sg_chain = sgl_ptr;
1267 				if (sc->mrsas_gen3_ctrl)
1268 					sg_chain->Flags = IEEE_SGE_FLAGS_CHAIN_ELEMENT;
1269 				else
1270 					sg_chain->Flags = (IEEE_SGE_FLAGS_CHAIN_ELEMENT | MPI2_IEEE_SGE_FLAGS_IOCPLBNTA_ADDR);
1271 				sg_chain->Length = (sizeof(MPI2_SGE_IO_UNION) * (nseg - sg_processed));
1272 				sg_chain->Address = cmd->chain_frame_phys_addr;
1273 				sgl_ptr = (pMpi25IeeeSgeChain64_t)cmd->chain_frame;
1274 			}
1275 		}
1276 	}
1277 	cmd->sge_count = nseg;
1278 }
1279 
1280 /*
1281  * mrsas_freeze_simq:	Freeze SIM queue
1282  * input:				Pointer to command packet
1283  * 						Pointer to SIM
1284  *
1285  * This function freezes the sim queue.
1286  */
1287 static void
1288 mrsas_freeze_simq(struct mrsas_mpt_cmd *cmd, struct cam_sim *sim)
1289 {
1290 	union ccb *ccb = (union ccb *)(cmd->ccb_ptr);
1291 
1292 	xpt_freeze_simq(sim, 1);
1293 	ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
1294 	ccb->ccb_h.status |= CAM_REQUEUE_REQ;
1295 }
1296 
1297 void
1298 mrsas_xpt_freeze(struct mrsas_softc *sc)
1299 {
1300 	xpt_freeze_simq(sc->sim_0, 1);
1301 	xpt_freeze_simq(sc->sim_1, 1);
1302 }
1303 
1304 void
1305 mrsas_xpt_release(struct mrsas_softc *sc)
1306 {
1307 	xpt_release_simq(sc->sim_0, 1);
1308 	xpt_release_simq(sc->sim_1, 1);
1309 }
1310 
1311 /*
1312  * mrsas_cmd_done:	Perform remaining command completion
1313  * input:			Adapter instance soft state  Pointer to command packet
1314  *
1315  * This function calls ummap request and releases the MPT command.
1316  */
1317 void
1318 mrsas_cmd_done(struct mrsas_softc *sc, struct mrsas_mpt_cmd *cmd)
1319 {
1320 	mrsas_unmap_request(sc, cmd);
1321 
1322 	mtx_lock(&sc->sim_lock);
1323 	callout_stop(&cmd->cm_callout);
1324 	xpt_done(cmd->ccb_ptr);
1325 	cmd->ccb_ptr = NULL;
1326 	mtx_unlock(&sc->sim_lock);
1327 	mrsas_release_mpt_cmd(cmd);
1328 }
1329 
1330 /*
1331  * mrsas_cam_poll:	Polling entry point
1332  * input:			Pointer to SIM
1333  *
1334  * This is currently a stub function.
1335  */
1336 static void
1337 mrsas_cam_poll(struct cam_sim *sim)
1338 {
1339 	int i;
1340 	struct mrsas_softc *sc = (struct mrsas_softc *)cam_sim_softc(sim);
1341 
1342 	if (sc->msix_vectors != 0){
1343 		for (i=0; i<sc->msix_vectors; i++){
1344 			mrsas_complete_cmd(sc, i);
1345 		}
1346 	} else {
1347 		mrsas_complete_cmd(sc, 0);
1348 	}
1349 }
1350 
1351 /*
1352  * mrsas_bus_scan:	Perform bus scan
1353  * input:			Adapter instance soft state
1354  *
1355  * This mrsas_bus_scan function is needed for FreeBSD 7.x.  Also, it should not
1356  * be called in FreeBSD 8.x and later versions, where the bus scan is
1357  * automatic.
1358  */
1359 int
1360 mrsas_bus_scan(struct mrsas_softc *sc)
1361 {
1362 	union ccb *ccb_0;
1363 	union ccb *ccb_1;
1364 
1365 	if ((ccb_0 = xpt_alloc_ccb()) == NULL) {
1366 		return (ENOMEM);
1367 	}
1368 	if ((ccb_1 = xpt_alloc_ccb()) == NULL) {
1369 		xpt_free_ccb(ccb_0);
1370 		return (ENOMEM);
1371 	}
1372 	mtx_lock(&sc->sim_lock);
1373 	if (xpt_create_path(&ccb_0->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_0),
1374 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1375 		xpt_free_ccb(ccb_0);
1376 		xpt_free_ccb(ccb_1);
1377 		mtx_unlock(&sc->sim_lock);
1378 		return (EIO);
1379 	}
1380 	if (xpt_create_path(&ccb_1->ccb_h.path, xpt_periph, cam_sim_path(sc->sim_1),
1381 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1382 		xpt_free_ccb(ccb_0);
1383 		xpt_free_ccb(ccb_1);
1384 		mtx_unlock(&sc->sim_lock);
1385 		return (EIO);
1386 	}
1387 	mtx_unlock(&sc->sim_lock);
1388 	xpt_rescan(ccb_0);
1389 	xpt_rescan(ccb_1);
1390 
1391 	return (0);
1392 }
1393 
1394 /*
1395  * mrsas_bus_scan_sim:	Perform bus scan per SIM
1396  * input:				adapter instance soft state
1397  *
1398  * This function will be called from Event handler on LD creation/deletion,
1399  * JBOD on/off.
1400  */
1401 int
1402 mrsas_bus_scan_sim(struct mrsas_softc *sc, struct cam_sim *sim)
1403 {
1404 	union ccb *ccb;
1405 
1406 	if ((ccb = xpt_alloc_ccb()) == NULL) {
1407 		return (ENOMEM);
1408 	}
1409 	mtx_lock(&sc->sim_lock);
1410 	if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, cam_sim_path(sim),
1411 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
1412 		xpt_free_ccb(ccb);
1413 		mtx_unlock(&sc->sim_lock);
1414 		return (EIO);
1415 	}
1416 	mtx_unlock(&sc->sim_lock);
1417 	xpt_rescan(ccb);
1418 
1419 	return (0);
1420 }
1421 
1422 /*
1423  * mrsas_track_scsiio:  Track IOs for a given target in the mpt_cmd_list
1424  * input:           Adapter instance soft state
1425  *                  Target ID of target
1426  *                  Bus ID of the target
1427  *
1428  * This function checks for any pending IO in the whole mpt_cmd_list pool
1429  * with the bus_id and target_id passed in arguments. If some IO is found
1430  * that means target reset is not successfully completed.
1431  *
1432  * Returns FAIL if IOs pending to the target device, else return SUCCESS
1433  */
1434 static int
1435 mrsas_track_scsiio(struct mrsas_softc *sc, target_id_t tgt_id, u_int32_t bus_id)
1436 {
1437 	int i;
1438 	struct mrsas_mpt_cmd *mpt_cmd = NULL;
1439 
1440 	for (i = 0 ; i < sc->max_fw_cmds; i++) {
1441 		mpt_cmd = sc->mpt_cmd_list[i];
1442 
1443 	/*
1444 	 * Check if the target_id and bus_id is same as the timeout IO
1445 	 */
1446 	if (mpt_cmd->ccb_ptr) {
1447 		/* bus_id = 1 denotes a VD */
1448 		if (bus_id == 1)
1449 			tgt_id = (mpt_cmd->ccb_ptr->ccb_h.target_id - (MRSAS_MAX_PD - 1));
1450 
1451 			if (mpt_cmd->ccb_ptr->cpi.bus_id == bus_id &&
1452 			    mpt_cmd->ccb_ptr->ccb_h.target_id == tgt_id) {
1453 				device_printf(sc->mrsas_dev,
1454 				    "IO commands pending to target id %d\n", tgt_id);
1455 				return FAIL;
1456 			}
1457 		}
1458 	}
1459 
1460 	return SUCCESS;
1461 }
1462 
1463 #if TM_DEBUG
1464 /*
1465  * mrsas_tm_response_code: Prints TM response code received from FW
1466  * input:           Adapter instance soft state
1467  *                  MPI reply returned from firmware
1468  *
1469  * Returns nothing.
1470  */
1471 static void
1472 mrsas_tm_response_code(struct mrsas_softc *sc,
1473 	MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply)
1474 {
1475 	char *desc;
1476 
1477 	switch (mpi_reply->ResponseCode) {
1478 	case MPI2_SCSITASKMGMT_RSP_TM_COMPLETE:
1479 		desc = "task management request completed";
1480 		break;
1481 	case MPI2_SCSITASKMGMT_RSP_INVALID_FRAME:
1482 		desc = "invalid frame";
1483 		break;
1484 	case MPI2_SCSITASKMGMT_RSP_TM_NOT_SUPPORTED:
1485 		desc = "task management request not supported";
1486 		break;
1487 	case MPI2_SCSITASKMGMT_RSP_TM_FAILED:
1488 		desc = "task management request failed";
1489 		break;
1490 	case MPI2_SCSITASKMGMT_RSP_TM_SUCCEEDED:
1491 		desc = "task management request succeeded";
1492 		break;
1493 	case MPI2_SCSITASKMGMT_RSP_TM_INVALID_LUN:
1494 		desc = "invalid lun";
1495 		break;
1496 	case 0xA:
1497 		desc = "overlapped tag attempted";
1498 		break;
1499 	case MPI2_SCSITASKMGMT_RSP_IO_QUEUED_ON_IOC:
1500 		desc = "task queued, however not sent to target";
1501 		break;
1502 	default:
1503 		desc = "unknown";
1504 		break;
1505 	}
1506 	device_printf(sc->mrsas_dev, "response_code(%01x): %s\n",
1507 	    mpi_reply->ResponseCode, desc);
1508 	device_printf(sc->mrsas_dev,
1509 	    "TerminationCount/DevHandle/Function/TaskType/IOCStat/IOCLoginfo\n"
1510 	    "0x%x/0x%x/0x%x/0x%x/0x%x/0x%x\n",
1511 	    mpi_reply->TerminationCount, mpi_reply->DevHandle,
1512 	    mpi_reply->Function, mpi_reply->TaskType,
1513 	    mpi_reply->IOCStatus, mpi_reply->IOCLogInfo);
1514 }
1515 #endif
1516 
1517 /*
1518  * mrsas_issue_tm:  Fires the TM command to FW and waits for completion
1519  * input:           Adapter instance soft state
1520  *                  reqest descriptor compiled by mrsas_reset_targets
1521  *
1522  * Returns FAIL if TM command TIMEDOUT from FW else SUCCESS.
1523  */
1524 static int
1525 mrsas_issue_tm(struct mrsas_softc *sc,
1526 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc)
1527 {
1528 	int sleep_stat;
1529 
1530 	mrsas_fire_cmd(sc, req_desc->addr.u.low, req_desc->addr.u.high);
1531 	sleep_stat = msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "tm_sleep", 50*hz);
1532 
1533 	if (sleep_stat == EWOULDBLOCK) {
1534 		device_printf(sc->mrsas_dev, "tm cmd TIMEDOUT\n");
1535 		return FAIL;
1536 	}
1537 
1538 	return SUCCESS;
1539 }
1540 
1541 /*
1542  * mrsas_reset_targets : Gathers info to fire a target reset command
1543  * input:           Adapter instance soft state
1544  *
1545  * This function compiles data for a target reset command to be fired to the FW
1546  * and then traverse the target_reset_pool to see targets with TIMEDOUT IOs.
1547  *
1548  * Returns SUCCESS or FAIL
1549  */
1550 int mrsas_reset_targets(struct mrsas_softc *sc)
1551 {
1552 	struct mrsas_mpt_cmd *tm_mpt_cmd = NULL;
1553 	struct mrsas_mpt_cmd *tgt_mpt_cmd = NULL;
1554 	MR_TASK_MANAGE_REQUEST *mr_request;
1555 	MPI2_SCSI_TASK_MANAGE_REQUEST *tm_mpi_request;
1556 	MRSAS_REQUEST_DESCRIPTOR_UNION *req_desc;
1557 	int retCode = FAIL, count, i, outstanding;
1558 	u_int32_t MSIxIndex, bus_id;
1559 	target_id_t tgt_id;
1560 #if TM_DEBUG
1561 	MPI2_SCSI_TASK_MANAGE_REPLY *mpi_reply;
1562 #endif
1563 
1564 	outstanding = mrsas_atomic_read(&sc->fw_outstanding);
1565 
1566 	if (!outstanding) {
1567 		device_printf(sc->mrsas_dev, "NO IOs pending...\n");
1568 		mrsas_atomic_set(&sc->target_reset_outstanding, 0);
1569 		retCode = SUCCESS;
1570 		goto return_status;
1571 	} else if (sc->adprecovery != MRSAS_HBA_OPERATIONAL) {
1572 		device_printf(sc->mrsas_dev, "Controller is not operational\n");
1573 		goto return_status;
1574 	} else {
1575 		/* Some more error checks will be added in future */
1576 	}
1577 
1578 	/* Get an mpt frame and an index to fire the TM cmd */
1579 	tm_mpt_cmd = mrsas_get_mpt_cmd(sc);
1580 	if (!tm_mpt_cmd) {
1581 		retCode = FAIL;
1582 		goto return_status;
1583 	}
1584 
1585 	req_desc = mrsas_get_request_desc(sc, (tm_mpt_cmd->index) - 1);
1586 	if (!req_desc) {
1587 		device_printf(sc->mrsas_dev, "Cannot get request_descriptor for tm.\n");
1588 		retCode = FAIL;
1589 		goto release_mpt;
1590 	}
1591 	memset(req_desc, 0, sizeof(MRSAS_REQUEST_DESCRIPTOR_UNION));
1592 
1593 	req_desc->HighPriority.SMID = tm_mpt_cmd->index;
1594 	req_desc->HighPriority.RequestFlags =
1595 	    (MPI2_REQ_DESCRIPT_FLAGS_HIGH_PRIORITY <<
1596 	    MRSAS_REQ_DESCRIPT_FLAGS_TYPE_SHIFT);
1597 	req_desc->HighPriority.MSIxIndex =  0;
1598 	req_desc->HighPriority.LMID = 0;
1599 	req_desc->HighPriority.Reserved1 = 0;
1600 	tm_mpt_cmd->request_desc = req_desc;
1601 
1602 	mr_request = (MR_TASK_MANAGE_REQUEST *) tm_mpt_cmd->io_request;
1603 	memset(mr_request, 0, sizeof(MR_TASK_MANAGE_REQUEST));
1604 
1605 	tm_mpi_request = (MPI2_SCSI_TASK_MANAGE_REQUEST *) &mr_request->TmRequest;
1606 	tm_mpi_request->Function = MPI2_FUNCTION_SCSI_TASK_MGMT;
1607 	tm_mpi_request->TaskType = MPI2_SCSITASKMGMT_TASKTYPE_TARGET_RESET;
1608 	tm_mpi_request->TaskMID = 0; /* smid task */
1609 	tm_mpi_request->LUN[1] = 0;
1610 
1611 	/* Traverse the tm_mpt pool to get valid entries */
1612 	for (i = 0 ; i < MRSAS_MAX_TM_TARGETS; i++) {
1613 		if(!sc->target_reset_pool[i]) {
1614 			continue;
1615 		} else {
1616 			tgt_mpt_cmd = sc->target_reset_pool[i];
1617 		}
1618 
1619 		tgt_id = i;
1620 
1621 		/* See if the target is tm capable or NOT */
1622 		if (!tgt_mpt_cmd->tmCapable) {
1623 			device_printf(sc->mrsas_dev, "Task management NOT SUPPORTED for "
1624 			    "CAM target:%d\n", tgt_id);
1625 
1626 			retCode = FAIL;
1627 			goto release_mpt;
1628 		}
1629 
1630 		tm_mpi_request->DevHandle = tgt_mpt_cmd->io_request->DevHandle;
1631 
1632 		if (i < (MRSAS_MAX_PD - 1)) {
1633 			mr_request->uTmReqReply.tmReqFlags.isTMForPD = 1;
1634 			bus_id = 0;
1635 		} else {
1636 			mr_request->uTmReqReply.tmReqFlags.isTMForLD = 1;
1637 			bus_id = 1;
1638 		}
1639 
1640 		device_printf(sc->mrsas_dev, "TM will be fired for "
1641 		    "CAM target:%d and bus_id %d\n", tgt_id, bus_id);
1642 
1643 		sc->ocr_chan = (void *)&tm_mpt_cmd;
1644 		retCode = mrsas_issue_tm(sc, req_desc);
1645 		if (retCode == FAIL)
1646 			goto release_mpt;
1647 
1648 #if TM_DEBUG
1649 		mpi_reply =
1650 		    (MPI2_SCSI_TASK_MANAGE_REPLY *) &mr_request->uTmReqReply.TMReply;
1651 		mrsas_tm_response_code(sc, mpi_reply);
1652 #endif
1653 		mrsas_atomic_dec(&sc->target_reset_outstanding);
1654 		sc->target_reset_pool[i] = NULL;
1655 
1656 		/* Check for pending cmds in the mpt_cmd_pool with the tgt_id */
1657 		mrsas_disable_intr(sc);
1658 		/* Wait for 1 second to complete parallel ISR calling same
1659 		 * mrsas_complete_cmd()
1660 		 */
1661 		msleep(&sc->ocr_chan, &sc->sim_lock, PRIBIO, "mrsas_reset_wakeup",
1662 		   1 * hz);
1663 		count = sc->msix_vectors > 0 ? sc->msix_vectors : 1;
1664 		mtx_unlock(&sc->sim_lock);
1665 		for (MSIxIndex = 0; MSIxIndex < count; MSIxIndex++)
1666 		    mrsas_complete_cmd(sc, MSIxIndex);
1667 		mtx_lock(&sc->sim_lock);
1668 		retCode = mrsas_track_scsiio(sc, tgt_id, bus_id);
1669 		mrsas_enable_intr(sc);
1670 
1671 		if (retCode == FAIL)
1672 			goto release_mpt;
1673 	}
1674 
1675 	device_printf(sc->mrsas_dev, "Number of targets outstanding "
1676 	    "after reset: %d\n", mrsas_atomic_read(&sc->target_reset_outstanding));
1677 
1678 release_mpt:
1679 	mrsas_release_mpt_cmd(tm_mpt_cmd);
1680 return_status:
1681 	device_printf(sc->mrsas_dev, "target reset %s!!\n",
1682 		(retCode == SUCCESS) ? "SUCCESS" : "FAIL");
1683 
1684 	return retCode;
1685 }
1686 
1687