xref: /freebsd/sys/dev/mpt/mpt_cam.c (revision 70ed590b393173d4ea697be2a27054ed171f0c1a)
1 /*-
2  * FreeBSD/CAM specific routines for LSI '909 FC  adapters.
3  * FreeBSD Version.
4  *
5  * Copyright (c)  2000, 2001 by Greg Ansley
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice immediately at the beginning of the file, without modification,
12  *    this list of conditions, and the following disclaimer.
13  * 2. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*-
29  * Copyright (c) 2002, 2006 by Matthew Jacob
30  * All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions are
34  * met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
38  *    substantially similar to the "NO WARRANTY" disclaimer below
39  *    ("Disclaimer") and any redistribution must be conditioned upon including
40  *    a substantially similar Disclaimer requirement for further binary
41  *    redistribution.
42  * 3. Neither the names of the above listed copyright holders nor the names
43  *    of any contributors may be used to endorse or promote products derived
44  *    from this software without specific prior written permission.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
47  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
50  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
51  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
52  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
55  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
56  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57  *
58  * Support from Chris Ellsworth in order to make SAS adapters work
59  * is gratefully acknowledged.
60  *
61  * Support from LSI-Logic has also gone a great deal toward making this a
62  * workable subsystem and is gratefully acknowledged.
63  */
64 /*-
65  * Copyright (c) 2004, Avid Technology, Inc. and its contributors.
66  * Copyright (c) 2005, WHEEL Sp. z o.o.
67  * Copyright (c) 2004, 2005 Justin T. Gibbs
68  * All rights reserved.
69  *
70  * Redistribution and use in source and binary forms, with or without
71  * modification, are permitted provided that the following conditions are
72  * met:
73  * 1. Redistributions of source code must retain the above copyright
74  *    notice, this list of conditions and the following disclaimer.
75  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
76  *    substantially similar to the "NO WARRANTY" disclaimer below
77  *    ("Disclaimer") and any redistribution must be conditioned upon including
78  *    a substantially similar Disclaimer requirement for further binary
79  *    redistribution.
80  * 3. Neither the names of the above listed copyright holders nor the names
81  *    of any contributors may be used to endorse or promote products derived
82  *    from this software without specific prior written permission.
83  *
84  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
85  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
86  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
87  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
88  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
89  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
90  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
91  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
92  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
93  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
94  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
95  */
96 #include <sys/cdefs.h>
97 __FBSDID("$FreeBSD$");
98 
99 #include <dev/mpt/mpt.h>
100 #include <dev/mpt/mpt_cam.h>
101 #include <dev/mpt/mpt_raid.h>
102 
103 #include "dev/mpt/mpilib/mpi_ioc.h" /* XXX Fix Event Handling!!! */
104 #include "dev/mpt/mpilib/mpi_init.h"
105 #include "dev/mpt/mpilib/mpi_targ.h"
106 #include "dev/mpt/mpilib/mpi_fc.h"
107 #include "dev/mpt/mpilib/mpi_sas.h"
108 #if __FreeBSD_version >= 500000
109 #include <sys/sysctl.h>
110 #endif
111 #include <sys/callout.h>
112 #include <sys/kthread.h>
113 
114 #if __FreeBSD_version >= 700025
115 #ifndef	CAM_NEW_TRAN_CODE
116 #define	CAM_NEW_TRAN_CODE	1
117 #endif
118 #endif
119 
120 static void mpt_poll(struct cam_sim *);
121 static timeout_t mpt_timeout;
122 static void mpt_action(struct cam_sim *, union ccb *);
123 static int
124 mpt_get_spi_settings(struct mpt_softc *, struct ccb_trans_settings *);
125 static void mpt_setwidth(struct mpt_softc *, int, int);
126 static void mpt_setsync(struct mpt_softc *, int, int, int);
127 static int mpt_update_spi_config(struct mpt_softc *, int);
128 static void mpt_calc_geometry(struct ccb_calc_geometry *ccg, int extended);
129 
130 static mpt_reply_handler_t mpt_scsi_reply_handler;
131 static mpt_reply_handler_t mpt_scsi_tmf_reply_handler;
132 static mpt_reply_handler_t mpt_fc_els_reply_handler;
133 static int mpt_scsi_reply_frame_handler(struct mpt_softc *, request_t *,
134 					MSG_DEFAULT_REPLY *);
135 static int mpt_bus_reset(struct mpt_softc *, target_id_t, lun_id_t, int);
136 static int mpt_fc_reset_link(struct mpt_softc *, int);
137 
138 static int mpt_spawn_recovery_thread(struct mpt_softc *mpt);
139 static void mpt_terminate_recovery_thread(struct mpt_softc *mpt);
140 static void mpt_recovery_thread(void *arg);
141 static void mpt_recover_commands(struct mpt_softc *mpt);
142 
143 static int mpt_scsi_send_tmf(struct mpt_softc *, u_int, u_int, u_int,
144     u_int, u_int, u_int, int);
145 
146 static void mpt_fc_post_els(struct mpt_softc *mpt, request_t *, int);
147 static void mpt_post_target_command(struct mpt_softc *, request_t *, int);
148 static int mpt_add_els_buffers(struct mpt_softc *mpt);
149 static int mpt_add_target_commands(struct mpt_softc *mpt);
150 static int mpt_enable_lun(struct mpt_softc *, target_id_t, lun_id_t);
151 static int mpt_disable_lun(struct mpt_softc *, target_id_t, lun_id_t);
152 static void mpt_target_start_io(struct mpt_softc *, union ccb *);
153 static cam_status mpt_abort_target_ccb(struct mpt_softc *, union ccb *);
154 static int mpt_abort_target_cmd(struct mpt_softc *, request_t *);
155 static void mpt_scsi_tgt_status(struct mpt_softc *, union ccb *, request_t *,
156     uint8_t, uint8_t const *);
157 static void
158 mpt_scsi_tgt_tsk_mgmt(struct mpt_softc *, request_t *, mpt_task_mgmt_t,
159     tgt_resource_t *, int);
160 static void mpt_tgt_dump_tgt_state(struct mpt_softc *, request_t *);
161 static void mpt_tgt_dump_req_state(struct mpt_softc *, request_t *);
162 static mpt_reply_handler_t mpt_scsi_tgt_reply_handler;
163 static mpt_reply_handler_t mpt_sata_pass_reply_handler;
164 
165 static uint32_t scsi_io_handler_id = MPT_HANDLER_ID_NONE;
166 static uint32_t scsi_tmf_handler_id = MPT_HANDLER_ID_NONE;
167 static uint32_t fc_els_handler_id = MPT_HANDLER_ID_NONE;
168 static uint32_t sata_pass_handler_id = MPT_HANDLER_ID_NONE;
169 
170 static mpt_probe_handler_t	mpt_cam_probe;
171 static mpt_attach_handler_t	mpt_cam_attach;
172 static mpt_enable_handler_t	mpt_cam_enable;
173 static mpt_ready_handler_t	mpt_cam_ready;
174 static mpt_event_handler_t	mpt_cam_event;
175 static mpt_reset_handler_t	mpt_cam_ioc_reset;
176 static mpt_detach_handler_t	mpt_cam_detach;
177 
178 static struct mpt_personality mpt_cam_personality =
179 {
180 	.name		= "mpt_cam",
181 	.probe		= mpt_cam_probe,
182 	.attach		= mpt_cam_attach,
183 	.enable		= mpt_cam_enable,
184 	.ready		= mpt_cam_ready,
185 	.event		= mpt_cam_event,
186 	.reset		= mpt_cam_ioc_reset,
187 	.detach		= mpt_cam_detach,
188 };
189 
190 DECLARE_MPT_PERSONALITY(mpt_cam, SI_ORDER_SECOND);
191 MODULE_DEPEND(mpt_cam, cam, 1, 1, 1);
192 
193 int mpt_enable_sata_wc = -1;
194 TUNABLE_INT("hw.mpt.enable_sata_wc", &mpt_enable_sata_wc);
195 
196 int
197 mpt_cam_probe(struct mpt_softc *mpt)
198 {
199 	int role;
200 
201 	/*
202 	 * Only attach to nodes that support the initiator or target role
203 	 * (or want to) or have RAID physical devices that need CAM pass-thru
204 	 * support.
205 	 */
206 	if (mpt->do_cfg_role) {
207 		role = mpt->cfg_role;
208 	} else {
209 		role = mpt->role;
210 	}
211 	if ((role & (MPT_ROLE_TARGET|MPT_ROLE_INITIATOR)) != 0 ||
212 	    (mpt->ioc_page2 != NULL && mpt->ioc_page2->MaxPhysDisks != 0)) {
213 		return (0);
214 	}
215 	return (ENODEV);
216 }
217 
218 int
219 mpt_cam_attach(struct mpt_softc *mpt)
220 {
221 	struct cam_devq *devq;
222 	mpt_handler_t	 handler;
223 	int		 maxq;
224 	int		 error;
225 
226 	MPT_LOCK(mpt);
227 	TAILQ_INIT(&mpt->request_timeout_list);
228 	maxq = (mpt->ioc_facts.GlobalCredits < MPT_MAX_REQUESTS(mpt))?
229 	    mpt->ioc_facts.GlobalCredits : MPT_MAX_REQUESTS(mpt);
230 
231 	handler.reply_handler = mpt_scsi_reply_handler;
232 	error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
233 				     &scsi_io_handler_id);
234 	if (error != 0) {
235 		MPT_UNLOCK(mpt);
236 		goto cleanup;
237 	}
238 
239 	handler.reply_handler = mpt_scsi_tmf_reply_handler;
240 	error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
241 				     &scsi_tmf_handler_id);
242 	if (error != 0) {
243 		MPT_UNLOCK(mpt);
244 		goto cleanup;
245 	}
246 
247 	/*
248 	 * If we're fibre channel and could support target mode, we register
249 	 * an ELS reply handler and give it resources.
250 	 */
251 	if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET) != 0) {
252 		handler.reply_handler = mpt_fc_els_reply_handler;
253 		error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
254 		    &fc_els_handler_id);
255 		if (error != 0) {
256 			MPT_UNLOCK(mpt);
257 			goto cleanup;
258 		}
259 		if (mpt_add_els_buffers(mpt) == FALSE) {
260 			error = ENOMEM;
261 			MPT_UNLOCK(mpt);
262 			goto cleanup;
263 		}
264 		maxq -= mpt->els_cmds_allocated;
265 	}
266 
267 	/*
268 	 * If we support target mode, we register a reply handler for it,
269 	 * but don't add command resources until we actually enable target
270 	 * mode.
271 	 */
272 	if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET) != 0) {
273 		handler.reply_handler = mpt_scsi_tgt_reply_handler;
274 		error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
275 		    &mpt->scsi_tgt_handler_id);
276 		if (error != 0) {
277 			MPT_UNLOCK(mpt);
278 			goto cleanup;
279 		}
280 	}
281 
282 	if (mpt->is_sas) {
283 		handler.reply_handler = mpt_sata_pass_reply_handler;
284 		error = mpt_register_handler(mpt, MPT_HANDLER_REPLY, handler,
285 		    &sata_pass_handler_id);
286 		if (error != 0) {
287 			MPT_UNLOCK(mpt);
288 			goto cleanup;
289 		}
290 	}
291 
292 	/*
293 	 * We keep one request reserved for timeout TMF requests.
294 	 */
295 	mpt->tmf_req = mpt_get_request(mpt, FALSE);
296 	if (mpt->tmf_req == NULL) {
297 		mpt_prt(mpt, "Unable to allocate dedicated TMF request!\n");
298 		error = ENOMEM;
299 		MPT_UNLOCK(mpt);
300 		goto cleanup;
301 	}
302 
303 	/*
304 	 * Mark the request as free even though not on the free list.
305 	 * There is only one TMF request allowed to be outstanding at
306 	 * a time and the TMF routines perform their own allocation
307 	 * tracking using the standard state flags.
308 	 */
309 	mpt->tmf_req->state = REQ_STATE_FREE;
310 	maxq--;
311 
312 	/*
313 	 * The rest of this is CAM foo, for which we need to drop our lock
314 	 */
315 	MPT_UNLOCK(mpt);
316 
317 	if (mpt_spawn_recovery_thread(mpt) != 0) {
318 		mpt_prt(mpt, "Unable to spawn recovery thread!\n");
319 		error = ENOMEM;
320 		goto cleanup;
321 	}
322 
323 	/*
324 	 * Create the device queue for our SIM(s).
325 	 */
326 	devq = cam_simq_alloc(maxq);
327 	if (devq == NULL) {
328 		mpt_prt(mpt, "Unable to allocate CAM SIMQ!\n");
329 		error = ENOMEM;
330 		goto cleanup;
331 	}
332 
333 	/*
334 	 * Construct our SIM entry.
335 	 */
336 	mpt->sim =
337 	    mpt_sim_alloc(mpt_action, mpt_poll, "mpt", mpt, 1, maxq, devq);
338 	if (mpt->sim == NULL) {
339 		mpt_prt(mpt, "Unable to allocate CAM SIM!\n");
340 		cam_simq_free(devq);
341 		error = ENOMEM;
342 		goto cleanup;
343 	}
344 
345 	/*
346 	 * Register exactly this bus.
347 	 */
348 	MPT_LOCK(mpt);
349 	if (mpt_xpt_bus_register(mpt->sim, mpt->dev, 0) != CAM_SUCCESS) {
350 		mpt_prt(mpt, "Bus registration Failed!\n");
351 		error = ENOMEM;
352 		MPT_UNLOCK(mpt);
353 		goto cleanup;
354 	}
355 
356 	if (xpt_create_path(&mpt->path, NULL, cam_sim_path(mpt->sim),
357 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
358 		mpt_prt(mpt, "Unable to allocate Path!\n");
359 		error = ENOMEM;
360 		MPT_UNLOCK(mpt);
361 		goto cleanup;
362 	}
363 	MPT_UNLOCK(mpt);
364 
365 	/*
366 	 * Only register a second bus for RAID physical
367 	 * devices if the controller supports RAID.
368 	 */
369 	if (mpt->ioc_page2 == NULL || mpt->ioc_page2->MaxPhysDisks == 0) {
370 		return (0);
371 	}
372 
373 	/*
374 	 * Create a "bus" to export all hidden disks to CAM.
375 	 */
376 	mpt->phydisk_sim =
377 	    mpt_sim_alloc(mpt_action, mpt_poll, "mpt", mpt, 1, maxq, devq);
378 	if (mpt->phydisk_sim == NULL) {
379 		mpt_prt(mpt, "Unable to allocate Physical Disk CAM SIM!\n");
380 		error = ENOMEM;
381 		goto cleanup;
382 	}
383 
384 	/*
385 	 * Register this bus.
386 	 */
387 	MPT_LOCK(mpt);
388 	if (mpt_xpt_bus_register(mpt->phydisk_sim, mpt->dev, 1) !=
389 	    CAM_SUCCESS) {
390 		mpt_prt(mpt, "Physical Disk Bus registration Failed!\n");
391 		error = ENOMEM;
392 		MPT_UNLOCK(mpt);
393 		goto cleanup;
394 	}
395 
396 	if (xpt_create_path(&mpt->phydisk_path, NULL,
397 	    cam_sim_path(mpt->phydisk_sim),
398 	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
399 		mpt_prt(mpt, "Unable to allocate Physical Disk Path!\n");
400 		error = ENOMEM;
401 		MPT_UNLOCK(mpt);
402 		goto cleanup;
403 	}
404 	MPT_UNLOCK(mpt);
405 	mpt_lprt(mpt, MPT_PRT_DEBUG, "attached cam\n");
406 	return (0);
407 
408 cleanup:
409 	mpt_cam_detach(mpt);
410 	return (error);
411 }
412 
413 /*
414  * Read FC configuration information
415  */
416 static int
417 mpt_read_config_info_fc(struct mpt_softc *mpt)
418 {
419 	char *topology = NULL;
420 	int rv;
421 
422 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_FC_PORT, 0,
423 	    0, &mpt->mpt_fcport_page0.Header, FALSE, 5000);
424 	if (rv) {
425 		return (-1);
426 	}
427 	mpt_lprt(mpt, MPT_PRT_DEBUG, "FC Port Page 0 Header: %x %x %x %x\n",
428 		 mpt->mpt_fcport_page0.Header.PageVersion,
429 		 mpt->mpt_fcport_page0.Header.PageLength,
430 		 mpt->mpt_fcport_page0.Header.PageNumber,
431 		 mpt->mpt_fcport_page0.Header.PageType);
432 
433 
434 	rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_fcport_page0.Header,
435 	    sizeof(mpt->mpt_fcport_page0), FALSE, 5000);
436 	if (rv) {
437 		mpt_prt(mpt, "failed to read FC Port Page 0\n");
438 		return (-1);
439 	}
440 	mpt2host_config_page_fc_port_0(&mpt->mpt_fcport_page0);
441 
442 	mpt->mpt_fcport_speed = mpt->mpt_fcport_page0.CurrentSpeed;
443 
444 	switch (mpt->mpt_fcport_page0.Flags &
445 	    MPI_FCPORTPAGE0_FLAGS_ATTACH_TYPE_MASK) {
446 	case MPI_FCPORTPAGE0_FLAGS_ATTACH_NO_INIT:
447 		mpt->mpt_fcport_speed = 0;
448 		topology = "<NO LOOP>";
449 		break;
450 	case MPI_FCPORTPAGE0_FLAGS_ATTACH_POINT_TO_POINT:
451 		topology = "N-Port";
452 		break;
453 	case MPI_FCPORTPAGE0_FLAGS_ATTACH_PRIVATE_LOOP:
454 		topology = "NL-Port";
455 		break;
456 	case MPI_FCPORTPAGE0_FLAGS_ATTACH_FABRIC_DIRECT:
457 		topology = "F-Port";
458 		break;
459 	case MPI_FCPORTPAGE0_FLAGS_ATTACH_PUBLIC_LOOP:
460 		topology = "FL-Port";
461 		break;
462 	default:
463 		mpt->mpt_fcport_speed = 0;
464 		topology = "?";
465 		break;
466 	}
467 
468 	mpt_lprt(mpt, MPT_PRT_INFO,
469 	    "FC Port Page 0: Topology <%s> WWNN 0x%08x%08x WWPN 0x%08x%08x "
470 	    "Speed %u-Gbit\n", topology,
471 	    mpt->mpt_fcport_page0.WWNN.High,
472 	    mpt->mpt_fcport_page0.WWNN.Low,
473 	    mpt->mpt_fcport_page0.WWPN.High,
474 	    mpt->mpt_fcport_page0.WWPN.Low,
475 	    mpt->mpt_fcport_speed);
476 #if __FreeBSD_version >= 500000
477 	MPT_UNLOCK(mpt);
478 	{
479 		struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(mpt->dev);
480 		struct sysctl_oid *tree = device_get_sysctl_tree(mpt->dev);
481 
482 		snprintf(mpt->scinfo.fc.wwnn,
483 		    sizeof (mpt->scinfo.fc.wwnn), "0x%08x%08x",
484 		    mpt->mpt_fcport_page0.WWNN.High,
485 		    mpt->mpt_fcport_page0.WWNN.Low);
486 
487 		snprintf(mpt->scinfo.fc.wwpn,
488 		    sizeof (mpt->scinfo.fc.wwpn), "0x%08x%08x",
489 		    mpt->mpt_fcport_page0.WWPN.High,
490 		    mpt->mpt_fcport_page0.WWPN.Low);
491 
492 		SYSCTL_ADD_STRING(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
493 		       "wwnn", CTLFLAG_RD, mpt->scinfo.fc.wwnn, 0,
494 		       "World Wide Node Name");
495 
496 		SYSCTL_ADD_STRING(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
497 		       "wwpn", CTLFLAG_RD, mpt->scinfo.fc.wwpn, 0,
498 		       "World Wide Port Name");
499 
500 	}
501 	MPT_LOCK(mpt);
502 #endif
503 	return (0);
504 }
505 
506 /*
507  * Set FC configuration information.
508  */
509 static int
510 mpt_set_initial_config_fc(struct mpt_softc *mpt)
511 {
512 
513 	CONFIG_PAGE_FC_PORT_1 fc;
514 	U32 fl;
515 	int r, doit = 0;
516 	int role;
517 
518 	r = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_FC_PORT, 1, 0,
519 	    &fc.Header, FALSE, 5000);
520 	if (r) {
521 		mpt_prt(mpt, "failed to read FC page 1 header\n");
522 		return (mpt_fc_reset_link(mpt, 1));
523 	}
524 
525 	r = mpt_read_cfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_NVRAM, 0,
526 	    &fc.Header, sizeof (fc), FALSE, 5000);
527 	if (r) {
528 		mpt_prt(mpt, "failed to read FC page 1\n");
529 		return (mpt_fc_reset_link(mpt, 1));
530 	}
531 	mpt2host_config_page_fc_port_1(&fc);
532 
533 	/*
534 	 * Check our flags to make sure we support the role we want.
535 	 */
536 	doit = 0;
537 	role = 0;
538 	fl = fc.Flags;
539 
540 	if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_INIT) {
541 		role |= MPT_ROLE_INITIATOR;
542 	}
543 	if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG) {
544 		role |= MPT_ROLE_TARGET;
545 	}
546 
547 	fl &= ~MPI_FCPORTPAGE1_FLAGS_PROT_MASK;
548 
549 	if (mpt->do_cfg_role == 0) {
550 		role = mpt->cfg_role;
551 	} else {
552 		mpt->do_cfg_role = 0;
553 	}
554 
555 	if (role != mpt->cfg_role) {
556 		if (mpt->cfg_role & MPT_ROLE_INITIATOR) {
557 			if ((role & MPT_ROLE_INITIATOR) == 0) {
558 				mpt_prt(mpt, "adding initiator role\n");
559 				fl |= MPI_FCPORTPAGE1_FLAGS_PROT_FCP_INIT;
560 				doit++;
561 			} else {
562 				mpt_prt(mpt, "keeping initiator role\n");
563 			}
564 		} else if (role & MPT_ROLE_INITIATOR) {
565 			mpt_prt(mpt, "removing initiator role\n");
566 			doit++;
567 		}
568 		if (mpt->cfg_role & MPT_ROLE_TARGET) {
569 			if ((role & MPT_ROLE_TARGET) == 0) {
570 				mpt_prt(mpt, "adding target role\n");
571 				fl |= MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG;
572 				doit++;
573 			} else {
574 				mpt_prt(mpt, "keeping target role\n");
575 			}
576 		} else if (role & MPT_ROLE_TARGET) {
577 			mpt_prt(mpt, "removing target role\n");
578 			doit++;
579 		}
580 		mpt->role = mpt->cfg_role;
581 	}
582 
583 	if (fl & MPI_FCPORTPAGE1_FLAGS_PROT_FCP_TARG) {
584 		if ((fl & MPI_FCPORTPAGE1_FLAGS_TARGET_MODE_OXID) == 0) {
585 			mpt_prt(mpt, "adding OXID option\n");
586 			fl |= MPI_FCPORTPAGE1_FLAGS_TARGET_MODE_OXID;
587 			doit++;
588 		}
589 	}
590 
591 	if (doit) {
592 		fc.Flags = fl;
593 		host2mpt_config_page_fc_port_1(&fc);
594 		r = mpt_write_cfg_page(mpt,
595 		    MPI_CONFIG_ACTION_PAGE_WRITE_NVRAM, 0, &fc.Header,
596 		    sizeof(fc), FALSE, 5000);
597 		if (r != 0) {
598 			mpt_prt(mpt, "failed to update NVRAM with changes\n");
599 			return (0);
600 		}
601 		mpt_prt(mpt, "NOTE: NVRAM changes will not take "
602 		    "effect until next reboot or IOC reset\n");
603 	}
604 	return (0);
605 }
606 
607 static int
608 mptsas_sas_io_unit_pg0(struct mpt_softc *mpt, struct mptsas_portinfo *portinfo)
609 {
610 	ConfigExtendedPageHeader_t hdr;
611 	struct mptsas_phyinfo *phyinfo;
612 	SasIOUnitPage0_t *buffer;
613 	int error, len, i;
614 
615 	error = mpt_read_extcfg_header(mpt, MPI_SASIOUNITPAGE0_PAGEVERSION,
616 				       0, 0, MPI_CONFIG_EXTPAGETYPE_SAS_IO_UNIT,
617 				       &hdr, 0, 10000);
618 	if (error)
619 		goto out;
620 	if (hdr.ExtPageLength == 0) {
621 		error = ENXIO;
622 		goto out;
623 	}
624 
625 	len = hdr.ExtPageLength * 4;
626 	buffer = malloc(len, M_DEVBUF, M_NOWAIT|M_ZERO);
627 	if (buffer == NULL) {
628 		error = ENOMEM;
629 		goto out;
630 	}
631 
632 	error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
633 				     0, &hdr, buffer, len, 0, 10000);
634 	if (error) {
635 		free(buffer, M_DEVBUF);
636 		goto out;
637 	}
638 
639 	portinfo->num_phys = buffer->NumPhys;
640 	portinfo->phy_info = malloc(sizeof(*portinfo->phy_info) *
641 	    portinfo->num_phys, M_DEVBUF, M_NOWAIT|M_ZERO);
642 	if (portinfo->phy_info == NULL) {
643 		free(buffer, M_DEVBUF);
644 		error = ENOMEM;
645 		goto out;
646 	}
647 
648 	for (i = 0; i < portinfo->num_phys; i++) {
649 		phyinfo = &portinfo->phy_info[i];
650 		phyinfo->phy_num = i;
651 		phyinfo->port_id = buffer->PhyData[i].Port;
652 		phyinfo->negotiated_link_rate =
653 		    buffer->PhyData[i].NegotiatedLinkRate;
654 		phyinfo->handle =
655 		    le16toh(buffer->PhyData[i].ControllerDevHandle);
656 	}
657 
658 	free(buffer, M_DEVBUF);
659 out:
660 	return (error);
661 }
662 
663 static int
664 mptsas_sas_phy_pg0(struct mpt_softc *mpt, struct mptsas_phyinfo *phy_info,
665 	uint32_t form, uint32_t form_specific)
666 {
667 	ConfigExtendedPageHeader_t hdr;
668 	SasPhyPage0_t *buffer;
669 	int error;
670 
671 	error = mpt_read_extcfg_header(mpt, MPI_SASPHY0_PAGEVERSION, 0, 0,
672 				       MPI_CONFIG_EXTPAGETYPE_SAS_PHY, &hdr,
673 				       0, 10000);
674 	if (error)
675 		goto out;
676 	if (hdr.ExtPageLength == 0) {
677 		error = ENXIO;
678 		goto out;
679 	}
680 
681 	buffer = malloc(sizeof(SasPhyPage0_t), M_DEVBUF, M_NOWAIT|M_ZERO);
682 	if (buffer == NULL) {
683 		error = ENOMEM;
684 		goto out;
685 	}
686 
687 	error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
688 				     form + form_specific, &hdr, buffer,
689 				     sizeof(SasPhyPage0_t), 0, 10000);
690 	if (error) {
691 		free(buffer, M_DEVBUF);
692 		goto out;
693 	}
694 
695 	phy_info->hw_link_rate = buffer->HwLinkRate;
696 	phy_info->programmed_link_rate = buffer->ProgrammedLinkRate;
697 	phy_info->identify.dev_handle = le16toh(buffer->OwnerDevHandle);
698 	phy_info->attached.dev_handle = le16toh(buffer->AttachedDevHandle);
699 
700 	free(buffer, M_DEVBUF);
701 out:
702 	return (error);
703 }
704 
705 static int
706 mptsas_sas_device_pg0(struct mpt_softc *mpt, struct mptsas_devinfo *device_info,
707 	uint32_t form, uint32_t form_specific)
708 {
709 	ConfigExtendedPageHeader_t hdr;
710 	SasDevicePage0_t *buffer;
711 	uint64_t sas_address;
712 	int error = 0;
713 
714 	bzero(device_info, sizeof(*device_info));
715 	error = mpt_read_extcfg_header(mpt, MPI_SASDEVICE0_PAGEVERSION, 0, 0,
716 				       MPI_CONFIG_EXTPAGETYPE_SAS_DEVICE,
717 				       &hdr, 0, 10000);
718 	if (error)
719 		goto out;
720 	if (hdr.ExtPageLength == 0) {
721 		error = ENXIO;
722 		goto out;
723 	}
724 
725 	buffer = malloc(sizeof(SasDevicePage0_t), M_DEVBUF, M_NOWAIT|M_ZERO);
726 	if (buffer == NULL) {
727 		error = ENOMEM;
728 		goto out;
729 	}
730 
731 	error = mpt_read_extcfg_page(mpt, MPI_CONFIG_ACTION_PAGE_READ_CURRENT,
732 				     form + form_specific, &hdr, buffer,
733 				     sizeof(SasDevicePage0_t), 0, 10000);
734 	if (error) {
735 		free(buffer, M_DEVBUF);
736 		goto out;
737 	}
738 
739 	device_info->dev_handle = le16toh(buffer->DevHandle);
740 	device_info->parent_dev_handle = le16toh(buffer->ParentDevHandle);
741 	device_info->enclosure_handle = le16toh(buffer->EnclosureHandle);
742 	device_info->slot = le16toh(buffer->Slot);
743 	device_info->phy_num = buffer->PhyNum;
744 	device_info->physical_port = buffer->PhysicalPort;
745 	device_info->target_id = buffer->TargetID;
746 	device_info->bus = buffer->Bus;
747 	bcopy(&buffer->SASAddress, &sas_address, sizeof(uint64_t));
748 	device_info->sas_address = le64toh(sas_address);
749 	device_info->device_info = le32toh(buffer->DeviceInfo);
750 
751 	free(buffer, M_DEVBUF);
752 out:
753 	return (error);
754 }
755 
756 /*
757  * Read SAS configuration information. Nothing to do yet.
758  */
759 static int
760 mpt_read_config_info_sas(struct mpt_softc *mpt)
761 {
762 	struct mptsas_portinfo *portinfo;
763 	struct mptsas_phyinfo *phyinfo;
764 	int error, i;
765 
766 	portinfo = malloc(sizeof(*portinfo), M_DEVBUF, M_NOWAIT|M_ZERO);
767 	if (portinfo == NULL)
768 		return (ENOMEM);
769 
770 	error = mptsas_sas_io_unit_pg0(mpt, portinfo);
771 	if (error) {
772 		free(portinfo, M_DEVBUF);
773 		return (0);
774 	}
775 
776 	for (i = 0; i < portinfo->num_phys; i++) {
777 		phyinfo = &portinfo->phy_info[i];
778 		error = mptsas_sas_phy_pg0(mpt, phyinfo,
779 		    (MPI_SAS_PHY_PGAD_FORM_PHY_NUMBER <<
780 		    MPI_SAS_PHY_PGAD_FORM_SHIFT), i);
781 		if (error)
782 			break;
783 		error = mptsas_sas_device_pg0(mpt, &phyinfo->identify,
784 		    (MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
785 		    MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
786 		    phyinfo->handle);
787 		if (error)
788 			break;
789 		phyinfo->identify.phy_num = phyinfo->phy_num = i;
790 		if (phyinfo->attached.dev_handle)
791 			error = mptsas_sas_device_pg0(mpt,
792 			    &phyinfo->attached,
793 			    (MPI_SAS_DEVICE_PGAD_FORM_HANDLE <<
794 			    MPI_SAS_DEVICE_PGAD_FORM_SHIFT),
795 			    phyinfo->attached.dev_handle);
796 		if (error)
797 			break;
798 	}
799 	mpt->sas_portinfo = portinfo;
800 	return (0);
801 }
802 
803 static void
804 mptsas_set_sata_wc(struct mpt_softc *mpt, struct mptsas_devinfo *devinfo,
805 	int enabled)
806 {
807 	SataPassthroughRequest_t	*pass;
808 	request_t *req;
809 	int error, status;
810 
811 	req = mpt_get_request(mpt, 0);
812 	if (req == NULL)
813 		return;
814 
815 	pass = req->req_vbuf;
816 	bzero(pass, sizeof(SataPassthroughRequest_t));
817 	pass->Function = MPI_FUNCTION_SATA_PASSTHROUGH;
818 	pass->TargetID = devinfo->target_id;
819 	pass->Bus = devinfo->bus;
820 	pass->PassthroughFlags = 0;
821 	pass->ConnectionRate = MPI_SATA_PT_REQ_CONNECT_RATE_NEGOTIATED;
822 	pass->DataLength = 0;
823 	pass->MsgContext = htole32(req->index | sata_pass_handler_id);
824 	pass->CommandFIS[0] = 0x27;
825 	pass->CommandFIS[1] = 0x80;
826 	pass->CommandFIS[2] = 0xef;
827 	pass->CommandFIS[3] = (enabled) ? 0x02 : 0x82;
828 	pass->CommandFIS[7] = 0x40;
829 	pass->CommandFIS[15] = 0x08;
830 
831 	mpt_check_doorbell(mpt);
832 	mpt_send_cmd(mpt, req);
833 	error = mpt_wait_req(mpt, req, REQ_STATE_DONE, REQ_STATE_DONE, 0,
834 			     10 * 1000);
835 	if (error) {
836 		mpt_free_request(mpt, req);
837 		printf("error %d sending passthrough\n", error);
838 		return;
839 	}
840 
841 	status = le16toh(req->IOCStatus);
842 	if (status != MPI_IOCSTATUS_SUCCESS) {
843 		mpt_free_request(mpt, req);
844 		printf("IOCSTATUS %d\n", status);
845 		return;
846 	}
847 
848 	mpt_free_request(mpt, req);
849 }
850 
851 /*
852  * Set SAS configuration information. Nothing to do yet.
853  */
854 static int
855 mpt_set_initial_config_sas(struct mpt_softc *mpt)
856 {
857 	struct mptsas_phyinfo *phyinfo;
858 	int i;
859 
860 	if ((mpt_enable_sata_wc != -1) && (mpt->sas_portinfo != NULL)) {
861 		for (i = 0; i < mpt->sas_portinfo->num_phys; i++) {
862 			phyinfo = &mpt->sas_portinfo->phy_info[i];
863 			if (phyinfo->attached.dev_handle == 0)
864 				continue;
865 			if ((phyinfo->attached.device_info &
866 			    MPI_SAS_DEVICE_INFO_SATA_DEVICE) == 0)
867 				continue;
868 			if (bootverbose)
869 				device_printf(mpt->dev,
870 				    "%sabling SATA WC on phy %d\n",
871 				    (mpt_enable_sata_wc) ? "En" : "Dis", i);
872 			mptsas_set_sata_wc(mpt, &phyinfo->attached,
873 					   mpt_enable_sata_wc);
874 		}
875 	}
876 
877 	return (0);
878 }
879 
880 static int
881 mpt_sata_pass_reply_handler(struct mpt_softc *mpt, request_t *req,
882  uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
883 {
884 	if (req != NULL) {
885 
886 		if (reply_frame != NULL) {
887 			req->IOCStatus = le16toh(reply_frame->IOCStatus);
888 		}
889 		req->state &= ~REQ_STATE_QUEUED;
890 		req->state |= REQ_STATE_DONE;
891 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
892 		if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
893 			wakeup(req);
894 		} else if ((req->state & REQ_STATE_TIMEDOUT) != 0) {
895 			/*
896 			 * Whew- we can free this request (late completion)
897 			 */
898 			mpt_free_request(mpt, req);
899 		}
900 	}
901 
902 	return (TRUE);
903 }
904 
905 /*
906  * Read SCSI configuration information
907  */
908 static int
909 mpt_read_config_info_spi(struct mpt_softc *mpt)
910 {
911 	int rv, i;
912 
913 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 0, 0,
914 	    &mpt->mpt_port_page0.Header, FALSE, 5000);
915 	if (rv) {
916 		return (-1);
917 	}
918 	mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 0 Header: %x %x %x %x\n",
919 	    mpt->mpt_port_page0.Header.PageVersion,
920 	    mpt->mpt_port_page0.Header.PageLength,
921 	    mpt->mpt_port_page0.Header.PageNumber,
922 	    mpt->mpt_port_page0.Header.PageType);
923 
924 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 1, 0,
925 	    &mpt->mpt_port_page1.Header, FALSE, 5000);
926 	if (rv) {
927 		return (-1);
928 	}
929 	mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 1 Header: %x %x %x %x\n",
930 	    mpt->mpt_port_page1.Header.PageVersion,
931 	    mpt->mpt_port_page1.Header.PageLength,
932 	    mpt->mpt_port_page1.Header.PageNumber,
933 	    mpt->mpt_port_page1.Header.PageType);
934 
935 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_PORT, 2, 0,
936 	    &mpt->mpt_port_page2.Header, FALSE, 5000);
937 	if (rv) {
938 		return (-1);
939 	}
940 	mpt_lprt(mpt, MPT_PRT_DEBUG, "SPI Port Page 2 Header: %x %x %x %x\n",
941 	    mpt->mpt_port_page2.Header.PageVersion,
942 	    mpt->mpt_port_page2.Header.PageLength,
943 	    mpt->mpt_port_page2.Header.PageNumber,
944 	    mpt->mpt_port_page2.Header.PageType);
945 
946 	for (i = 0; i < 16; i++) {
947 		rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_DEVICE,
948 		    0, i, &mpt->mpt_dev_page0[i].Header, FALSE, 5000);
949 		if (rv) {
950 			return (-1);
951 		}
952 		mpt_lprt(mpt, MPT_PRT_DEBUG,
953 		    "SPI Target %d Device Page 0 Header: %x %x %x %x\n", i,
954 		    mpt->mpt_dev_page0[i].Header.PageVersion,
955 		    mpt->mpt_dev_page0[i].Header.PageLength,
956 		    mpt->mpt_dev_page0[i].Header.PageNumber,
957 		    mpt->mpt_dev_page0[i].Header.PageType);
958 
959 		rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_SCSI_DEVICE,
960 		    1, i, &mpt->mpt_dev_page1[i].Header, FALSE, 5000);
961 		if (rv) {
962 			return (-1);
963 		}
964 		mpt_lprt(mpt, MPT_PRT_DEBUG,
965 		    "SPI Target %d Device Page 1 Header: %x %x %x %x\n", i,
966 		    mpt->mpt_dev_page1[i].Header.PageVersion,
967 		    mpt->mpt_dev_page1[i].Header.PageLength,
968 		    mpt->mpt_dev_page1[i].Header.PageNumber,
969 		    mpt->mpt_dev_page1[i].Header.PageType);
970 	}
971 
972 	/*
973 	 * At this point, we don't *have* to fail. As long as we have
974 	 * valid config header information, we can (barely) lurch
975 	 * along.
976 	 */
977 
978 	rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page0.Header,
979 	    sizeof(mpt->mpt_port_page0), FALSE, 5000);
980 	if (rv) {
981 		mpt_prt(mpt, "failed to read SPI Port Page 0\n");
982 	} else {
983 		mpt2host_config_page_scsi_port_0(&mpt->mpt_port_page0);
984 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
985 		    "SPI Port Page 0: Capabilities %x PhysicalInterface %x\n",
986 		    mpt->mpt_port_page0.Capabilities,
987 		    mpt->mpt_port_page0.PhysicalInterface);
988 	}
989 
990 	rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page1.Header,
991 	    sizeof(mpt->mpt_port_page1), FALSE, 5000);
992 	if (rv) {
993 		mpt_prt(mpt, "failed to read SPI Port Page 1\n");
994 	} else {
995 		mpt2host_config_page_scsi_port_1(&mpt->mpt_port_page1);
996 		mpt_lprt(mpt, MPT_PRT_DEBUG,
997 		    "SPI Port Page 1: Configuration %x OnBusTimerValue %x\n",
998 		    mpt->mpt_port_page1.Configuration,
999 		    mpt->mpt_port_page1.OnBusTimerValue);
1000 	}
1001 
1002 	rv = mpt_read_cur_cfg_page(mpt, 0, &mpt->mpt_port_page2.Header,
1003 	    sizeof(mpt->mpt_port_page2), FALSE, 5000);
1004 	if (rv) {
1005 		mpt_prt(mpt, "failed to read SPI Port Page 2\n");
1006 	} else {
1007 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1008 		    "Port Page 2: Flags %x Settings %x\n",
1009 		    mpt->mpt_port_page2.PortFlags,
1010 		    mpt->mpt_port_page2.PortSettings);
1011 		mpt2host_config_page_scsi_port_2(&mpt->mpt_port_page2);
1012 		for (i = 0; i < 16; i++) {
1013 			mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1014 		  	    " Port Page 2 Tgt %d: timo %x SF %x Flags %x\n",
1015 			    i, mpt->mpt_port_page2.DeviceSettings[i].Timeout,
1016 			    mpt->mpt_port_page2.DeviceSettings[i].SyncFactor,
1017 			    mpt->mpt_port_page2.DeviceSettings[i].DeviceFlags);
1018 		}
1019 	}
1020 
1021 	for (i = 0; i < 16; i++) {
1022 		rv = mpt_read_cur_cfg_page(mpt, i,
1023 		    &mpt->mpt_dev_page0[i].Header, sizeof(*mpt->mpt_dev_page0),
1024 		    FALSE, 5000);
1025 		if (rv) {
1026 			mpt_prt(mpt,
1027 			    "cannot read SPI Target %d Device Page 0\n", i);
1028 			continue;
1029 		}
1030 		mpt2host_config_page_scsi_device_0(&mpt->mpt_dev_page0[i]);
1031 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1032 		    "target %d page 0: Negotiated Params %x Information %x\n",
1033 		    i, mpt->mpt_dev_page0[i].NegotiatedParameters,
1034 		    mpt->mpt_dev_page0[i].Information);
1035 
1036 		rv = mpt_read_cur_cfg_page(mpt, i,
1037 		    &mpt->mpt_dev_page1[i].Header, sizeof(*mpt->mpt_dev_page1),
1038 		    FALSE, 5000);
1039 		if (rv) {
1040 			mpt_prt(mpt,
1041 			    "cannot read SPI Target %d Device Page 1\n", i);
1042 			continue;
1043 		}
1044 		mpt2host_config_page_scsi_device_1(&mpt->mpt_dev_page1[i]);
1045 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1046 		    "target %d page 1: Requested Params %x Configuration %x\n",
1047 		    i, mpt->mpt_dev_page1[i].RequestedParameters,
1048 		    mpt->mpt_dev_page1[i].Configuration);
1049 	}
1050 	return (0);
1051 }
1052 
1053 /*
1054  * Validate SPI configuration information.
1055  *
1056  * In particular, validate SPI Port Page 1.
1057  */
1058 static int
1059 mpt_set_initial_config_spi(struct mpt_softc *mpt)
1060 {
1061 	int i, pp1val = ((1 << mpt->mpt_ini_id) << 16) | mpt->mpt_ini_id;
1062 	int error;
1063 
1064 	mpt->mpt_disc_enable = 0xff;
1065 	mpt->mpt_tag_enable = 0;
1066 
1067 	if (mpt->mpt_port_page1.Configuration != pp1val) {
1068 		CONFIG_PAGE_SCSI_PORT_1 tmp;
1069 
1070 		mpt_prt(mpt, "SPI Port Page 1 Config value bad (%x)- should "
1071 		    "be %x\n", mpt->mpt_port_page1.Configuration, pp1val);
1072 		tmp = mpt->mpt_port_page1;
1073 		tmp.Configuration = pp1val;
1074 		host2mpt_config_page_scsi_port_1(&tmp);
1075 		error = mpt_write_cur_cfg_page(mpt, 0,
1076 		    &tmp.Header, sizeof(tmp), FALSE, 5000);
1077 		if (error) {
1078 			return (-1);
1079 		}
1080 		error = mpt_read_cur_cfg_page(mpt, 0,
1081 		    &tmp.Header, sizeof(tmp), FALSE, 5000);
1082 		if (error) {
1083 			return (-1);
1084 		}
1085 		mpt2host_config_page_scsi_port_1(&tmp);
1086 		if (tmp.Configuration != pp1val) {
1087 			mpt_prt(mpt,
1088 			    "failed to reset SPI Port Page 1 Config value\n");
1089 			return (-1);
1090 		}
1091 		mpt->mpt_port_page1 = tmp;
1092 	}
1093 
1094 	/*
1095 	 * The purpose of this exercise is to get
1096 	 * all targets back to async/narrow.
1097 	 *
1098 	 * We skip this step if the BIOS has already negotiated
1099 	 * speeds with the targets.
1100 	 */
1101 	i = mpt->mpt_port_page2.PortSettings &
1102 	    MPI_SCSIPORTPAGE2_PORT_MASK_NEGO_MASTER_SETTINGS;
1103 	if (i == MPI_SCSIPORTPAGE2_PORT_ALL_MASTER_SETTINGS) {
1104 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
1105 		    "honoring BIOS transfer negotiations\n");
1106 	} else {
1107 		for (i = 0; i < 16; i++) {
1108 			mpt->mpt_dev_page1[i].RequestedParameters = 0;
1109 			mpt->mpt_dev_page1[i].Configuration = 0;
1110 			(void) mpt_update_spi_config(mpt, i);
1111 		}
1112 	}
1113 	return (0);
1114 }
1115 
1116 int
1117 mpt_cam_enable(struct mpt_softc *mpt)
1118 {
1119 	int error;
1120 
1121 	MPT_LOCK(mpt);
1122 
1123 	error = EIO;
1124 	if (mpt->is_fc) {
1125 		if (mpt_read_config_info_fc(mpt)) {
1126 			goto out;
1127 		}
1128 		if (mpt_set_initial_config_fc(mpt)) {
1129 			goto out;
1130 		}
1131 	} else if (mpt->is_sas) {
1132 		if (mpt_read_config_info_sas(mpt)) {
1133 			goto out;
1134 		}
1135 		if (mpt_set_initial_config_sas(mpt)) {
1136 			goto out;
1137 		}
1138 	} else if (mpt->is_spi) {
1139 		if (mpt_read_config_info_spi(mpt)) {
1140 			goto out;
1141 		}
1142 		if (mpt_set_initial_config_spi(mpt)) {
1143 			goto out;
1144 		}
1145 	}
1146 	error = 0;
1147 
1148 out:
1149 	MPT_UNLOCK(mpt);
1150 	return (error);
1151 }
1152 
1153 void
1154 mpt_cam_ready(struct mpt_softc *mpt)
1155 {
1156 	/*
1157 	 * If we're in target mode, hang out resources now
1158 	 * so we don't cause the world to hang talking to us.
1159 	 */
1160 	if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET)) {
1161 		/*
1162 		 * Try to add some target command resources
1163 		 */
1164 		MPT_LOCK(mpt);
1165 		if (mpt_add_target_commands(mpt) == FALSE) {
1166 			mpt_prt(mpt, "failed to add target commands\n");
1167 		}
1168 		MPT_UNLOCK(mpt);
1169 	}
1170 	mpt->ready = 1;
1171 }
1172 
1173 void
1174 mpt_cam_detach(struct mpt_softc *mpt)
1175 {
1176 	mpt_handler_t handler;
1177 
1178 	MPT_LOCK(mpt);
1179 	mpt->ready = 0;
1180 	mpt_terminate_recovery_thread(mpt);
1181 
1182 	handler.reply_handler = mpt_scsi_reply_handler;
1183 	mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1184 			       scsi_io_handler_id);
1185 	handler.reply_handler = mpt_scsi_tmf_reply_handler;
1186 	mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1187 			       scsi_tmf_handler_id);
1188 	handler.reply_handler = mpt_fc_els_reply_handler;
1189 	mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1190 			       fc_els_handler_id);
1191 	handler.reply_handler = mpt_scsi_tgt_reply_handler;
1192 	mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1193 			       mpt->scsi_tgt_handler_id);
1194 	handler.reply_handler = mpt_sata_pass_reply_handler;
1195 	mpt_deregister_handler(mpt, MPT_HANDLER_REPLY, handler,
1196 			       sata_pass_handler_id);
1197 
1198 	if (mpt->tmf_req != NULL) {
1199 		mpt->tmf_req->state = REQ_STATE_ALLOCATED;
1200 		mpt_free_request(mpt, mpt->tmf_req);
1201 		mpt->tmf_req = NULL;
1202 	}
1203 	if (mpt->sas_portinfo != NULL) {
1204 		free(mpt->sas_portinfo, M_DEVBUF);
1205 		mpt->sas_portinfo = NULL;
1206 	}
1207 	MPT_UNLOCK(mpt);
1208 
1209 	if (mpt->sim != NULL) {
1210 		xpt_free_path(mpt->path);
1211 		MPT_LOCK(mpt);
1212 		xpt_bus_deregister(cam_sim_path(mpt->sim));
1213 		MPT_UNLOCK(mpt);
1214 		cam_sim_free(mpt->sim, TRUE);
1215 		mpt->sim = NULL;
1216 	}
1217 
1218 	if (mpt->phydisk_sim != NULL) {
1219 		xpt_free_path(mpt->phydisk_path);
1220 		MPT_LOCK(mpt);
1221 		xpt_bus_deregister(cam_sim_path(mpt->phydisk_sim));
1222 		MPT_UNLOCK(mpt);
1223 		cam_sim_free(mpt->phydisk_sim, TRUE);
1224 		mpt->phydisk_sim = NULL;
1225 	}
1226 }
1227 
1228 /* This routine is used after a system crash to dump core onto the swap device.
1229  */
1230 static void
1231 mpt_poll(struct cam_sim *sim)
1232 {
1233 	struct mpt_softc *mpt;
1234 
1235 	mpt = (struct mpt_softc *)cam_sim_softc(sim);
1236 	mpt_intr(mpt);
1237 }
1238 
1239 /*
1240  * Watchdog timeout routine for SCSI requests.
1241  */
1242 static void
1243 mpt_timeout(void *arg)
1244 {
1245 	union ccb	 *ccb;
1246 	struct mpt_softc *mpt;
1247 	request_t	 *req;
1248 
1249 	ccb = (union ccb *)arg;
1250 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1251 
1252 #if __FreeBSD_version < 500000
1253 	MPT_LOCK(mpt);
1254 #endif
1255 	MPT_LOCK_ASSERT(mpt);
1256 	req = ccb->ccb_h.ccb_req_ptr;
1257 	mpt_prt(mpt, "request %p:%u timed out for ccb %p (req->ccb %p)\n", req,
1258 	    req->serno, ccb, req->ccb);
1259 /* XXX: WHAT ARE WE TRYING TO DO HERE? */
1260 	if ((req->state & REQ_STATE_QUEUED) == REQ_STATE_QUEUED) {
1261 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
1262 		TAILQ_INSERT_TAIL(&mpt->request_timeout_list, req, links);
1263 		req->state |= REQ_STATE_TIMEDOUT;
1264 		mpt_wakeup_recovery_thread(mpt);
1265 	}
1266 #if __FreeBSD_version < 500000
1267 	MPT_UNLOCK(mpt);
1268 #endif
1269 }
1270 
1271 /*
1272  * Callback routine from "bus_dmamap_load" or, in simple cases, called directly.
1273  *
1274  * Takes a list of physical segments and builds the SGL for SCSI IO command
1275  * and forwards the commard to the IOC after one last check that CAM has not
1276  * aborted the transaction.
1277  */
1278 static void
1279 mpt_execute_req_a64(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1280 {
1281 	request_t *req, *trq;
1282 	char *mpt_off;
1283 	union ccb *ccb;
1284 	struct mpt_softc *mpt;
1285 	int seg, first_lim;
1286 	uint32_t flags, nxt_off;
1287 	void *sglp = NULL;
1288 	MSG_REQUEST_HEADER *hdrp;
1289 	SGE_SIMPLE64 *se;
1290 	SGE_CHAIN64 *ce;
1291 	int istgt = 0;
1292 
1293 	req = (request_t *)arg;
1294 	ccb = req->ccb;
1295 
1296 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1297 	req = ccb->ccb_h.ccb_req_ptr;
1298 
1299 	hdrp = req->req_vbuf;
1300 	mpt_off = req->req_vbuf;
1301 
1302 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1303 		error = EFBIG;
1304 	}
1305 
1306 	if (error == 0) {
1307 		switch (hdrp->Function) {
1308 		case MPI_FUNCTION_SCSI_IO_REQUEST:
1309 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1310 			istgt = 0;
1311 			sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1312 			break;
1313 		case MPI_FUNCTION_TARGET_ASSIST:
1314 			istgt = 1;
1315 			sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1316 			break;
1317 		default:
1318 			mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req_a64\n",
1319 			    hdrp->Function);
1320 			error = EINVAL;
1321 			break;
1322 		}
1323 	}
1324 
1325 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1326 		error = EFBIG;
1327 		mpt_prt(mpt, "segment count %d too large (max %u)\n",
1328 		    nseg, mpt->max_seg_cnt);
1329 	}
1330 
1331 bad:
1332 	if (error != 0) {
1333 		if (error != EFBIG && error != ENOMEM) {
1334 			mpt_prt(mpt, "mpt_execute_req_a64: err %d\n", error);
1335 		}
1336 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1337 			cam_status status;
1338 			mpt_freeze_ccb(ccb);
1339 			if (error == EFBIG) {
1340 				status = CAM_REQ_TOO_BIG;
1341 			} else if (error == ENOMEM) {
1342 				if (mpt->outofbeer == 0) {
1343 					mpt->outofbeer = 1;
1344 					xpt_freeze_simq(mpt->sim, 1);
1345 					mpt_lprt(mpt, MPT_PRT_DEBUG,
1346 					    "FREEZEQ\n");
1347 				}
1348 				status = CAM_REQUEUE_REQ;
1349 			} else {
1350 				status = CAM_REQ_CMP_ERR;
1351 			}
1352 			mpt_set_ccb_status(ccb, status);
1353 		}
1354 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1355 			request_t *cmd_req =
1356 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1357 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1358 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1359 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1360 		}
1361 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1362 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1363 		xpt_done(ccb);
1364 		CAMLOCK_2_MPTLOCK(mpt);
1365 		mpt_free_request(mpt, req);
1366 		MPTLOCK_2_CAMLOCK(mpt);
1367 		return;
1368 	}
1369 
1370 	/*
1371 	 * No data to transfer?
1372 	 * Just make a single simple SGL with zero length.
1373 	 */
1374 
1375 	if (mpt->verbose >= MPT_PRT_DEBUG) {
1376 		int tidx = ((char *)sglp) - mpt_off;
1377 		memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1378 	}
1379 
1380 	if (nseg == 0) {
1381 		SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1382 		MPI_pSGE_SET_FLAGS(se1,
1383 		    (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1384 		    MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1385 		se1->FlagsLength = htole32(se1->FlagsLength);
1386 		goto out;
1387 	}
1388 
1389 
1390 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1391 	if (istgt == 0) {
1392 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1393 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1394 		}
1395 	} else {
1396 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1397 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1398 		}
1399 	}
1400 
1401 	if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1402 		bus_dmasync_op_t op;
1403 		if (istgt == 0) {
1404 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1405 				op = BUS_DMASYNC_PREREAD;
1406 			} else {
1407 				op = BUS_DMASYNC_PREWRITE;
1408 			}
1409 		} else {
1410 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1411 				op = BUS_DMASYNC_PREWRITE;
1412 			} else {
1413 				op = BUS_DMASYNC_PREREAD;
1414 			}
1415 		}
1416 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1417 	}
1418 
1419 	/*
1420 	 * Okay, fill in what we can at the end of the command frame.
1421 	 * If we have up to MPT_NSGL_FIRST, we can fit them all into
1422 	 * the command frame.
1423 	 *
1424 	 * Otherwise, we fill up through MPT_NSGL_FIRST less one
1425 	 * SIMPLE64 pointers and start doing CHAIN64 entries after
1426 	 * that.
1427 	 */
1428 
1429 	if (nseg < MPT_NSGL_FIRST(mpt)) {
1430 		first_lim = nseg;
1431 	} else {
1432 		/*
1433 		 * Leave room for CHAIN element
1434 		 */
1435 		first_lim = MPT_NSGL_FIRST(mpt) - 1;
1436 	}
1437 
1438 	se = (SGE_SIMPLE64 *) sglp;
1439 	for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1440 		uint32_t tf;
1441 
1442 		memset(se, 0, sizeof (*se));
1443 		se->Address.Low = htole32(dm_segs->ds_addr & 0xffffffff);
1444 		if (sizeof(bus_addr_t) > 4) {
1445 			se->Address.High =
1446 			    htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1447 		}
1448 		MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1449 		tf = flags;
1450 		if (seg == first_lim - 1) {
1451 			tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1452 		}
1453 		if (seg == nseg - 1) {
1454 			tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1455 				MPI_SGE_FLAGS_END_OF_BUFFER;
1456 		}
1457 		MPI_pSGE_SET_FLAGS(se, tf);
1458 		se->FlagsLength = htole32(se->FlagsLength);
1459 	}
1460 
1461 	if (seg == nseg) {
1462 		goto out;
1463 	}
1464 
1465 	/*
1466 	 * Tell the IOC where to find the first chain element.
1467 	 */
1468 	hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1469 	nxt_off = MPT_RQSL(mpt);
1470 	trq = req;
1471 
1472 	/*
1473 	 * Make up the rest of the data segments out of a chain element
1474 	 * (contiained in the current request frame) which points to
1475 	 * SIMPLE64 elements in the next request frame, possibly ending
1476 	 * with *another* chain element (if there's more).
1477 	 */
1478 	while (seg < nseg) {
1479 		int this_seg_lim;
1480 		uint32_t tf, cur_off;
1481 		bus_addr_t chain_list_addr;
1482 
1483 		/*
1484 		 * Point to the chain descriptor. Note that the chain
1485 		 * descriptor is at the end of the *previous* list (whether
1486 		 * chain or simple).
1487 		 */
1488 		ce = (SGE_CHAIN64 *) se;
1489 
1490 		/*
1491 		 * Before we change our current pointer, make  sure we won't
1492 		 * overflow the request area with this frame. Note that we
1493 		 * test against 'greater than' here as it's okay in this case
1494 		 * to have next offset be just outside the request area.
1495 		 */
1496 		if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1497 			nxt_off = MPT_REQUEST_AREA;
1498 			goto next_chain;
1499 		}
1500 
1501 		/*
1502 		 * Set our SGE element pointer to the beginning of the chain
1503 		 * list and update our next chain list offset.
1504 		 */
1505 		se = (SGE_SIMPLE64 *) &mpt_off[nxt_off];
1506 		cur_off = nxt_off;
1507 		nxt_off += MPT_RQSL(mpt);
1508 
1509 		/*
1510 		 * Now initialized the chain descriptor.
1511 		 */
1512 		memset(ce, 0, sizeof (*ce));
1513 
1514 		/*
1515 		 * Get the physical address of the chain list.
1516 		 */
1517 		chain_list_addr = trq->req_pbuf;
1518 		chain_list_addr += cur_off;
1519 		if (sizeof (bus_addr_t) > 4) {
1520 			ce->Address.High =
1521 			    htole32(((uint64_t)chain_list_addr) >> 32);
1522 		}
1523 		ce->Address.Low = htole32(chain_list_addr & 0xffffffff);
1524 		ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT |
1525 			    MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1526 
1527 		/*
1528 		 * If we have more than a frame's worth of segments left,
1529 		 * set up the chain list to have the last element be another
1530 		 * chain descriptor.
1531 		 */
1532 		if ((nseg - seg) > MPT_NSGL(mpt)) {
1533 			this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1534 			/*
1535 			 * The length of the chain is the length in bytes of the
1536 			 * number of segments plus the next chain element.
1537 			 *
1538 			 * The next chain descriptor offset is the length,
1539 			 * in words, of the number of segments.
1540 			 */
1541 			ce->Length = (this_seg_lim - seg) *
1542 			    sizeof (SGE_SIMPLE64);
1543 			ce->NextChainOffset = ce->Length >> 2;
1544 			ce->Length += sizeof (SGE_CHAIN64);
1545 		} else {
1546 			this_seg_lim = nseg;
1547 			ce->Length = (this_seg_lim - seg) *
1548 			    sizeof (SGE_SIMPLE64);
1549 		}
1550 		ce->Length = htole16(ce->Length);
1551 
1552 		/*
1553 		 * Fill in the chain list SGE elements with our segment data.
1554 		 *
1555 		 * If we're the last element in this chain list, set the last
1556 		 * element flag. If we're the completely last element period,
1557 		 * set the end of list and end of buffer flags.
1558 		 */
1559 		while (seg < this_seg_lim) {
1560 			memset(se, 0, sizeof (*se));
1561 			se->Address.Low = htole32(dm_segs->ds_addr &
1562 			    0xffffffff);
1563 			if (sizeof (bus_addr_t) > 4) {
1564 				se->Address.High =
1565 				    htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1566 			}
1567 			MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1568 			tf = flags;
1569 			if (seg ==  this_seg_lim - 1) {
1570 				tf |=	MPI_SGE_FLAGS_LAST_ELEMENT;
1571 			}
1572 			if (seg == nseg - 1) {
1573 				tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1574 					MPI_SGE_FLAGS_END_OF_BUFFER;
1575 			}
1576 			MPI_pSGE_SET_FLAGS(se, tf);
1577 			se->FlagsLength = htole32(se->FlagsLength);
1578 			se++;
1579 			seg++;
1580 			dm_segs++;
1581 		}
1582 
1583     next_chain:
1584 		/*
1585 		 * If we have more segments to do and we've used up all of
1586 		 * the space in a request area, go allocate another one
1587 		 * and chain to that.
1588 		 */
1589 		if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1590 			request_t *nrq;
1591 
1592 			CAMLOCK_2_MPTLOCK(mpt);
1593 			nrq = mpt_get_request(mpt, FALSE);
1594 			MPTLOCK_2_CAMLOCK(mpt);
1595 
1596 			if (nrq == NULL) {
1597 				error = ENOMEM;
1598 				goto bad;
1599 			}
1600 
1601 			/*
1602 			 * Append the new request area on the tail of our list.
1603 			 */
1604 			if ((trq = req->chain) == NULL) {
1605 				req->chain = nrq;
1606 			} else {
1607 				while (trq->chain != NULL) {
1608 					trq = trq->chain;
1609 				}
1610 				trq->chain = nrq;
1611 			}
1612 			trq = nrq;
1613 			mpt_off = trq->req_vbuf;
1614 			if (mpt->verbose >= MPT_PRT_DEBUG) {
1615 				memset(mpt_off, 0xff, MPT_REQUEST_AREA);
1616 			}
1617 			nxt_off = 0;
1618 		}
1619 	}
1620 out:
1621 
1622 	/*
1623 	 * Last time we need to check if this CCB needs to be aborted.
1624 	 */
1625 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
1626 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1627 			request_t *cmd_req =
1628 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1629 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1630 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1631 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1632 		}
1633 		mpt_prt(mpt,
1634 		    "mpt_execute_req_a64: I/O cancelled (status 0x%x)\n",
1635 		    ccb->ccb_h.status & CAM_STATUS_MASK);
1636 		if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
1637 			bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
1638 		}
1639 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1640 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1641 		xpt_done(ccb);
1642 		CAMLOCK_2_MPTLOCK(mpt);
1643 		mpt_free_request(mpt, req);
1644 		MPTLOCK_2_CAMLOCK(mpt);
1645 		return;
1646 	}
1647 
1648 	ccb->ccb_h.status |= CAM_SIM_QUEUED;
1649 	if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
1650 		mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
1651 		    mpt_timeout, ccb);
1652 	}
1653 	if (mpt->verbose > MPT_PRT_DEBUG) {
1654 		int nc = 0;
1655 		mpt_print_request(req->req_vbuf);
1656 		for (trq = req->chain; trq; trq = trq->chain) {
1657 			printf("  Additional Chain Area %d\n", nc++);
1658 			mpt_dump_sgl(trq->req_vbuf, 0);
1659 		}
1660 	}
1661 
1662 	if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1663 		request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1664 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
1665 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
1666 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1667 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
1668 			tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
1669 		} else {
1670 			tgt->state = TGT_STATE_MOVING_DATA;
1671 		}
1672 #else
1673 		tgt->state = TGT_STATE_MOVING_DATA;
1674 #endif
1675 	}
1676 	CAMLOCK_2_MPTLOCK(mpt);
1677 	mpt_send_cmd(mpt, req);
1678 	MPTLOCK_2_CAMLOCK(mpt);
1679 }
1680 
1681 static void
1682 mpt_execute_req(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1683 {
1684 	request_t *req, *trq;
1685 	char *mpt_off;
1686 	union ccb *ccb;
1687 	struct mpt_softc *mpt;
1688 	int seg, first_lim;
1689 	uint32_t flags, nxt_off;
1690 	void *sglp = NULL;
1691 	MSG_REQUEST_HEADER *hdrp;
1692 	SGE_SIMPLE32 *se;
1693 	SGE_CHAIN32 *ce;
1694 	int istgt = 0;
1695 
1696 	req = (request_t *)arg;
1697 	ccb = req->ccb;
1698 
1699 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1700 	req = ccb->ccb_h.ccb_req_ptr;
1701 
1702 	hdrp = req->req_vbuf;
1703 	mpt_off = req->req_vbuf;
1704 
1705 
1706 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1707 		error = EFBIG;
1708 	}
1709 
1710 	if (error == 0) {
1711 		switch (hdrp->Function) {
1712 		case MPI_FUNCTION_SCSI_IO_REQUEST:
1713 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1714 			sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1715 			break;
1716 		case MPI_FUNCTION_TARGET_ASSIST:
1717 			istgt = 1;
1718 			sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1719 			break;
1720 		default:
1721 			mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req\n",
1722 			    hdrp->Function);
1723 			error = EINVAL;
1724 			break;
1725 		}
1726 	}
1727 
1728 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1729 		error = EFBIG;
1730 		mpt_prt(mpt, "segment count %d too large (max %u)\n",
1731 		    nseg, mpt->max_seg_cnt);
1732 	}
1733 
1734 bad:
1735 	if (error != 0) {
1736 		if (error != EFBIG && error != ENOMEM) {
1737 			mpt_prt(mpt, "mpt_execute_req: err %d\n", error);
1738 		}
1739 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1740 			cam_status status;
1741 			mpt_freeze_ccb(ccb);
1742 			if (error == EFBIG) {
1743 				status = CAM_REQ_TOO_BIG;
1744 			} else if (error == ENOMEM) {
1745 				if (mpt->outofbeer == 0) {
1746 					mpt->outofbeer = 1;
1747 					xpt_freeze_simq(mpt->sim, 1);
1748 					mpt_lprt(mpt, MPT_PRT_DEBUG,
1749 					    "FREEZEQ\n");
1750 				}
1751 				status = CAM_REQUEUE_REQ;
1752 			} else {
1753 				status = CAM_REQ_CMP_ERR;
1754 			}
1755 			mpt_set_ccb_status(ccb, status);
1756 		}
1757 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1758 			request_t *cmd_req =
1759 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1760 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1761 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1762 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1763 		}
1764 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1765 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1766 		xpt_done(ccb);
1767 		CAMLOCK_2_MPTLOCK(mpt);
1768 		mpt_free_request(mpt, req);
1769 		MPTLOCK_2_CAMLOCK(mpt);
1770 		return;
1771 	}
1772 
1773 	/*
1774 	 * No data to transfer?
1775 	 * Just make a single simple SGL with zero length.
1776 	 */
1777 
1778 	if (mpt->verbose >= MPT_PRT_DEBUG) {
1779 		int tidx = ((char *)sglp) - mpt_off;
1780 		memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1781 	}
1782 
1783 	if (nseg == 0) {
1784 		SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1785 		MPI_pSGE_SET_FLAGS(se1,
1786 		    (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1787 		    MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1788 		se1->FlagsLength = htole32(se1->FlagsLength);
1789 		goto out;
1790 	}
1791 
1792 
1793 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
1794 	if (istgt == 0) {
1795 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1796 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1797 		}
1798 	} else {
1799 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1800 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1801 		}
1802 	}
1803 
1804 	if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1805 		bus_dmasync_op_t op;
1806 		if (istgt) {
1807 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1808 				op = BUS_DMASYNC_PREREAD;
1809 			} else {
1810 				op = BUS_DMASYNC_PREWRITE;
1811 			}
1812 		} else {
1813 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1814 				op = BUS_DMASYNC_PREWRITE;
1815 			} else {
1816 				op = BUS_DMASYNC_PREREAD;
1817 			}
1818 		}
1819 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1820 	}
1821 
1822 	/*
1823 	 * Okay, fill in what we can at the end of the command frame.
1824 	 * If we have up to MPT_NSGL_FIRST, we can fit them all into
1825 	 * the command frame.
1826 	 *
1827 	 * Otherwise, we fill up through MPT_NSGL_FIRST less one
1828 	 * SIMPLE32 pointers and start doing CHAIN32 entries after
1829 	 * that.
1830 	 */
1831 
1832 	if (nseg < MPT_NSGL_FIRST(mpt)) {
1833 		first_lim = nseg;
1834 	} else {
1835 		/*
1836 		 * Leave room for CHAIN element
1837 		 */
1838 		first_lim = MPT_NSGL_FIRST(mpt) - 1;
1839 	}
1840 
1841 	se = (SGE_SIMPLE32 *) sglp;
1842 	for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1843 		uint32_t tf;
1844 
1845 		memset(se, 0,sizeof (*se));
1846 		se->Address = htole32(dm_segs->ds_addr);
1847 
1848 
1849 
1850 		MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1851 		tf = flags;
1852 		if (seg == first_lim - 1) {
1853 			tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1854 		}
1855 		if (seg == nseg - 1) {
1856 			tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1857 				MPI_SGE_FLAGS_END_OF_BUFFER;
1858 		}
1859 		MPI_pSGE_SET_FLAGS(se, tf);
1860 		se->FlagsLength = htole32(se->FlagsLength);
1861 	}
1862 
1863 	if (seg == nseg) {
1864 		goto out;
1865 	}
1866 
1867 	/*
1868 	 * Tell the IOC where to find the first chain element.
1869 	 */
1870 	hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1871 	nxt_off = MPT_RQSL(mpt);
1872 	trq = req;
1873 
1874 	/*
1875 	 * Make up the rest of the data segments out of a chain element
1876 	 * (contiained in the current request frame) which points to
1877 	 * SIMPLE32 elements in the next request frame, possibly ending
1878 	 * with *another* chain element (if there's more).
1879 	 */
1880 	while (seg < nseg) {
1881 		int this_seg_lim;
1882 		uint32_t tf, cur_off;
1883 		bus_addr_t chain_list_addr;
1884 
1885 		/*
1886 		 * Point to the chain descriptor. Note that the chain
1887 		 * descriptor is at the end of the *previous* list (whether
1888 		 * chain or simple).
1889 		 */
1890 		ce = (SGE_CHAIN32 *) se;
1891 
1892 		/*
1893 		 * Before we change our current pointer, make  sure we won't
1894 		 * overflow the request area with this frame. Note that we
1895 		 * test against 'greater than' here as it's okay in this case
1896 		 * to have next offset be just outside the request area.
1897 		 */
1898 		if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1899 			nxt_off = MPT_REQUEST_AREA;
1900 			goto next_chain;
1901 		}
1902 
1903 		/*
1904 		 * Set our SGE element pointer to the beginning of the chain
1905 		 * list and update our next chain list offset.
1906 		 */
1907 		se = (SGE_SIMPLE32 *) &mpt_off[nxt_off];
1908 		cur_off = nxt_off;
1909 		nxt_off += MPT_RQSL(mpt);
1910 
1911 		/*
1912 		 * Now initialized the chain descriptor.
1913 		 */
1914 		memset(ce, 0, sizeof (*ce));
1915 
1916 		/*
1917 		 * Get the physical address of the chain list.
1918 		 */
1919 		chain_list_addr = trq->req_pbuf;
1920 		chain_list_addr += cur_off;
1921 
1922 
1923 
1924 		ce->Address = htole32(chain_list_addr);
1925 		ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT;
1926 
1927 
1928 		/*
1929 		 * If we have more than a frame's worth of segments left,
1930 		 * set up the chain list to have the last element be another
1931 		 * chain descriptor.
1932 		 */
1933 		if ((nseg - seg) > MPT_NSGL(mpt)) {
1934 			this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1935 			/*
1936 			 * The length of the chain is the length in bytes of the
1937 			 * number of segments plus the next chain element.
1938 			 *
1939 			 * The next chain descriptor offset is the length,
1940 			 * in words, of the number of segments.
1941 			 */
1942 			ce->Length = (this_seg_lim - seg) *
1943 			    sizeof (SGE_SIMPLE32);
1944 			ce->NextChainOffset = ce->Length >> 2;
1945 			ce->Length += sizeof (SGE_CHAIN32);
1946 		} else {
1947 			this_seg_lim = nseg;
1948 			ce->Length = (this_seg_lim - seg) *
1949 			    sizeof (SGE_SIMPLE32);
1950 		}
1951 		ce->Length = htole16(ce->Length);
1952 
1953 		/*
1954 		 * Fill in the chain list SGE elements with our segment data.
1955 		 *
1956 		 * If we're the last element in this chain list, set the last
1957 		 * element flag. If we're the completely last element period,
1958 		 * set the end of list and end of buffer flags.
1959 		 */
1960 		while (seg < this_seg_lim) {
1961 			memset(se, 0, sizeof (*se));
1962 			se->Address = htole32(dm_segs->ds_addr);
1963 
1964 
1965 
1966 
1967 			MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1968 			tf = flags;
1969 			if (seg ==  this_seg_lim - 1) {
1970 				tf |=	MPI_SGE_FLAGS_LAST_ELEMENT;
1971 			}
1972 			if (seg == nseg - 1) {
1973 				tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1974 					MPI_SGE_FLAGS_END_OF_BUFFER;
1975 			}
1976 			MPI_pSGE_SET_FLAGS(se, tf);
1977 			se->FlagsLength = htole32(se->FlagsLength);
1978 			se++;
1979 			seg++;
1980 			dm_segs++;
1981 		}
1982 
1983     next_chain:
1984 		/*
1985 		 * If we have more segments to do and we've used up all of
1986 		 * the space in a request area, go allocate another one
1987 		 * and chain to that.
1988 		 */
1989 		if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1990 			request_t *nrq;
1991 
1992 			CAMLOCK_2_MPTLOCK(mpt);
1993 			nrq = mpt_get_request(mpt, FALSE);
1994 			MPTLOCK_2_CAMLOCK(mpt);
1995 
1996 			if (nrq == NULL) {
1997 				error = ENOMEM;
1998 				goto bad;
1999 			}
2000 
2001 			/*
2002 			 * Append the new request area on the tail of our list.
2003 			 */
2004 			if ((trq = req->chain) == NULL) {
2005 				req->chain = nrq;
2006 			} else {
2007 				while (trq->chain != NULL) {
2008 					trq = trq->chain;
2009 				}
2010 				trq->chain = nrq;
2011 			}
2012 			trq = nrq;
2013 			mpt_off = trq->req_vbuf;
2014 			if (mpt->verbose >= MPT_PRT_DEBUG) {
2015 				memset(mpt_off, 0xff, MPT_REQUEST_AREA);
2016 			}
2017 			nxt_off = 0;
2018 		}
2019 	}
2020 out:
2021 
2022 	/*
2023 	 * Last time we need to check if this CCB needs to be aborted.
2024 	 */
2025 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2026 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2027 			request_t *cmd_req =
2028 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2029 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
2030 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
2031 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
2032 		}
2033 		mpt_prt(mpt,
2034 		    "mpt_execute_req: I/O cancelled (status 0x%x)\n",
2035 		    ccb->ccb_h.status & CAM_STATUS_MASK);
2036 		if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
2037 			bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2038 		}
2039 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2040 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2041 		xpt_done(ccb);
2042 		CAMLOCK_2_MPTLOCK(mpt);
2043 		mpt_free_request(mpt, req);
2044 		MPTLOCK_2_CAMLOCK(mpt);
2045 		return;
2046 	}
2047 
2048 	ccb->ccb_h.status |= CAM_SIM_QUEUED;
2049 	if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
2050 		mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
2051 		    mpt_timeout, ccb);
2052 	}
2053 	if (mpt->verbose > MPT_PRT_DEBUG) {
2054 		int nc = 0;
2055 		mpt_print_request(req->req_vbuf);
2056 		for (trq = req->chain; trq; trq = trq->chain) {
2057 			printf("  Additional Chain Area %d\n", nc++);
2058 			mpt_dump_sgl(trq->req_vbuf, 0);
2059 		}
2060 	}
2061 
2062 	if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2063 		request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2064 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
2065 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
2066 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
2067 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
2068 			tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
2069 		} else {
2070 			tgt->state = TGT_STATE_MOVING_DATA;
2071 		}
2072 #else
2073 		tgt->state = TGT_STATE_MOVING_DATA;
2074 #endif
2075 	}
2076 	CAMLOCK_2_MPTLOCK(mpt);
2077 	mpt_send_cmd(mpt, req);
2078 	MPTLOCK_2_CAMLOCK(mpt);
2079 }
2080 
2081 static void
2082 mpt_start(struct cam_sim *sim, union ccb *ccb)
2083 {
2084 	request_t *req;
2085 	struct mpt_softc *mpt;
2086 	MSG_SCSI_IO_REQUEST *mpt_req;
2087 	struct ccb_scsiio *csio = &ccb->csio;
2088 	struct ccb_hdr *ccbh = &ccb->ccb_h;
2089 	bus_dmamap_callback_t *cb;
2090 	target_id_t tgt;
2091 	int raid_passthru;
2092 
2093 	/* Get the pointer for the physical addapter */
2094 	mpt = ccb->ccb_h.ccb_mpt_ptr;
2095 	raid_passthru = (sim == mpt->phydisk_sim);
2096 
2097 	CAMLOCK_2_MPTLOCK(mpt);
2098 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
2099 		if (mpt->outofbeer == 0) {
2100 			mpt->outofbeer = 1;
2101 			xpt_freeze_simq(mpt->sim, 1);
2102 			mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
2103 		}
2104 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2105 		mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
2106 		MPTLOCK_2_CAMLOCK(mpt);
2107 		xpt_done(ccb);
2108 		return;
2109 	}
2110 #ifdef	INVARIANTS
2111 	mpt_req_not_spcl(mpt, req, "mpt_start", __LINE__);
2112 #endif
2113 	MPTLOCK_2_CAMLOCK(mpt);
2114 
2115 	if (sizeof (bus_addr_t) > 4) {
2116 		cb = mpt_execute_req_a64;
2117 	} else {
2118 		cb = mpt_execute_req;
2119 	}
2120 
2121 	/*
2122 	 * Link the ccb and the request structure so we can find
2123 	 * the other knowing either the request or the ccb
2124 	 */
2125 	req->ccb = ccb;
2126 	ccb->ccb_h.ccb_req_ptr = req;
2127 
2128 	/* Now we build the command for the IOC */
2129 	mpt_req = req->req_vbuf;
2130 	memset(mpt_req, 0, sizeof (MSG_SCSI_IO_REQUEST));
2131 
2132 	mpt_req->Function = MPI_FUNCTION_SCSI_IO_REQUEST;
2133 	if (raid_passthru) {
2134 		mpt_req->Function = MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH;
2135 		CAMLOCK_2_MPTLOCK(mpt);
2136 		if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
2137 			MPTLOCK_2_CAMLOCK(mpt);
2138 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2139 			mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
2140 			xpt_done(ccb);
2141 			return;
2142 		}
2143 		MPTLOCK_2_CAMLOCK(mpt);
2144 		mpt_req->Bus = 0;	/* we never set bus here */
2145 	} else {
2146 		tgt = ccb->ccb_h.target_id;
2147 		mpt_req->Bus = 0;	/* XXX */
2148 
2149 	}
2150 	mpt_req->SenseBufferLength =
2151 		(csio->sense_len < MPT_SENSE_SIZE) ?
2152 		 csio->sense_len : MPT_SENSE_SIZE;
2153 
2154 	/*
2155 	 * We use the message context to find the request structure when we
2156 	 * Get the command completion interrupt from the IOC.
2157 	 */
2158 	mpt_req->MsgContext = htole32(req->index | scsi_io_handler_id);
2159 
2160 	/* Which physical device to do the I/O on */
2161 	mpt_req->TargetID = tgt;
2162 
2163 	/* We assume a single level LUN type */
2164 	if (ccb->ccb_h.target_lun >= MPT_MAX_LUNS) {
2165 		mpt_req->LUN[0] = 0x40 | ((ccb->ccb_h.target_lun >> 8) & 0x3f);
2166 		mpt_req->LUN[1] = ccb->ccb_h.target_lun & 0xff;
2167 	} else {
2168 		mpt_req->LUN[1] = ccb->ccb_h.target_lun;
2169 	}
2170 
2171 	/* Set the direction of the transfer */
2172 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2173 		mpt_req->Control = MPI_SCSIIO_CONTROL_READ;
2174 	} else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2175 		mpt_req->Control = MPI_SCSIIO_CONTROL_WRITE;
2176 	} else {
2177 		mpt_req->Control = MPI_SCSIIO_CONTROL_NODATATRANSFER;
2178 	}
2179 
2180 	if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
2181 		switch(ccb->csio.tag_action) {
2182 		case MSG_HEAD_OF_Q_TAG:
2183 			mpt_req->Control |= MPI_SCSIIO_CONTROL_HEADOFQ;
2184 			break;
2185 		case MSG_ACA_TASK:
2186 			mpt_req->Control |= MPI_SCSIIO_CONTROL_ACAQ;
2187 			break;
2188 		case MSG_ORDERED_Q_TAG:
2189 			mpt_req->Control |= MPI_SCSIIO_CONTROL_ORDEREDQ;
2190 			break;
2191 		case MSG_SIMPLE_Q_TAG:
2192 		default:
2193 			mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2194 			break;
2195 		}
2196 	} else {
2197 		if (mpt->is_fc || mpt->is_sas) {
2198 			mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2199 		} else {
2200 			/* XXX No such thing for a target doing packetized. */
2201 			mpt_req->Control |= MPI_SCSIIO_CONTROL_UNTAGGED;
2202 		}
2203 	}
2204 
2205 	if (mpt->is_spi) {
2206 		if (ccb->ccb_h.flags & CAM_DIS_DISCONNECT) {
2207 			mpt_req->Control |= MPI_SCSIIO_CONTROL_NO_DISCONNECT;
2208 		}
2209 	}
2210 	mpt_req->Control = htole32(mpt_req->Control);
2211 
2212 	/* Copy the scsi command block into place */
2213 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
2214 		bcopy(csio->cdb_io.cdb_ptr, mpt_req->CDB, csio->cdb_len);
2215 	} else {
2216 		bcopy(csio->cdb_io.cdb_bytes, mpt_req->CDB, csio->cdb_len);
2217 	}
2218 
2219 	mpt_req->CDBLength = csio->cdb_len;
2220 	mpt_req->DataLength = htole32(csio->dxfer_len);
2221 	mpt_req->SenseBufferLowAddr = htole32(req->sense_pbuf);
2222 
2223 	/*
2224 	 * Do a *short* print here if we're set to MPT_PRT_DEBUG
2225 	 */
2226 	if (mpt->verbose == MPT_PRT_DEBUG) {
2227 		U32 df;
2228 		mpt_prt(mpt, "mpt_start: %s op 0x%x ",
2229 		    (mpt_req->Function == MPI_FUNCTION_SCSI_IO_REQUEST)?
2230 		    "SCSI_IO_REQUEST" : "SCSI_IO_PASSTHRU", mpt_req->CDB[0]);
2231 		df = mpt_req->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK;
2232 		if (df != MPI_SCSIIO_CONTROL_NODATATRANSFER) {
2233 			mpt_prtc(mpt, "(%s %u byte%s ",
2234 			    (df == MPI_SCSIIO_CONTROL_READ)?
2235 			    "read" : "write",  csio->dxfer_len,
2236 			    (csio->dxfer_len == 1)? ")" : "s)");
2237 		}
2238 		mpt_prtc(mpt, "tgt %u lun %u req %p:%u\n", tgt,
2239 		    ccb->ccb_h.target_lun, req, req->serno);
2240 	}
2241 
2242 	/*
2243 	 * If we have any data to send with this command map it into bus space.
2244 	 */
2245 	if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2246 		if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
2247 			/*
2248 			 * We've been given a pointer to a single buffer.
2249 			 */
2250 			if ((ccbh->flags & CAM_DATA_PHYS) == 0) {
2251 				/*
2252 				 * Virtual address that needs to translated into
2253 				 * one or more physical address ranges.
2254 				 */
2255 				int error;
2256 				int s = splsoftvm();
2257 				error = bus_dmamap_load(mpt->buffer_dmat,
2258 				    req->dmap, csio->data_ptr, csio->dxfer_len,
2259 				    cb, req, 0);
2260 				splx(s);
2261 				if (error == EINPROGRESS) {
2262 					/*
2263 					 * So as to maintain ordering,
2264 					 * freeze the controller queue
2265 					 * until our mapping is
2266 					 * returned.
2267 					 */
2268 					xpt_freeze_simq(mpt->sim, 1);
2269 					ccbh->status |= CAM_RELEASE_SIMQ;
2270 				}
2271 			} else {
2272 				/*
2273 				 * We have been given a pointer to single
2274 				 * physical buffer.
2275 				 */
2276 				struct bus_dma_segment seg;
2277 				seg.ds_addr =
2278 				    (bus_addr_t)(vm_offset_t)csio->data_ptr;
2279 				seg.ds_len = csio->dxfer_len;
2280 				(*cb)(req, &seg, 1, 0);
2281 			}
2282 		} else {
2283 			/*
2284 			 * We have been given a list of addresses.
2285 			 * This case could be easily supported but they are not
2286 			 * currently generated by the CAM subsystem so there
2287 			 * is no point in wasting the time right now.
2288 			 */
2289 			struct bus_dma_segment *segs;
2290 			if ((ccbh->flags & CAM_SG_LIST_PHYS) == 0) {
2291 				(*cb)(req, NULL, 0, EFAULT);
2292 			} else {
2293 				/* Just use the segments provided */
2294 				segs = (struct bus_dma_segment *)csio->data_ptr;
2295 				(*cb)(req, segs, csio->sglist_cnt, 0);
2296 			}
2297 		}
2298 	} else {
2299 		(*cb)(req, NULL, 0, 0);
2300 	}
2301 }
2302 
2303 static int
2304 mpt_bus_reset(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun,
2305     int sleep_ok)
2306 {
2307 	int   error;
2308 	uint16_t status;
2309 	uint8_t response;
2310 
2311 	error = mpt_scsi_send_tmf(mpt,
2312 	    (tgt != CAM_TARGET_WILDCARD || lun != CAM_LUN_WILDCARD) ?
2313 	    MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET :
2314 	    MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
2315 	    mpt->is_fc ? MPI_SCSITASKMGMT_MSGFLAGS_LIP_RESET_OPTION : 0,
2316 	    0,	/* XXX How do I get the channel ID? */
2317 	    tgt != CAM_TARGET_WILDCARD ? tgt : 0,
2318 	    lun != CAM_LUN_WILDCARD ? lun : 0,
2319 	    0, sleep_ok);
2320 
2321 	if (error != 0) {
2322 		/*
2323 		 * mpt_scsi_send_tmf hard resets on failure, so no
2324 		 * need to do so here.
2325 		 */
2326 		mpt_prt(mpt,
2327 		    "mpt_bus_reset: mpt_scsi_send_tmf returned %d\n", error);
2328 		return (EIO);
2329 	}
2330 
2331 	/* Wait for bus reset to be processed by the IOC. */
2332 	error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
2333 	    REQ_STATE_DONE, sleep_ok, 5000);
2334 
2335 	status = le16toh(mpt->tmf_req->IOCStatus);
2336 	response = mpt->tmf_req->ResponseCode;
2337 	mpt->tmf_req->state = REQ_STATE_FREE;
2338 
2339 	if (error) {
2340 		mpt_prt(mpt, "mpt_bus_reset: Reset timed-out. "
2341 		    "Resetting controller.\n");
2342 		mpt_reset(mpt, TRUE);
2343 		return (ETIMEDOUT);
2344 	}
2345 
2346 	if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
2347 		mpt_prt(mpt, "mpt_bus_reset: TMF IOC Status 0x%x. "
2348 		    "Resetting controller.\n", status);
2349 		mpt_reset(mpt, TRUE);
2350 		return (EIO);
2351 	}
2352 
2353 	if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
2354 	    response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
2355 		mpt_prt(mpt, "mpt_bus_reset: TMF Response 0x%x. "
2356 		    "Resetting controller.\n", response);
2357 		mpt_reset(mpt, TRUE);
2358 		return (EIO);
2359 	}
2360 	return (0);
2361 }
2362 
2363 static int
2364 mpt_fc_reset_link(struct mpt_softc *mpt, int dowait)
2365 {
2366 	int r = 0;
2367 	request_t *req;
2368 	PTR_MSG_FC_PRIMITIVE_SEND_REQUEST fc;
2369 
2370  	req = mpt_get_request(mpt, FALSE);
2371 	if (req == NULL) {
2372 		return (ENOMEM);
2373 	}
2374 	fc = req->req_vbuf;
2375 	memset(fc, 0, sizeof(*fc));
2376 	fc->SendFlags = MPI_FC_PRIM_SEND_FLAGS_RESET_LINK;
2377 	fc->Function = MPI_FUNCTION_FC_PRIMITIVE_SEND;
2378 	fc->MsgContext = htole32(req->index | fc_els_handler_id);
2379 	mpt_send_cmd(mpt, req);
2380 	if (dowait) {
2381 		r = mpt_wait_req(mpt, req, REQ_STATE_DONE,
2382 		    REQ_STATE_DONE, FALSE, 60 * 1000);
2383 		if (r == 0) {
2384 			mpt_free_request(mpt, req);
2385 		}
2386 	}
2387 	return (r);
2388 }
2389 
2390 static int
2391 mpt_cam_event(struct mpt_softc *mpt, request_t *req,
2392 	      MSG_EVENT_NOTIFY_REPLY *msg)
2393 {
2394 	uint32_t data0, data1;
2395 
2396 	data0 = le32toh(msg->Data[0]);
2397 	data1 = le32toh(msg->Data[1]);
2398 	switch(msg->Event & 0xFF) {
2399 	case MPI_EVENT_UNIT_ATTENTION:
2400 		mpt_prt(mpt, "UNIT ATTENTION: Bus: 0x%02x TargetID: 0x%02x\n",
2401 		    (data0 >> 8) & 0xff, data0 & 0xff);
2402 		break;
2403 
2404 	case MPI_EVENT_IOC_BUS_RESET:
2405 		/* We generated a bus reset */
2406 		mpt_prt(mpt, "IOC Generated Bus Reset Port: %d\n",
2407 		    (data0 >> 8) & 0xff);
2408 		xpt_async(AC_BUS_RESET, mpt->path, NULL);
2409 		break;
2410 
2411 	case MPI_EVENT_EXT_BUS_RESET:
2412 		/* Someone else generated a bus reset */
2413 		mpt_prt(mpt, "External Bus Reset Detected\n");
2414 		/*
2415 		 * These replies don't return EventData like the MPI
2416 		 * spec says they do
2417 		 */
2418 		xpt_async(AC_BUS_RESET, mpt->path, NULL);
2419 		break;
2420 
2421 	case MPI_EVENT_RESCAN:
2422 #if __FreeBSD_version >= 600000
2423 	{
2424 		union ccb *ccb;
2425 		uint32_t pathid;
2426 		/*
2427 		 * In general this means a device has been added to the loop.
2428 		 */
2429 		mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2430 		if (mpt->ready == 0) {
2431 			break;
2432 		}
2433 		if (mpt->phydisk_sim) {
2434 			pathid = cam_sim_path(mpt->phydisk_sim);
2435 		} else {
2436 			pathid = cam_sim_path(mpt->sim);
2437 		}
2438 		MPTLOCK_2_CAMLOCK(mpt);
2439 		/*
2440 		 * Allocate a CCB, create a wildcard path for this bus,
2441 		 * and schedule a rescan.
2442 		 */
2443 		ccb = xpt_alloc_ccb_nowait();
2444 		if (ccb == NULL) {
2445 			mpt_prt(mpt, "unable to alloc CCB for rescan\n");
2446 			CAMLOCK_2_MPTLOCK(mpt);
2447 			break;
2448 		}
2449 
2450 		if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, pathid,
2451 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2452 			CAMLOCK_2_MPTLOCK(mpt);
2453 			mpt_prt(mpt, "unable to create path for rescan\n");
2454 			xpt_free_ccb(ccb);
2455 			break;
2456 		}
2457 		xpt_rescan(ccb);
2458 		CAMLOCK_2_MPTLOCK(mpt);
2459 		break;
2460 	}
2461 #else
2462 		mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2463 		break;
2464 #endif
2465 	case MPI_EVENT_LINK_STATUS_CHANGE:
2466 		mpt_prt(mpt, "Port %d: LinkState: %s\n",
2467 		    (data1 >> 8) & 0xff,
2468 		    ((data0 & 0xff) == 0)?  "Failed" : "Active");
2469 		break;
2470 
2471 	case MPI_EVENT_LOOP_STATE_CHANGE:
2472 		switch ((data0 >> 16) & 0xff) {
2473 		case 0x01:
2474 			mpt_prt(mpt,
2475 			    "Port 0x%x: FC LinkEvent: LIP(%02x,%02x) "
2476 			    "(Loop Initialization)\n",
2477 			    (data1 >> 8) & 0xff,
2478 			    (data0 >> 8) & 0xff,
2479 			    (data0     ) & 0xff);
2480 			switch ((data0 >> 8) & 0xff) {
2481 			case 0xF7:
2482 				if ((data0 & 0xff) == 0xF7) {
2483 					mpt_prt(mpt, "Device needs AL_PA\n");
2484 				} else {
2485 					mpt_prt(mpt, "Device %02x doesn't like "
2486 					    "FC performance\n",
2487 					    data0 & 0xFF);
2488 				}
2489 				break;
2490 			case 0xF8:
2491 				if ((data0 & 0xff) == 0xF7) {
2492 					mpt_prt(mpt, "Device had loop failure "
2493 					    "at its receiver prior to acquiring"
2494 					    " AL_PA\n");
2495 				} else {
2496 					mpt_prt(mpt, "Device %02x detected loop"
2497 					    " failure at its receiver\n",
2498 					    data0 & 0xFF);
2499 				}
2500 				break;
2501 			default:
2502 				mpt_prt(mpt, "Device %02x requests that device "
2503 				    "%02x reset itself\n",
2504 				    data0 & 0xFF,
2505 				    (data0 >> 8) & 0xFF);
2506 				break;
2507 			}
2508 			break;
2509 		case 0x02:
2510 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2511 			    "LPE(%02x,%02x) (Loop Port Enable)\n",
2512 			    (data1 >> 8) & 0xff, /* Port */
2513 			    (data0 >>  8) & 0xff, /* Character 3 */
2514 			    (data0      ) & 0xff  /* Character 4 */);
2515 			break;
2516 		case 0x03:
2517 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2518 			    "LPB(%02x,%02x) (Loop Port Bypass)\n",
2519 			    (data1 >> 8) & 0xff, /* Port */
2520 			    (data0 >> 8) & 0xff, /* Character 3 */
2521 			    (data0     ) & 0xff  /* Character 4 */);
2522 			break;
2523 		default:
2524 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: Unknown "
2525 			    "FC event (%02x %02x %02x)\n",
2526 			    (data1 >> 8) & 0xff, /* Port */
2527 			    (data0 >> 16) & 0xff, /* Event */
2528 			    (data0 >>  8) & 0xff, /* Character 3 */
2529 			    (data0      ) & 0xff  /* Character 4 */);
2530 		}
2531 		break;
2532 
2533 	case MPI_EVENT_LOGOUT:
2534 		mpt_prt(mpt, "FC Logout Port: %d N_PortID: %02x\n",
2535 		    (data1 >> 8) & 0xff, data0);
2536 		break;
2537 	case MPI_EVENT_QUEUE_FULL:
2538 	{
2539 		struct cam_sim *sim;
2540 		struct cam_path *tmppath;
2541 		struct ccb_relsim crs;
2542 		PTR_EVENT_DATA_QUEUE_FULL pqf;
2543 		lun_id_t lun_id;
2544 
2545 		pqf = (PTR_EVENT_DATA_QUEUE_FULL)msg->Data;
2546 		pqf->CurrentDepth = le16toh(pqf->CurrentDepth);
2547 		mpt_prt(mpt, "QUEUE FULL EVENT: Bus 0x%02x Target 0x%02x Depth "
2548 		    "%d\n", pqf->Bus, pqf->TargetID, pqf->CurrentDepth);
2549 		if (mpt->phydisk_sim) {
2550 			sim = mpt->phydisk_sim;
2551 		} else {
2552 			sim = mpt->sim;
2553 		}
2554 		MPTLOCK_2_CAMLOCK(mpt);
2555 		for (lun_id = 0; lun_id < MPT_MAX_LUNS; lun_id++) {
2556 			if (xpt_create_path(&tmppath, NULL, cam_sim_path(sim),
2557 			    pqf->TargetID, lun_id) != CAM_REQ_CMP) {
2558 				mpt_prt(mpt, "unable to create a path to send "
2559 				    "XPT_REL_SIMQ");
2560 				CAMLOCK_2_MPTLOCK(mpt);
2561 				break;
2562 			}
2563 			xpt_setup_ccb(&crs.ccb_h, tmppath, 5);
2564 			crs.ccb_h.func_code = XPT_REL_SIMQ;
2565 			crs.ccb_h.flags = CAM_DEV_QFREEZE;
2566 			crs.release_flags = RELSIM_ADJUST_OPENINGS;
2567 			crs.openings = pqf->CurrentDepth - 1;
2568 			xpt_action((union ccb *)&crs);
2569 			if (crs.ccb_h.status != CAM_REQ_CMP) {
2570 				mpt_prt(mpt, "XPT_REL_SIMQ failed\n");
2571 			}
2572 			xpt_free_path(tmppath);
2573 		}
2574 		CAMLOCK_2_MPTLOCK(mpt);
2575 		break;
2576 	}
2577 	case MPI_EVENT_EVENT_CHANGE:
2578 	case MPI_EVENT_INTEGRATED_RAID:
2579 	case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
2580 	case MPI_EVENT_SAS_SES:
2581 		break;
2582 	default:
2583 		mpt_lprt(mpt, MPT_PRT_WARN, "mpt_cam_event: 0x%x\n",
2584 		    msg->Event & 0xFF);
2585 		return (0);
2586 	}
2587 	return (1);
2588 }
2589 
2590 /*
2591  * Reply path for all SCSI I/O requests, called from our
2592  * interrupt handler by extracting our handler index from
2593  * the MsgContext field of the reply from the IOC.
2594  *
2595  * This routine is optimized for the common case of a
2596  * completion without error.  All exception handling is
2597  * offloaded to non-inlined helper routines to minimize
2598  * cache footprint.
2599  */
2600 static int
2601 mpt_scsi_reply_handler(struct mpt_softc *mpt, request_t *req,
2602     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2603 {
2604 	MSG_SCSI_IO_REQUEST *scsi_req;
2605 	union ccb *ccb;
2606 
2607 	if (req->state == REQ_STATE_FREE) {
2608 		mpt_prt(mpt, "mpt_scsi_reply_handler: req already free\n");
2609 		return (TRUE);
2610 	}
2611 
2612 	scsi_req = (MSG_SCSI_IO_REQUEST *)req->req_vbuf;
2613 	ccb = req->ccb;
2614 	if (ccb == NULL) {
2615 		mpt_prt(mpt, "mpt_scsi_reply_handler: req %p:%u with no ccb\n",
2616 		    req, req->serno);
2617 		return (TRUE);
2618 	}
2619 
2620 	mpt_req_untimeout(req, mpt_timeout, ccb);
2621 	ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2622 
2623 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2624 		bus_dmasync_op_t op;
2625 
2626 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
2627 			op = BUS_DMASYNC_POSTREAD;
2628 		else
2629 			op = BUS_DMASYNC_POSTWRITE;
2630 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
2631 		bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2632 	}
2633 
2634 	if (reply_frame == NULL) {
2635 		/*
2636 		 * Context only reply, completion without error status.
2637 		 */
2638 		ccb->csio.resid = 0;
2639 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
2640 		ccb->csio.scsi_status = SCSI_STATUS_OK;
2641 	} else {
2642 		mpt_scsi_reply_frame_handler(mpt, req, reply_frame);
2643 	}
2644 
2645 	if (mpt->outofbeer) {
2646 		ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2647 		mpt->outofbeer = 0;
2648 		mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
2649 	}
2650 	if (scsi_req->CDB[0] == INQUIRY && (scsi_req->CDB[1] & SI_EVPD) == 0) {
2651 		struct scsi_inquiry_data *iq =
2652 		    (struct scsi_inquiry_data *)ccb->csio.data_ptr;
2653 		if (scsi_req->Function ==
2654 		    MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH) {
2655 			/*
2656 			 * Fake out the device type so that only the
2657 			 * pass-thru device will attach.
2658 			 */
2659 			iq->device &= ~0x1F;
2660 			iq->device |= T_NODEVICE;
2661 		}
2662 	}
2663 	if (mpt->verbose == MPT_PRT_DEBUG) {
2664 		mpt_prt(mpt, "mpt_scsi_reply_handler: %p:%u complete\n",
2665 		    req, req->serno);
2666 	}
2667 	KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2668 	MPTLOCK_2_CAMLOCK(mpt);
2669 	xpt_done(ccb);
2670 	CAMLOCK_2_MPTLOCK(mpt);
2671 	if ((req->state & REQ_STATE_TIMEDOUT) == 0) {
2672 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2673 	} else {
2674 		mpt_prt(mpt, "completing timedout/aborted req %p:%u\n",
2675 		    req, req->serno);
2676 		TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
2677 	}
2678 	KASSERT((req->state & REQ_STATE_NEED_WAKEUP) == 0,
2679 	    ("CCB req needed wakeup"));
2680 #ifdef	INVARIANTS
2681 	mpt_req_not_spcl(mpt, req, "mpt_scsi_reply_handler", __LINE__);
2682 #endif
2683 	mpt_free_request(mpt, req);
2684 	return (TRUE);
2685 }
2686 
2687 static int
2688 mpt_scsi_tmf_reply_handler(struct mpt_softc *mpt, request_t *req,
2689     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2690 {
2691 	MSG_SCSI_TASK_MGMT_REPLY *tmf_reply;
2692 
2693 	KASSERT(req == mpt->tmf_req, ("TMF Reply not using mpt->tmf_req"));
2694 #ifdef	INVARIANTS
2695 	mpt_req_not_spcl(mpt, req, "mpt_scsi_tmf_reply_handler", __LINE__);
2696 #endif
2697 	tmf_reply = (MSG_SCSI_TASK_MGMT_REPLY *)reply_frame;
2698 	/* Record IOC Status and Response Code of TMF for any waiters. */
2699 	req->IOCStatus = le16toh(tmf_reply->IOCStatus);
2700 	req->ResponseCode = tmf_reply->ResponseCode;
2701 
2702 	mpt_lprt(mpt, MPT_PRT_DEBUG, "TMF complete: req %p:%u status 0x%x\n",
2703 	    req, req->serno, le16toh(tmf_reply->IOCStatus));
2704 	TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2705 	if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
2706 		req->state |= REQ_STATE_DONE;
2707 		wakeup(req);
2708 	} else {
2709 		mpt->tmf_req->state = REQ_STATE_FREE;
2710 	}
2711 	return (TRUE);
2712 }
2713 
2714 /*
2715  * XXX: Move to definitions file
2716  */
2717 #define	ELS	0x22
2718 #define	FC4LS	0x32
2719 #define	ABTS	0x81
2720 #define	BA_ACC	0x84
2721 
2722 #define	LS_RJT	0x01
2723 #define	LS_ACC	0x02
2724 #define	PLOGI	0x03
2725 #define	LOGO	0x05
2726 #define SRR	0x14
2727 #define PRLI	0x20
2728 #define PRLO	0x21
2729 #define ADISC	0x52
2730 #define RSCN	0x61
2731 
2732 static void
2733 mpt_fc_els_send_response(struct mpt_softc *mpt, request_t *req,
2734     PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp, U8 length)
2735 {
2736 	uint32_t fl;
2737 	MSG_LINK_SERVICE_RSP_REQUEST tmp;
2738 	PTR_MSG_LINK_SERVICE_RSP_REQUEST rsp;
2739 
2740 	/*
2741 	 * We are going to reuse the ELS request to send this response back.
2742 	 */
2743 	rsp = &tmp;
2744 	memset(rsp, 0, sizeof(*rsp));
2745 
2746 #ifdef	USE_IMMEDIATE_LINK_DATA
2747 	/*
2748 	 * Apparently the IMMEDIATE stuff doesn't seem to work.
2749 	 */
2750 	rsp->RspFlags = LINK_SERVICE_RSP_FLAGS_IMMEDIATE;
2751 #endif
2752 	rsp->RspLength = length;
2753 	rsp->Function = MPI_FUNCTION_FC_LINK_SRVC_RSP;
2754 	rsp->MsgContext = htole32(req->index | fc_els_handler_id);
2755 
2756 	/*
2757 	 * Copy over information from the original reply frame to
2758 	 * it's correct place in the response.
2759 	 */
2760 	memcpy((U8 *)rsp + 0x0c, (U8 *)rp + 0x1c, 24);
2761 
2762 	/*
2763 	 * And now copy back the temporary area to the original frame.
2764 	 */
2765 	memcpy(req->req_vbuf, rsp, sizeof (MSG_LINK_SERVICE_RSP_REQUEST));
2766 	rsp = req->req_vbuf;
2767 
2768 #ifdef	USE_IMMEDIATE_LINK_DATA
2769 	memcpy((U8 *)&rsp->SGL, &((U8 *)req->req_vbuf)[MPT_RQSL(mpt)], length);
2770 #else
2771 {
2772 	PTR_SGE_SIMPLE32 se = (PTR_SGE_SIMPLE32) &rsp->SGL;
2773 	bus_addr_t paddr = req->req_pbuf;
2774 	paddr += MPT_RQSL(mpt);
2775 
2776 	fl =
2777 		MPI_SGE_FLAGS_HOST_TO_IOC	|
2778 		MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
2779 		MPI_SGE_FLAGS_LAST_ELEMENT	|
2780 		MPI_SGE_FLAGS_END_OF_LIST	|
2781 		MPI_SGE_FLAGS_END_OF_BUFFER;
2782 	fl <<= MPI_SGE_FLAGS_SHIFT;
2783 	fl |= (length);
2784 	se->FlagsLength = htole32(fl);
2785 	se->Address = htole32((uint32_t) paddr);
2786 }
2787 #endif
2788 
2789 	/*
2790 	 * Send it on...
2791 	 */
2792 	mpt_send_cmd(mpt, req);
2793 }
2794 
2795 static int
2796 mpt_fc_els_reply_handler(struct mpt_softc *mpt, request_t *req,
2797     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2798 {
2799 	PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp =
2800 	    (PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY) reply_frame;
2801 	U8 rctl;
2802 	U8 type;
2803 	U8 cmd;
2804 	U16 status = le16toh(reply_frame->IOCStatus);
2805 	U32 *elsbuf;
2806 	int ioindex;
2807 	int do_refresh = TRUE;
2808 
2809 #ifdef	INVARIANTS
2810 	KASSERT(mpt_req_on_free_list(mpt, req) == 0,
2811 	    ("fc_els_reply_handler: req %p:%u for function %x on freelist!",
2812 	    req, req->serno, rp->Function));
2813 	if (rp->Function != MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2814 		mpt_req_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2815 	} else {
2816 		mpt_req_not_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2817 	}
2818 #endif
2819 	mpt_lprt(mpt, MPT_PRT_DEBUG,
2820 	    "FC_ELS Complete: req %p:%u, reply %p function %x\n",
2821 	    req, req->serno, reply_frame, reply_frame->Function);
2822 
2823 	if  (status != MPI_IOCSTATUS_SUCCESS) {
2824 		mpt_prt(mpt, "ELS REPLY STATUS 0x%x for Function %x\n",
2825 		    status, reply_frame->Function);
2826 		if (status == MPI_IOCSTATUS_INVALID_STATE) {
2827 			/*
2828 			 * XXX: to get around shutdown issue
2829 			 */
2830 			mpt->disabled = 1;
2831 			return (TRUE);
2832 		}
2833 		return (TRUE);
2834 	}
2835 
2836 	/*
2837 	 * If the function of a link service response, we recycle the
2838 	 * response to be a refresh for a new link service request.
2839 	 *
2840 	 * The request pointer is bogus in this case and we have to fetch
2841 	 * it based upon the TransactionContext.
2842 	 */
2843 	if (rp->Function == MPI_FUNCTION_FC_LINK_SRVC_RSP) {
2844 		/* Freddie Uncle Charlie Katie */
2845 		/* We don't get the IOINDEX as part of the Link Svc Rsp */
2846 		for (ioindex = 0; ioindex < mpt->els_cmds_allocated; ioindex++)
2847 			if (mpt->els_cmd_ptrs[ioindex] == req) {
2848 				break;
2849 			}
2850 
2851 		KASSERT(ioindex < mpt->els_cmds_allocated,
2852 		    ("can't find my mommie!"));
2853 
2854 		/* remove from active list as we're going to re-post it */
2855 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2856 		req->state &= ~REQ_STATE_QUEUED;
2857 		req->state |= REQ_STATE_DONE;
2858 		mpt_fc_post_els(mpt, req, ioindex);
2859 		return (TRUE);
2860 	}
2861 
2862 	if (rp->Function == MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2863 		/* remove from active list as we're done */
2864 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2865 		req->state &= ~REQ_STATE_QUEUED;
2866 		req->state |= REQ_STATE_DONE;
2867 		if (req->state & REQ_STATE_TIMEDOUT) {
2868 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2869 			    "Sync Primitive Send Completed After Timeout\n");
2870 			mpt_free_request(mpt, req);
2871 		} else if ((req->state & REQ_STATE_NEED_WAKEUP) == 0) {
2872 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2873 			    "Async Primitive Send Complete\n");
2874 			mpt_free_request(mpt, req);
2875 		} else {
2876 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2877 			    "Sync Primitive Send Complete- Waking Waiter\n");
2878 			wakeup(req);
2879 		}
2880 		return (TRUE);
2881 	}
2882 
2883 	if (rp->Function != MPI_FUNCTION_FC_LINK_SRVC_BUF_POST) {
2884 		mpt_prt(mpt, "unexpected ELS_REPLY: Function 0x%x Flags %x "
2885 		    "Length %d Message Flags %x\n", rp->Function, rp->Flags,
2886 		    rp->MsgLength, rp->MsgFlags);
2887 		return (TRUE);
2888 	}
2889 
2890 	if (rp->MsgLength <= 5) {
2891 		/*
2892 		 * This is just a ack of an original ELS buffer post
2893 		 */
2894 		mpt_lprt(mpt, MPT_PRT_DEBUG,
2895 		    "RECV'd ACK of FC_ELS buf post %p:%u\n", req, req->serno);
2896 		return (TRUE);
2897 	}
2898 
2899 
2900 	rctl = (le32toh(rp->Rctl_Did) & MPI_FC_RCTL_MASK) >> MPI_FC_RCTL_SHIFT;
2901 	type = (le32toh(rp->Type_Fctl) & MPI_FC_TYPE_MASK) >> MPI_FC_TYPE_SHIFT;
2902 
2903 	elsbuf = &((U32 *)req->req_vbuf)[MPT_RQSL(mpt)/sizeof (U32)];
2904 	cmd = be32toh(elsbuf[0]) >> 24;
2905 
2906 	if (rp->Flags & MPI_LS_BUF_POST_REPLY_FLAG_NO_RSP_NEEDED) {
2907 		mpt_lprt(mpt, MPT_PRT_ALWAYS, "ELS_REPLY: response unneeded\n");
2908 		return (TRUE);
2909 	}
2910 
2911 	ioindex = le32toh(rp->TransactionContext);
2912 	req = mpt->els_cmd_ptrs[ioindex];
2913 
2914 	if (rctl == ELS && type == 1) {
2915 		switch (cmd) {
2916 		case PRLI:
2917 			/*
2918 			 * Send back a PRLI ACC
2919 			 */
2920 			mpt_prt(mpt, "PRLI from 0x%08x%08x\n",
2921 			    le32toh(rp->Wwn.PortNameHigh),
2922 			    le32toh(rp->Wwn.PortNameLow));
2923 			elsbuf[0] = htobe32(0x02100014);
2924 			elsbuf[1] |= htobe32(0x00000100);
2925 			elsbuf[4] = htobe32(0x00000002);
2926 			if (mpt->role & MPT_ROLE_TARGET)
2927 				elsbuf[4] |= htobe32(0x00000010);
2928 			if (mpt->role & MPT_ROLE_INITIATOR)
2929 				elsbuf[4] |= htobe32(0x00000020);
2930 			/* remove from active list as we're done */
2931 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2932 			req->state &= ~REQ_STATE_QUEUED;
2933 			req->state |= REQ_STATE_DONE;
2934 			mpt_fc_els_send_response(mpt, req, rp, 20);
2935 			do_refresh = FALSE;
2936 			break;
2937 		case PRLO:
2938 			memset(elsbuf, 0, 5 * (sizeof (U32)));
2939 			elsbuf[0] = htobe32(0x02100014);
2940 			elsbuf[1] = htobe32(0x08000100);
2941 			mpt_prt(mpt, "PRLO from 0x%08x%08x\n",
2942 			    le32toh(rp->Wwn.PortNameHigh),
2943 			    le32toh(rp->Wwn.PortNameLow));
2944 			/* remove from active list as we're done */
2945 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2946 			req->state &= ~REQ_STATE_QUEUED;
2947 			req->state |= REQ_STATE_DONE;
2948 			mpt_fc_els_send_response(mpt, req, rp, 20);
2949 			do_refresh = FALSE;
2950 			break;
2951 		default:
2952 			mpt_prt(mpt, "ELS TYPE 1 COMMAND: %x\n", cmd);
2953 			break;
2954 		}
2955 	} else if (rctl == ABTS && type == 0) {
2956 		uint16_t rx_id = le16toh(rp->Rxid);
2957 		uint16_t ox_id = le16toh(rp->Oxid);
2958 		request_t *tgt_req = NULL;
2959 
2960 		mpt_prt(mpt,
2961 		    "ELS: ABTS OX_ID 0x%x RX_ID 0x%x from 0x%08x%08x\n",
2962 		    ox_id, rx_id, le32toh(rp->Wwn.PortNameHigh),
2963 		    le32toh(rp->Wwn.PortNameLow));
2964 		if (rx_id >= mpt->mpt_max_tgtcmds) {
2965 			mpt_prt(mpt, "Bad RX_ID 0x%x\n", rx_id);
2966 		} else if (mpt->tgt_cmd_ptrs == NULL) {
2967 			mpt_prt(mpt, "No TGT CMD PTRS\n");
2968 		} else {
2969 			tgt_req = mpt->tgt_cmd_ptrs[rx_id];
2970 		}
2971 		if (tgt_req) {
2972 			mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, tgt_req);
2973 			union ccb *ccb = tgt->ccb;
2974 			uint32_t ct_id;
2975 
2976 			/*
2977 			 * Check to make sure we have the correct command
2978 			 * The reply descriptor in the target state should
2979 			 * should contain an IoIndex that should match the
2980 			 * RX_ID.
2981 			 *
2982 			 * It'd be nice to have OX_ID to crosscheck with
2983 			 * as well.
2984 			 */
2985 			ct_id = GET_IO_INDEX(tgt->reply_desc);
2986 
2987 			if (ct_id != rx_id) {
2988 				mpt_lprt(mpt, MPT_PRT_ERROR, "ABORT Mismatch: "
2989 				    "RX_ID received=0x%x; RX_ID in cmd=0x%x\n",
2990 				    rx_id, ct_id);
2991 				goto skip;
2992 			}
2993 
2994 			ccb = tgt->ccb;
2995 			if (ccb) {
2996 				mpt_prt(mpt,
2997 				    "CCB (%p): lun %u flags %x status %x\n",
2998 				    ccb, ccb->ccb_h.target_lun,
2999 				    ccb->ccb_h.flags, ccb->ccb_h.status);
3000 			}
3001 			mpt_prt(mpt, "target state 0x%x resid %u xfrd %u rpwrd "
3002 			    "%x nxfers %x\n", tgt->state,
3003 			    tgt->resid, tgt->bytes_xfered, tgt->reply_desc,
3004 			    tgt->nxfers);
3005   skip:
3006 			if (mpt_abort_target_cmd(mpt, tgt_req)) {
3007 				mpt_prt(mpt, "unable to start TargetAbort\n");
3008 			}
3009 		} else {
3010 			mpt_prt(mpt, "no back pointer for RX_ID 0x%x\n", rx_id);
3011 		}
3012 		memset(elsbuf, 0, 5 * (sizeof (U32)));
3013 		elsbuf[0] = htobe32(0);
3014 		elsbuf[1] = htobe32((ox_id << 16) | rx_id);
3015 		elsbuf[2] = htobe32(0x000ffff);
3016 		/*
3017 		 * Dork with the reply frame so that the reponse to it
3018 		 * will be correct.
3019 		 */
3020 		rp->Rctl_Did += ((BA_ACC - ABTS) << MPI_FC_RCTL_SHIFT);
3021 		/* remove from active list as we're done */
3022 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3023 		req->state &= ~REQ_STATE_QUEUED;
3024 		req->state |= REQ_STATE_DONE;
3025 		mpt_fc_els_send_response(mpt, req, rp, 12);
3026 		do_refresh = FALSE;
3027 	} else {
3028 		mpt_prt(mpt, "ELS: RCTL %x TYPE %x CMD %x\n", rctl, type, cmd);
3029 	}
3030 	if (do_refresh == TRUE) {
3031 		/* remove from active list as we're done */
3032 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3033 		req->state &= ~REQ_STATE_QUEUED;
3034 		req->state |= REQ_STATE_DONE;
3035 		mpt_fc_post_els(mpt, req, ioindex);
3036 	}
3037 	return (TRUE);
3038 }
3039 
3040 /*
3041  * Clean up all SCSI Initiator personality state in response
3042  * to a controller reset.
3043  */
3044 static void
3045 mpt_cam_ioc_reset(struct mpt_softc *mpt, int type)
3046 {
3047 	/*
3048 	 * The pending list is already run down by
3049 	 * the generic handler.  Perform the same
3050 	 * operation on the timed out request list.
3051 	 */
3052 	mpt_complete_request_chain(mpt, &mpt->request_timeout_list,
3053 				   MPI_IOCSTATUS_INVALID_STATE);
3054 
3055 	/*
3056 	 * XXX: We need to repost ELS and Target Command Buffers?
3057 	 */
3058 
3059 	/*
3060 	 * Inform the XPT that a bus reset has occurred.
3061 	 */
3062 	xpt_async(AC_BUS_RESET, mpt->path, NULL);
3063 }
3064 
3065 /*
3066  * Parse additional completion information in the reply
3067  * frame for SCSI I/O requests.
3068  */
3069 static int
3070 mpt_scsi_reply_frame_handler(struct mpt_softc *mpt, request_t *req,
3071 			     MSG_DEFAULT_REPLY *reply_frame)
3072 {
3073 	union ccb *ccb;
3074 	MSG_SCSI_IO_REPLY *scsi_io_reply;
3075 	u_int ioc_status;
3076 	u_int sstate;
3077 
3078 	MPT_DUMP_REPLY_FRAME(mpt, reply_frame);
3079 	KASSERT(reply_frame->Function == MPI_FUNCTION_SCSI_IO_REQUEST
3080 	     || reply_frame->Function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH,
3081 		("MPT SCSI I/O Handler called with incorrect reply type"));
3082 	KASSERT((reply_frame->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY) == 0,
3083 		("MPT SCSI I/O Handler called with continuation reply"));
3084 
3085 	scsi_io_reply = (MSG_SCSI_IO_REPLY *)reply_frame;
3086 	ioc_status = le16toh(scsi_io_reply->IOCStatus);
3087 	ioc_status &= MPI_IOCSTATUS_MASK;
3088 	sstate = scsi_io_reply->SCSIState;
3089 
3090 	ccb = req->ccb;
3091 	ccb->csio.resid =
3092 	    ccb->csio.dxfer_len - le32toh(scsi_io_reply->TransferCount);
3093 
3094 	if ((sstate & MPI_SCSI_STATE_AUTOSENSE_VALID) != 0
3095 	 && (ccb->ccb_h.flags & (CAM_SENSE_PHYS | CAM_SENSE_PTR)) == 0) {
3096 		ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
3097 		ccb->csio.sense_resid =
3098 		    ccb->csio.sense_len - le32toh(scsi_io_reply->SenseCount);
3099 		bcopy(req->sense_vbuf, &ccb->csio.sense_data,
3100 		    min(ccb->csio.sense_len,
3101 		    le32toh(scsi_io_reply->SenseCount)));
3102 	}
3103 
3104 	if ((sstate & MPI_SCSI_STATE_QUEUE_TAG_REJECTED) != 0) {
3105 		/*
3106 		 * Tag messages rejected, but non-tagged retry
3107 		 * was successful.
3108 XXXX
3109 		mpt_set_tags(mpt, devinfo, MPT_QUEUE_NONE);
3110 		 */
3111 	}
3112 
3113 	switch(ioc_status) {
3114 	case MPI_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
3115 		/*
3116 		 * XXX
3117 		 * Linux driver indicates that a zero
3118 		 * transfer length with this error code
3119 		 * indicates a CRC error.
3120 		 *
3121 		 * No need to swap the bytes for checking
3122 		 * against zero.
3123 		 */
3124 		if (scsi_io_reply->TransferCount == 0) {
3125 			mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3126 			break;
3127 		}
3128 		/* FALLTHROUGH */
3129 	case MPI_IOCSTATUS_SCSI_DATA_UNDERRUN:
3130 	case MPI_IOCSTATUS_SUCCESS:
3131 	case MPI_IOCSTATUS_SCSI_RECOVERED_ERROR:
3132 		if ((sstate & MPI_SCSI_STATE_NO_SCSI_STATUS) != 0) {
3133 			/*
3134 			 * Status was never returned for this transaction.
3135 			 */
3136 			mpt_set_ccb_status(ccb, CAM_UNEXP_BUSFREE);
3137 		} else if (scsi_io_reply->SCSIStatus != SCSI_STATUS_OK) {
3138 			ccb->csio.scsi_status = scsi_io_reply->SCSIStatus;
3139 			mpt_set_ccb_status(ccb, CAM_SCSI_STATUS_ERROR);
3140 			if ((sstate & MPI_SCSI_STATE_AUTOSENSE_FAILED) != 0)
3141 				mpt_set_ccb_status(ccb, CAM_AUTOSENSE_FAIL);
3142 		} else if ((sstate & MPI_SCSI_STATE_RESPONSE_INFO_VALID) != 0) {
3143 
3144 			/* XXX Handle SPI-Packet and FCP-2 reponse info. */
3145 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3146 		} else
3147 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3148 		break;
3149 	case MPI_IOCSTATUS_SCSI_DATA_OVERRUN:
3150 		mpt_set_ccb_status(ccb, CAM_DATA_RUN_ERR);
3151 		break;
3152 	case MPI_IOCSTATUS_SCSI_IO_DATA_ERROR:
3153 		mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3154 		break;
3155 	case MPI_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
3156 		/*
3157 		 * Since selection timeouts and "device really not
3158 		 * there" are grouped into this error code, report
3159 		 * selection timeout.  Selection timeouts are
3160 		 * typically retried before giving up on the device
3161 		 * whereas "device not there" errors are considered
3162 		 * unretryable.
3163 		 */
3164 		mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3165 		break;
3166 	case MPI_IOCSTATUS_SCSI_PROTOCOL_ERROR:
3167 		mpt_set_ccb_status(ccb, CAM_SEQUENCE_FAIL);
3168 		break;
3169 	case MPI_IOCSTATUS_SCSI_INVALID_BUS:
3170 		mpt_set_ccb_status(ccb, CAM_PATH_INVALID);
3171 		break;
3172 	case MPI_IOCSTATUS_SCSI_INVALID_TARGETID:
3173 		mpt_set_ccb_status(ccb, CAM_TID_INVALID);
3174 		break;
3175 	case MPI_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
3176 		ccb->ccb_h.status = CAM_UA_TERMIO;
3177 		break;
3178 	case MPI_IOCSTATUS_INVALID_STATE:
3179 		/*
3180 		 * The IOC has been reset.  Emulate a bus reset.
3181 		 */
3182 		/* FALLTHROUGH */
3183 	case MPI_IOCSTATUS_SCSI_EXT_TERMINATED:
3184 		ccb->ccb_h.status = CAM_SCSI_BUS_RESET;
3185 		break;
3186 	case MPI_IOCSTATUS_SCSI_TASK_TERMINATED:
3187 	case MPI_IOCSTATUS_SCSI_IOC_TERMINATED:
3188 		/*
3189 		 * Don't clobber any timeout status that has
3190 		 * already been set for this transaction.  We
3191 		 * want the SCSI layer to be able to differentiate
3192 		 * between the command we aborted due to timeout
3193 		 * and any innocent bystanders.
3194 		 */
3195 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG)
3196 			break;
3197 		mpt_set_ccb_status(ccb, CAM_REQ_TERMIO);
3198 		break;
3199 
3200 	case MPI_IOCSTATUS_INSUFFICIENT_RESOURCES:
3201 		mpt_set_ccb_status(ccb, CAM_RESRC_UNAVAIL);
3202 		break;
3203 	case MPI_IOCSTATUS_BUSY:
3204 		mpt_set_ccb_status(ccb, CAM_BUSY);
3205 		break;
3206 	case MPI_IOCSTATUS_INVALID_FUNCTION:
3207 	case MPI_IOCSTATUS_INVALID_SGL:
3208 	case MPI_IOCSTATUS_INTERNAL_ERROR:
3209 	case MPI_IOCSTATUS_INVALID_FIELD:
3210 	default:
3211 		/* XXX
3212 		 * Some of the above may need to kick
3213 		 * of a recovery action!!!!
3214 		 */
3215 		ccb->ccb_h.status = CAM_UNREC_HBA_ERROR;
3216 		break;
3217 	}
3218 
3219 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3220 		mpt_freeze_ccb(ccb);
3221 	}
3222 
3223 	return (TRUE);
3224 }
3225 
3226 static void
3227 mpt_action(struct cam_sim *sim, union ccb *ccb)
3228 {
3229 	struct mpt_softc *mpt;
3230 	struct ccb_trans_settings *cts;
3231 	target_id_t tgt;
3232 	lun_id_t lun;
3233 	int raid_passthru;
3234 
3235 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mpt_action\n"));
3236 
3237 	mpt = (struct mpt_softc *)cam_sim_softc(sim);
3238 	raid_passthru = (sim == mpt->phydisk_sim);
3239 	MPT_LOCK_ASSERT(mpt);
3240 
3241 	tgt = ccb->ccb_h.target_id;
3242 	lun = ccb->ccb_h.target_lun;
3243 	if (raid_passthru &&
3244 	    ccb->ccb_h.func_code != XPT_PATH_INQ &&
3245 	    ccb->ccb_h.func_code != XPT_RESET_BUS &&
3246 	    ccb->ccb_h.func_code != XPT_RESET_DEV) {
3247 		CAMLOCK_2_MPTLOCK(mpt);
3248 		if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
3249 			MPTLOCK_2_CAMLOCK(mpt);
3250 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3251 			mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
3252 			xpt_done(ccb);
3253 			return;
3254 		}
3255 		MPTLOCK_2_CAMLOCK(mpt);
3256 	}
3257 	ccb->ccb_h.ccb_mpt_ptr = mpt;
3258 
3259 	switch (ccb->ccb_h.func_code) {
3260 	case XPT_SCSI_IO:	/* Execute the requested I/O operation */
3261 		/*
3262 		 * Do a couple of preliminary checks...
3263 		 */
3264 		if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
3265 			if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
3266 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3267 				mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3268 				break;
3269 			}
3270 		}
3271 		/* Max supported CDB length is 16 bytes */
3272 		/* XXX Unless we implement the new 32byte message type */
3273 		if (ccb->csio.cdb_len >
3274 		    sizeof (((PTR_MSG_SCSI_IO_REQUEST)0)->CDB)) {
3275 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3276 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3277 			break;
3278 		}
3279 #ifdef	MPT_TEST_MULTIPATH
3280 		if (mpt->failure_id == ccb->ccb_h.target_id) {
3281 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3282 			mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3283 			break;
3284 		}
3285 #endif
3286 		ccb->csio.scsi_status = SCSI_STATUS_OK;
3287 		mpt_start(sim, ccb);
3288 		return;
3289 
3290 	case XPT_RESET_BUS:
3291 		if (raid_passthru) {
3292 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3293 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3294 			break;
3295 		}
3296 	case XPT_RESET_DEV:
3297 		if (ccb->ccb_h.func_code == XPT_RESET_BUS) {
3298 			if (bootverbose) {
3299 				xpt_print(ccb->ccb_h.path, "reset bus\n");
3300 			}
3301 		} else {
3302 			xpt_print(ccb->ccb_h.path, "reset device\n");
3303 		}
3304 		CAMLOCK_2_MPTLOCK(mpt);
3305 		(void) mpt_bus_reset(mpt, tgt, lun, FALSE);
3306 		MPTLOCK_2_CAMLOCK(mpt);
3307 
3308 		/*
3309 		 * mpt_bus_reset is always successful in that it
3310 		 * will fall back to a hard reset should a bus
3311 		 * reset attempt fail.
3312 		 */
3313 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3314 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3315 		break;
3316 
3317 	case XPT_ABORT:
3318 	{
3319 		union ccb *accb = ccb->cab.abort_ccb;
3320 		CAMLOCK_2_MPTLOCK(mpt);
3321 		switch (accb->ccb_h.func_code) {
3322 		case XPT_ACCEPT_TARGET_IO:
3323 		case XPT_IMMED_NOTIFY:
3324 			ccb->ccb_h.status = mpt_abort_target_ccb(mpt, ccb);
3325 			break;
3326 		case XPT_CONT_TARGET_IO:
3327 			mpt_prt(mpt, "cannot abort active CTIOs yet\n");
3328 			ccb->ccb_h.status = CAM_UA_ABORT;
3329 			break;
3330 		case XPT_SCSI_IO:
3331 			ccb->ccb_h.status = CAM_UA_ABORT;
3332 			break;
3333 		default:
3334 			ccb->ccb_h.status = CAM_REQ_INVALID;
3335 			break;
3336 		}
3337 		MPTLOCK_2_CAMLOCK(mpt);
3338 		break;
3339 	}
3340 
3341 #ifdef	CAM_NEW_TRAN_CODE
3342 #define	IS_CURRENT_SETTINGS(c)	((c)->type == CTS_TYPE_CURRENT_SETTINGS)
3343 #else
3344 #define	IS_CURRENT_SETTINGS(c)	((c)->flags & CCB_TRANS_CURRENT_SETTINGS)
3345 #endif
3346 #define	DP_DISC_ENABLE	0x1
3347 #define	DP_DISC_DISABL	0x2
3348 #define	DP_DISC		(DP_DISC_ENABLE|DP_DISC_DISABL)
3349 
3350 #define	DP_TQING_ENABLE	0x4
3351 #define	DP_TQING_DISABL	0x8
3352 #define	DP_TQING	(DP_TQING_ENABLE|DP_TQING_DISABL)
3353 
3354 #define	DP_WIDE		0x10
3355 #define	DP_NARROW	0x20
3356 #define	DP_WIDTH	(DP_WIDE|DP_NARROW)
3357 
3358 #define	DP_SYNC		0x40
3359 
3360 	case XPT_SET_TRAN_SETTINGS:	/* Nexus Settings */
3361 	{
3362 #ifdef	CAM_NEW_TRAN_CODE
3363 		struct ccb_trans_settings_scsi *scsi;
3364 		struct ccb_trans_settings_spi *spi;
3365 #endif
3366 		uint8_t dval;
3367 		u_int period;
3368 		u_int offset;
3369 		int i, j;
3370 
3371 		cts = &ccb->cts;
3372 
3373 		if (mpt->is_fc || mpt->is_sas) {
3374 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3375 			break;
3376 		}
3377 
3378 #ifdef	CAM_NEW_TRAN_CODE
3379 		scsi = &cts->proto_specific.scsi;
3380 		spi = &cts->xport_specific.spi;
3381 
3382 		/*
3383 		 * We can be called just to valid transport and proto versions
3384 		 */
3385 		if (scsi->valid == 0 && spi->valid == 0) {
3386 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3387 			break;
3388 		}
3389 #endif
3390 
3391 		/*
3392 		 * Skip attempting settings on RAID volume disks.
3393 		 * Other devices on the bus get the normal treatment.
3394 		 */
3395 		if (mpt->phydisk_sim && raid_passthru == 0 &&
3396 		    mpt_is_raid_volume(mpt, tgt) != 0) {
3397 			mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3398 			    "no transfer settings for RAID vols\n");
3399 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3400 			break;
3401 		}
3402 
3403 		i = mpt->mpt_port_page2.PortSettings &
3404 		    MPI_SCSIPORTPAGE2_PORT_MASK_NEGO_MASTER_SETTINGS;
3405 		j = mpt->mpt_port_page2.PortFlags &
3406 		    MPI_SCSIPORTPAGE2_PORT_FLAGS_DV_MASK;
3407 		if (i == MPI_SCSIPORTPAGE2_PORT_ALL_MASTER_SETTINGS &&
3408 		    j == MPI_SCSIPORTPAGE2_PORT_FLAGS_OFF_DV) {
3409 			mpt_lprt(mpt, MPT_PRT_ALWAYS,
3410 			    "honoring BIOS transfer negotiations\n");
3411 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3412 			break;
3413 		}
3414 
3415 		dval = 0;
3416 		period = 0;
3417 		offset = 0;
3418 
3419 #ifndef	CAM_NEW_TRAN_CODE
3420 		if ((cts->valid & CCB_TRANS_DISC_VALID) != 0) {
3421 			dval |= (cts->flags & CCB_TRANS_DISC_ENB) ?
3422 			    DP_DISC_ENABLE : DP_DISC_DISABL;
3423 		}
3424 
3425 		if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
3426 			dval |= (cts->flags & CCB_TRANS_TAG_ENB) ?
3427 			    DP_TQING_ENABLE : DP_TQING_DISABL;
3428 		}
3429 
3430 		if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) != 0) {
3431 			dval |= cts->bus_width ? DP_WIDE : DP_NARROW;
3432 		}
3433 
3434 		if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) &&
3435 		    (cts->valid & CCB_TRANS_SYNC_OFFSET_VALID)) {
3436 			dval |= DP_SYNC;
3437 			period = cts->sync_period;
3438 			offset = cts->sync_offset;
3439 		}
3440 #else
3441 		if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
3442 			dval |= ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0) ?
3443 			    DP_DISC_ENABLE : DP_DISC_DISABL;
3444 		}
3445 
3446 		if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
3447 			dval |= ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) ?
3448 			    DP_TQING_ENABLE : DP_TQING_DISABL;
3449 		}
3450 
3451 		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
3452 			dval |= (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT) ?
3453 			    DP_WIDE : DP_NARROW;
3454 		}
3455 
3456 		if (spi->valid & CTS_SPI_VALID_SYNC_OFFSET) {
3457 			dval |= DP_SYNC;
3458 			offset = spi->sync_offset;
3459 		} else {
3460 			PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3461 			    &mpt->mpt_dev_page1[tgt];
3462 			offset = ptr->RequestedParameters;
3463 			offset &= MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3464 	    		offset >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3465 		}
3466 		if (spi->valid & CTS_SPI_VALID_SYNC_RATE) {
3467 			dval |= DP_SYNC;
3468 			period = spi->sync_period;
3469 		} else {
3470 			PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3471 			    &mpt->mpt_dev_page1[tgt];
3472 			period = ptr->RequestedParameters;
3473 			period &= MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3474 	    		period >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3475 		}
3476 #endif
3477 		CAMLOCK_2_MPTLOCK(mpt);
3478 		if (dval & DP_DISC_ENABLE) {
3479 			mpt->mpt_disc_enable |= (1 << tgt);
3480 		} else if (dval & DP_DISC_DISABL) {
3481 			mpt->mpt_disc_enable &= ~(1 << tgt);
3482 		}
3483 		if (dval & DP_TQING_ENABLE) {
3484 			mpt->mpt_tag_enable |= (1 << tgt);
3485 		} else if (dval & DP_TQING_DISABL) {
3486 			mpt->mpt_tag_enable &= ~(1 << tgt);
3487 		}
3488 		if (dval & DP_WIDTH) {
3489 			mpt_setwidth(mpt, tgt, 1);
3490 		}
3491 		if (dval & DP_SYNC) {
3492 			mpt_setsync(mpt, tgt, period, offset);
3493 		}
3494 		if (dval == 0) {
3495 			MPTLOCK_2_CAMLOCK(mpt);
3496 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3497 			break;
3498 		}
3499 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3500 		    "set [%d]: 0x%x period 0x%x offset %d\n",
3501 		    tgt, dval, period, offset);
3502 		if (mpt_update_spi_config(mpt, tgt)) {
3503 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3504 		} else {
3505 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3506 		}
3507 		MPTLOCK_2_CAMLOCK(mpt);
3508 		break;
3509 	}
3510 	case XPT_GET_TRAN_SETTINGS:
3511 	{
3512 #ifdef	CAM_NEW_TRAN_CODE
3513 		struct ccb_trans_settings_scsi *scsi;
3514 		cts = &ccb->cts;
3515 		cts->protocol = PROTO_SCSI;
3516 		if (mpt->is_fc) {
3517 			struct ccb_trans_settings_fc *fc =
3518 			    &cts->xport_specific.fc;
3519 			cts->protocol_version = SCSI_REV_SPC;
3520 			cts->transport = XPORT_FC;
3521 			cts->transport_version = 0;
3522 			fc->valid = CTS_FC_VALID_SPEED;
3523 			fc->bitrate = 100000;
3524 		} else if (mpt->is_sas) {
3525 			struct ccb_trans_settings_sas *sas =
3526 			    &cts->xport_specific.sas;
3527 			cts->protocol_version = SCSI_REV_SPC2;
3528 			cts->transport = XPORT_SAS;
3529 			cts->transport_version = 0;
3530 			sas->valid = CTS_SAS_VALID_SPEED;
3531 			sas->bitrate = 300000;
3532 		} else {
3533 			cts->protocol_version = SCSI_REV_2;
3534 			cts->transport = XPORT_SPI;
3535 			cts->transport_version = 2;
3536 			if (mpt_get_spi_settings(mpt, cts) != 0) {
3537 				mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3538 				break;
3539 			}
3540 		}
3541 		scsi = &cts->proto_specific.scsi;
3542 		scsi->valid = CTS_SCSI_VALID_TQ;
3543 		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3544 #else
3545 		cts = &ccb->cts;
3546 		if (mpt->is_fc) {
3547 			cts->flags = CCB_TRANS_TAG_ENB | CCB_TRANS_DISC_ENB;
3548 			cts->valid = CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3549 			cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3550 		} else if (mpt->is_sas) {
3551 			cts->flags = CCB_TRANS_TAG_ENB | CCB_TRANS_DISC_ENB;
3552 			cts->valid = CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3553 			cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3554 		} else if (mpt_get_spi_settings(mpt, cts) != 0) {
3555 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3556 			break;
3557 		}
3558 #endif
3559 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3560 		break;
3561 	}
3562 	case XPT_CALC_GEOMETRY:
3563 	{
3564 		struct ccb_calc_geometry *ccg;
3565 
3566 		ccg = &ccb->ccg;
3567 		if (ccg->block_size == 0) {
3568 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3569 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3570 			break;
3571 		}
3572 		mpt_calc_geometry(ccg, /*extended*/1);
3573 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
3574 		break;
3575 	}
3576 	case XPT_PATH_INQ:		/* Path routing inquiry */
3577 	{
3578 		struct ccb_pathinq *cpi = &ccb->cpi;
3579 
3580 		cpi->version_num = 1;
3581 		cpi->target_sprt = 0;
3582 		cpi->hba_eng_cnt = 0;
3583 		cpi->max_target = mpt->port_facts[0].MaxDevices - 1;
3584 		/*
3585 		 * FC cards report MAX_DEVICES of 512, but
3586 		 * the MSG_SCSI_IO_REQUEST target id field
3587 		 * is only 8 bits. Until we fix the driver
3588 		 * to support 'channels' for bus overflow,
3589 		 * just limit it.
3590 		 */
3591 		if (cpi->max_target > 255) {
3592 			cpi->max_target = 255;
3593 		}
3594 
3595 		/*
3596 		 * VMware ESX reports > 16 devices and then dies when we probe.
3597 		 */
3598 		if (mpt->is_spi && cpi->max_target > 15) {
3599 			cpi->max_target = 15;
3600 		}
3601 		if (mpt->is_spi)
3602 			cpi->max_lun = 7;
3603 		else
3604 			cpi->max_lun = MPT_MAX_LUNS;
3605 		cpi->initiator_id = mpt->mpt_ini_id;
3606 		cpi->bus_id = cam_sim_bus(sim);
3607 
3608 		/*
3609 		 * The base speed is the speed of the underlying connection.
3610 		 */
3611 #ifdef	CAM_NEW_TRAN_CODE
3612 		cpi->protocol = PROTO_SCSI;
3613 		if (mpt->is_fc) {
3614 			cpi->hba_misc = PIM_NOBUSRESET;
3615 			cpi->base_transfer_speed = 100000;
3616 			cpi->hba_inquiry = PI_TAG_ABLE;
3617 			cpi->transport = XPORT_FC;
3618 			cpi->transport_version = 0;
3619 			cpi->protocol_version = SCSI_REV_SPC;
3620 		} else if (mpt->is_sas) {
3621 			cpi->hba_misc = PIM_NOBUSRESET;
3622 			cpi->base_transfer_speed = 300000;
3623 			cpi->hba_inquiry = PI_TAG_ABLE;
3624 			cpi->transport = XPORT_SAS;
3625 			cpi->transport_version = 0;
3626 			cpi->protocol_version = SCSI_REV_SPC2;
3627 		} else {
3628 			cpi->hba_misc = PIM_SEQSCAN;
3629 			cpi->base_transfer_speed = 3300;
3630 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3631 			cpi->transport = XPORT_SPI;
3632 			cpi->transport_version = 2;
3633 			cpi->protocol_version = SCSI_REV_2;
3634 		}
3635 #else
3636 		if (mpt->is_fc) {
3637 			cpi->hba_misc = PIM_NOBUSRESET;
3638 			cpi->base_transfer_speed = 100000;
3639 			cpi->hba_inquiry = PI_TAG_ABLE;
3640 		} else if (mpt->is_sas) {
3641 			cpi->hba_misc = PIM_NOBUSRESET;
3642 			cpi->base_transfer_speed = 300000;
3643 			cpi->hba_inquiry = PI_TAG_ABLE;
3644 		} else {
3645 			cpi->hba_misc = PIM_SEQSCAN;
3646 			cpi->base_transfer_speed = 3300;
3647 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3648 		}
3649 #endif
3650 
3651 		/*
3652 		 * We give our fake RAID passhtru bus a width that is MaxVolumes
3653 		 * wide and restrict it to one lun.
3654 		 */
3655 		if (raid_passthru) {
3656 			cpi->max_target = mpt->ioc_page2->MaxPhysDisks - 1;
3657 			cpi->initiator_id = cpi->max_target + 1;
3658 			cpi->max_lun = 0;
3659 		}
3660 
3661 		if ((mpt->role & MPT_ROLE_INITIATOR) == 0) {
3662 			cpi->hba_misc |= PIM_NOINITIATOR;
3663 		}
3664 		if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET)) {
3665 			cpi->target_sprt =
3666 			    PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
3667 		} else {
3668 			cpi->target_sprt = 0;
3669 		}
3670 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
3671 		strncpy(cpi->hba_vid, "LSI", HBA_IDLEN);
3672 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
3673 		cpi->unit_number = cam_sim_unit(sim);
3674 		cpi->ccb_h.status = CAM_REQ_CMP;
3675 		break;
3676 	}
3677 	case XPT_EN_LUN:		/* Enable LUN as a target */
3678 	{
3679 		int result;
3680 
3681 		CAMLOCK_2_MPTLOCK(mpt);
3682 		if (ccb->cel.enable)
3683 			result = mpt_enable_lun(mpt,
3684 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3685 		else
3686 			result = mpt_disable_lun(mpt,
3687 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3688 		MPTLOCK_2_CAMLOCK(mpt);
3689 		if (result == 0) {
3690 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3691 		} else {
3692 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3693 		}
3694 		break;
3695 	}
3696 	case XPT_NOTIFY_ACK:		/* recycle notify ack */
3697 	case XPT_IMMED_NOTIFY:		/* Add Immediate Notify Resource */
3698 	case XPT_ACCEPT_TARGET_IO:	/* Add Accept Target IO Resource */
3699 	{
3700 		tgt_resource_t *trtp;
3701 		lun_id_t lun = ccb->ccb_h.target_lun;
3702 		ccb->ccb_h.sim_priv.entries[0].field = 0;
3703 		ccb->ccb_h.sim_priv.entries[1].ptr = mpt;
3704 		ccb->ccb_h.flags = 0;
3705 
3706 		if (lun == CAM_LUN_WILDCARD) {
3707 			if (ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
3708 				mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3709 				break;
3710 			}
3711 			trtp = &mpt->trt_wildcard;
3712 		} else if (lun >= MPT_MAX_LUNS) {
3713 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3714 			break;
3715 		} else {
3716 			trtp = &mpt->trt[lun];
3717 		}
3718 		CAMLOCK_2_MPTLOCK(mpt);
3719 		if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
3720 			mpt_lprt(mpt, MPT_PRT_DEBUG1,
3721 			    "Put FREE ATIO %p lun %d\n", ccb, lun);
3722 			STAILQ_INSERT_TAIL(&trtp->atios, &ccb->ccb_h,
3723 			    sim_links.stqe);
3724 		} else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
3725 			mpt_lprt(mpt, MPT_PRT_DEBUG1,
3726 			    "Put FREE INOT lun %d\n", lun);
3727 			STAILQ_INSERT_TAIL(&trtp->inots, &ccb->ccb_h,
3728 			    sim_links.stqe);
3729 		} else {
3730 			mpt_lprt(mpt, MPT_PRT_ALWAYS, "Got Notify ACK\n");
3731 		}
3732 		mpt_set_ccb_status(ccb, CAM_REQ_INPROG);
3733 		MPTLOCK_2_CAMLOCK(mpt);
3734 		return;
3735 	}
3736 	case XPT_CONT_TARGET_IO:
3737 		CAMLOCK_2_MPTLOCK(mpt);
3738 		mpt_target_start_io(mpt, ccb);
3739 		MPTLOCK_2_CAMLOCK(mpt);
3740 		return;
3741 
3742 	default:
3743 		ccb->ccb_h.status = CAM_REQ_INVALID;
3744 		break;
3745 	}
3746 	xpt_done(ccb);
3747 }
3748 
3749 static int
3750 mpt_get_spi_settings(struct mpt_softc *mpt, struct ccb_trans_settings *cts)
3751 {
3752 #ifdef	CAM_NEW_TRAN_CODE
3753 	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3754 	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3755 #endif
3756 	target_id_t tgt;
3757 	uint32_t dval, pval, oval;
3758 	int rv;
3759 
3760 	if (IS_CURRENT_SETTINGS(cts) == 0) {
3761 		tgt = cts->ccb_h.target_id;
3762 	} else if (xpt_path_sim(cts->ccb_h.path) == mpt->phydisk_sim) {
3763 		if (mpt_map_physdisk(mpt, (union ccb *)cts, &tgt)) {
3764 			return (-1);
3765 		}
3766 	} else {
3767 		tgt = cts->ccb_h.target_id;
3768 	}
3769 
3770 	/*
3771 	 * We aren't looking at Port Page 2 BIOS settings here-
3772 	 * sometimes these have been known to be bogus XXX.
3773 	 *
3774 	 * For user settings, we pick the max from port page 0
3775 	 *
3776 	 * For current settings we read the current settings out from
3777 	 * device page 0 for that target.
3778 	 */
3779 	if (IS_CURRENT_SETTINGS(cts)) {
3780 		CONFIG_PAGE_SCSI_DEVICE_0 tmp;
3781 		dval = 0;
3782 
3783 		CAMLOCK_2_MPTLOCK(mpt);
3784 		tmp = mpt->mpt_dev_page0[tgt];
3785 		rv = mpt_read_cur_cfg_page(mpt, tgt, &tmp.Header,
3786 		    sizeof(tmp), FALSE, 5000);
3787 		if (rv) {
3788 			MPTLOCK_2_CAMLOCK(mpt);
3789 			mpt_prt(mpt, "can't get tgt %d config page 0\n", tgt);
3790 			return (rv);
3791 		}
3792 		mpt2host_config_page_scsi_device_0(&tmp);
3793 
3794 		MPTLOCK_2_CAMLOCK(mpt);
3795 		mpt_lprt(mpt, MPT_PRT_DEBUG,
3796 		    "mpt_get_spi_settings[%d]: current NP %x Info %x\n", tgt,
3797 		    tmp.NegotiatedParameters, tmp.Information);
3798 		dval |= (tmp.NegotiatedParameters & MPI_SCSIDEVPAGE0_NP_WIDE) ?
3799 		    DP_WIDE : DP_NARROW;
3800 		dval |= (mpt->mpt_disc_enable & (1 << tgt)) ?
3801 		    DP_DISC_ENABLE : DP_DISC_DISABL;
3802 		dval |= (mpt->mpt_tag_enable & (1 << tgt)) ?
3803 		    DP_TQING_ENABLE : DP_TQING_DISABL;
3804 		oval = tmp.NegotiatedParameters;
3805 		oval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK;
3806 		oval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_OFFSET;
3807 		pval = tmp.NegotiatedParameters;
3808 		pval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK;
3809 		pval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_PERIOD;
3810 		mpt->mpt_dev_page0[tgt] = tmp;
3811 	} else {
3812 		dval = DP_WIDE|DP_DISC_ENABLE|DP_TQING_ENABLE|DP_SYNC;
3813 		oval = mpt->mpt_port_page0.Capabilities;
3814 		oval = MPI_SCSIPORTPAGE0_CAP_GET_MAX_SYNC_OFFSET(oval);
3815 		pval = mpt->mpt_port_page0.Capabilities;
3816 		pval = MPI_SCSIPORTPAGE0_CAP_GET_MIN_SYNC_PERIOD(pval);
3817 	}
3818 
3819 #ifndef	CAM_NEW_TRAN_CODE
3820 	cts->flags &= ~(CCB_TRANS_DISC_ENB|CCB_TRANS_TAG_ENB);
3821 	cts->valid = 0;
3822 	cts->sync_period = pval;
3823 	cts->sync_offset = oval;
3824 	cts->valid |= CCB_TRANS_SYNC_RATE_VALID;
3825 	cts->valid |= CCB_TRANS_SYNC_OFFSET_VALID;
3826 	cts->valid |= CCB_TRANS_BUS_WIDTH_VALID;
3827 	if (dval & DP_WIDE) {
3828 		cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3829 	} else {
3830 		cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3831 	}
3832 	if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3833 		cts->valid |= CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3834 		if (dval & DP_DISC_ENABLE) {
3835 			cts->flags |= CCB_TRANS_DISC_ENB;
3836 		}
3837 		if (dval & DP_TQING_ENABLE) {
3838 			cts->flags |= CCB_TRANS_TAG_ENB;
3839 		}
3840 	}
3841 #else
3842 	spi->valid = 0;
3843 	scsi->valid = 0;
3844 	spi->flags = 0;
3845 	scsi->flags = 0;
3846 	spi->sync_offset = oval;
3847 	spi->sync_period = pval;
3848 	spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
3849 	spi->valid |= CTS_SPI_VALID_SYNC_RATE;
3850 	spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
3851 	if (dval & DP_WIDE) {
3852 		spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3853 	} else {
3854 		spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3855 	}
3856 	if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3857 		scsi->valid = CTS_SCSI_VALID_TQ;
3858 		if (dval & DP_TQING_ENABLE) {
3859 			scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
3860 		}
3861 		spi->valid |= CTS_SPI_VALID_DISC;
3862 		if (dval & DP_DISC_ENABLE) {
3863 			spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
3864 		}
3865 	}
3866 #endif
3867 	mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3868 	    "mpt_get_spi_settings[%d]: %s flags 0x%x per 0x%x off=%d\n", tgt,
3869 	    IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM ", dval, pval, oval);
3870 	return (0);
3871 }
3872 
3873 static void
3874 mpt_setwidth(struct mpt_softc *mpt, int tgt, int onoff)
3875 {
3876 	PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3877 
3878 	ptr = &mpt->mpt_dev_page1[tgt];
3879 	if (onoff) {
3880 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_WIDE;
3881 	} else {
3882 		ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_WIDE;
3883 	}
3884 }
3885 
3886 static void
3887 mpt_setsync(struct mpt_softc *mpt, int tgt, int period, int offset)
3888 {
3889 	PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3890 
3891 	ptr = &mpt->mpt_dev_page1[tgt];
3892 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3893 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3894 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_DT;
3895 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_QAS;
3896 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_IU;
3897 	if (period == 0) {
3898 		return;
3899 	}
3900 	ptr->RequestedParameters |=
3901 	    period << MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3902 	ptr->RequestedParameters |=
3903 	    offset << MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3904 	if (period < 0xa) {
3905 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_DT;
3906 	}
3907 	if (period < 0x9) {
3908 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_QAS;
3909 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_IU;
3910 	}
3911 }
3912 
3913 static int
3914 mpt_update_spi_config(struct mpt_softc *mpt, int tgt)
3915 {
3916 	CONFIG_PAGE_SCSI_DEVICE_1 tmp;
3917 	int rv;
3918 
3919 	mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3920 	    "mpt_update_spi_config[%d].page1: Requested Params 0x%08x\n",
3921 	    tgt, mpt->mpt_dev_page1[tgt].RequestedParameters);
3922 	tmp = mpt->mpt_dev_page1[tgt];
3923 	host2mpt_config_page_scsi_device_1(&tmp);
3924 	rv = mpt_write_cur_cfg_page(mpt, tgt,
3925 	    &tmp.Header, sizeof(tmp), FALSE, 5000);
3926 	if (rv) {
3927 		mpt_prt(mpt, "mpt_update_spi_config: write cur page failed\n");
3928 		return (-1);
3929 	}
3930 	return (0);
3931 }
3932 
3933 static void
3934 mpt_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
3935 {
3936 #if __FreeBSD_version >= 500000
3937 	cam_calc_geometry(ccg, extended);
3938 #else
3939 	uint32_t size_mb;
3940 	uint32_t secs_per_cylinder;
3941 
3942 	if (ccg->block_size == 0) {
3943 		ccg->ccb_h.status = CAM_REQ_INVALID;
3944 		return;
3945 	}
3946 	size_mb = ccg->volume_size / ((1024L * 1024L) / ccg->block_size);
3947 	if (size_mb > 1024 && extended) {
3948 		ccg->heads = 255;
3949 		ccg->secs_per_track = 63;
3950 	} else {
3951 		ccg->heads = 64;
3952 		ccg->secs_per_track = 32;
3953 	}
3954 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
3955 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
3956 	ccg->ccb_h.status = CAM_REQ_CMP;
3957 #endif
3958 }
3959 
3960 /****************************** Timeout Recovery ******************************/
3961 static int
3962 mpt_spawn_recovery_thread(struct mpt_softc *mpt)
3963 {
3964 	int error;
3965 
3966 	error = mpt_kthread_create(mpt_recovery_thread, mpt,
3967 	    &mpt->recovery_thread, /*flags*/0,
3968 	    /*altstack*/0, "mpt_recovery%d", mpt->unit);
3969 	return (error);
3970 }
3971 
3972 static void
3973 mpt_terminate_recovery_thread(struct mpt_softc *mpt)
3974 {
3975 	if (mpt->recovery_thread == NULL) {
3976 		return;
3977 	}
3978 	mpt->shutdwn_recovery = 1;
3979 	wakeup(mpt);
3980 	/*
3981 	 * Sleep on a slightly different location
3982 	 * for this interlock just for added safety.
3983 	 */
3984 	mpt_sleep(mpt, &mpt->recovery_thread, PUSER, "thtrm", 0);
3985 }
3986 
3987 static void
3988 mpt_recovery_thread(void *arg)
3989 {
3990 	struct mpt_softc *mpt;
3991 
3992 	mpt = (struct mpt_softc *)arg;
3993 	MPT_LOCK(mpt);
3994 	for (;;) {
3995 		if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
3996 			if (mpt->shutdwn_recovery == 0) {
3997 				mpt_sleep(mpt, mpt, PUSER, "idle", 0);
3998 			}
3999 		}
4000 		if (mpt->shutdwn_recovery != 0) {
4001 			break;
4002 		}
4003 		mpt_recover_commands(mpt);
4004 	}
4005 	mpt->recovery_thread = NULL;
4006 	wakeup(&mpt->recovery_thread);
4007 	MPT_UNLOCK(mpt);
4008 	mpt_kthread_exit(0);
4009 }
4010 
4011 static int
4012 mpt_scsi_send_tmf(struct mpt_softc *mpt, u_int type, u_int flags,
4013     u_int channel, u_int target, u_int lun, u_int abort_ctx, int sleep_ok)
4014 {
4015 	MSG_SCSI_TASK_MGMT *tmf_req;
4016 	int		    error;
4017 
4018 	/*
4019 	 * Wait for any current TMF request to complete.
4020 	 * We're only allowed to issue one TMF at a time.
4021 	 */
4022 	error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_FREE, REQ_STATE_FREE,
4023 	    sleep_ok, MPT_TMF_MAX_TIMEOUT);
4024 	if (error != 0) {
4025 		mpt_reset(mpt, TRUE);
4026 		return (ETIMEDOUT);
4027 	}
4028 
4029 	mpt_assign_serno(mpt, mpt->tmf_req);
4030 	mpt->tmf_req->state = REQ_STATE_ALLOCATED|REQ_STATE_QUEUED;
4031 
4032 	tmf_req = (MSG_SCSI_TASK_MGMT *)mpt->tmf_req->req_vbuf;
4033 	memset(tmf_req, 0, sizeof(*tmf_req));
4034 	tmf_req->TargetID = target;
4035 	tmf_req->Bus = channel;
4036 	tmf_req->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
4037 	tmf_req->TaskType = type;
4038 	tmf_req->MsgFlags = flags;
4039 	tmf_req->MsgContext =
4040 	    htole32(mpt->tmf_req->index | scsi_tmf_handler_id);
4041 	if (lun > MPT_MAX_LUNS) {
4042 		tmf_req->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4043 		tmf_req->LUN[1] = lun & 0xff;
4044 	} else {
4045 		tmf_req->LUN[1] = lun;
4046 	}
4047 	tmf_req->TaskMsgContext = abort_ctx;
4048 
4049 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4050 	    "Issuing TMF %p:%u with MsgContext of 0x%x\n", mpt->tmf_req,
4051 	    mpt->tmf_req->serno, tmf_req->MsgContext);
4052 	if (mpt->verbose > MPT_PRT_DEBUG) {
4053 		mpt_print_request(tmf_req);
4054 	}
4055 
4056 	KASSERT(mpt_req_on_pending_list(mpt, mpt->tmf_req) == 0,
4057 	    ("mpt_scsi_send_tmf: tmf_req already on pending list"));
4058 	TAILQ_INSERT_HEAD(&mpt->request_pending_list, mpt->tmf_req, links);
4059 	error = mpt_send_handshake_cmd(mpt, sizeof(*tmf_req), tmf_req);
4060 	if (error != MPT_OK) {
4061 		TAILQ_REMOVE(&mpt->request_pending_list, mpt->tmf_req, links);
4062 		mpt->tmf_req->state = REQ_STATE_FREE;
4063 		mpt_reset(mpt, TRUE);
4064 	}
4065 	return (error);
4066 }
4067 
4068 /*
4069  * When a command times out, it is placed on the requeust_timeout_list
4070  * and we wake our recovery thread.  The MPT-Fusion architecture supports
4071  * only a single TMF operation at a time, so we serially abort/bdr, etc,
4072  * the timedout transactions.  The next TMF is issued either by the
4073  * completion handler of the current TMF waking our recovery thread,
4074  * or the TMF timeout handler causing a hard reset sequence.
4075  */
4076 static void
4077 mpt_recover_commands(struct mpt_softc *mpt)
4078 {
4079 	request_t	   *req;
4080 	union ccb	   *ccb;
4081 	int		    error;
4082 
4083 	if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4084 		/*
4085 		 * No work to do- leave.
4086 		 */
4087 		mpt_prt(mpt, "mpt_recover_commands: no requests.\n");
4088 		return;
4089 	}
4090 
4091 	/*
4092 	 * Flush any commands whose completion coincides with their timeout.
4093 	 */
4094 	mpt_intr(mpt);
4095 
4096 	if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4097 		/*
4098 		 * The timedout commands have already
4099 		 * completed.  This typically means
4100 		 * that either the timeout value was on
4101 		 * the hairy edge of what the device
4102 		 * requires or - more likely - interrupts
4103 		 * are not happening.
4104 		 */
4105 		mpt_prt(mpt, "Timedout requests already complete. "
4106 		    "Interrupts may not be functioning.\n");
4107 		mpt_enable_ints(mpt);
4108 		return;
4109 	}
4110 
4111 	/*
4112 	 * We have no visibility into the current state of the
4113 	 * controller, so attempt to abort the commands in the
4114 	 * order they timed-out. For initiator commands, we
4115 	 * depend on the reply handler pulling requests off
4116 	 * the timeout list.
4117 	 */
4118 	while ((req = TAILQ_FIRST(&mpt->request_timeout_list)) != NULL) {
4119 		uint16_t status;
4120 		uint8_t response;
4121 		MSG_REQUEST_HEADER *hdrp = req->req_vbuf;
4122 
4123 		mpt_prt(mpt, "attempting to abort req %p:%u function %x\n",
4124 		    req, req->serno, hdrp->Function);
4125 		ccb = req->ccb;
4126 		if (ccb == NULL) {
4127 			mpt_prt(mpt, "null ccb in timed out request. "
4128 			    "Resetting Controller.\n");
4129 			mpt_reset(mpt, TRUE);
4130 			continue;
4131 		}
4132 		mpt_set_ccb_status(ccb, CAM_CMD_TIMEOUT);
4133 
4134 		/*
4135 		 * Check to see if this is not an initiator command and
4136 		 * deal with it differently if it is.
4137 		 */
4138 		switch (hdrp->Function) {
4139 		case MPI_FUNCTION_SCSI_IO_REQUEST:
4140 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
4141 			break;
4142 		default:
4143 			/*
4144 			 * XXX: FIX ME: need to abort target assists...
4145 			 */
4146 			mpt_prt(mpt, "just putting it back on the pend q\n");
4147 			TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
4148 			TAILQ_INSERT_HEAD(&mpt->request_pending_list, req,
4149 			    links);
4150 			continue;
4151 		}
4152 
4153 		error = mpt_scsi_send_tmf(mpt,
4154 		    MPI_SCSITASKMGMT_TASKTYPE_ABORT_TASK,
4155 		    0, 0, ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
4156 		    htole32(req->index | scsi_io_handler_id), TRUE);
4157 
4158 		if (error != 0) {
4159 			/*
4160 			 * mpt_scsi_send_tmf hard resets on failure, so no
4161 			 * need to do so here.  Our queue should be emptied
4162 			 * by the hard reset.
4163 			 */
4164 			continue;
4165 		}
4166 
4167 		error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
4168 		    REQ_STATE_DONE, TRUE, 500);
4169 
4170 		status = le16toh(mpt->tmf_req->IOCStatus);
4171 		response = mpt->tmf_req->ResponseCode;
4172 		mpt->tmf_req->state = REQ_STATE_FREE;
4173 
4174 		if (error != 0) {
4175 			/*
4176 			 * If we've errored out,, reset the controller.
4177 			 */
4178 			mpt_prt(mpt, "mpt_recover_commands: abort timed-out. "
4179 			    "Resetting controller\n");
4180 			mpt_reset(mpt, TRUE);
4181 			continue;
4182 		}
4183 
4184 		if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
4185 			mpt_prt(mpt, "mpt_recover_commands: IOC Status 0x%x. "
4186 			    "Resetting controller.\n", status);
4187 			mpt_reset(mpt, TRUE);
4188 			continue;
4189 		}
4190 
4191 		if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
4192 		    response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
4193 			mpt_prt(mpt, "mpt_recover_commands: TMF Response 0x%x. "
4194 			    "Resetting controller.\n", response);
4195 			mpt_reset(mpt, TRUE);
4196 			continue;
4197 		}
4198 		mpt_prt(mpt, "abort of req %p:%u completed\n", req, req->serno);
4199 	}
4200 }
4201 
4202 /************************ Target Mode Support ****************************/
4203 static void
4204 mpt_fc_post_els(struct mpt_softc *mpt, request_t *req, int ioindex)
4205 {
4206 	MSG_LINK_SERVICE_BUFFER_POST_REQUEST *fc;
4207 	PTR_SGE_TRANSACTION32 tep;
4208 	PTR_SGE_SIMPLE32 se;
4209 	bus_addr_t paddr;
4210 	uint32_t fl;
4211 
4212 	paddr = req->req_pbuf;
4213 	paddr += MPT_RQSL(mpt);
4214 
4215 	fc = req->req_vbuf;
4216 	memset(fc, 0, MPT_REQUEST_AREA);
4217 	fc->BufferCount = 1;
4218 	fc->Function = MPI_FUNCTION_FC_LINK_SRVC_BUF_POST;
4219 	fc->MsgContext = htole32(req->index | fc_els_handler_id);
4220 
4221 	/*
4222 	 * Okay, set up ELS buffer pointers. ELS buffer pointers
4223 	 * consist of a TE SGL element (with details length of zero)
4224 	 * followe by a SIMPLE SGL element which holds the address
4225 	 * of the buffer.
4226 	 */
4227 
4228 	tep = (PTR_SGE_TRANSACTION32) &fc->SGL;
4229 
4230 	tep->ContextSize = 4;
4231 	tep->Flags = 0;
4232 	tep->TransactionContext[0] = htole32(ioindex);
4233 
4234 	se = (PTR_SGE_SIMPLE32) &tep->TransactionDetails[0];
4235 	fl =
4236 		MPI_SGE_FLAGS_HOST_TO_IOC	|
4237 		MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
4238 		MPI_SGE_FLAGS_LAST_ELEMENT	|
4239 		MPI_SGE_FLAGS_END_OF_LIST	|
4240 		MPI_SGE_FLAGS_END_OF_BUFFER;
4241 	fl <<= MPI_SGE_FLAGS_SHIFT;
4242 	fl |= (MPT_NRFM(mpt) - MPT_RQSL(mpt));
4243 	se->FlagsLength = htole32(fl);
4244 	se->Address = htole32((uint32_t) paddr);
4245 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4246 	    "add ELS index %d ioindex %d for %p:%u\n",
4247 	    req->index, ioindex, req, req->serno);
4248 	KASSERT(((req->state & REQ_STATE_LOCKED) != 0),
4249 	    ("mpt_fc_post_els: request not locked"));
4250 	mpt_send_cmd(mpt, req);
4251 }
4252 
4253 static void
4254 mpt_post_target_command(struct mpt_softc *mpt, request_t *req, int ioindex)
4255 {
4256 	PTR_MSG_TARGET_CMD_BUFFER_POST_REQUEST fc;
4257 	PTR_CMD_BUFFER_DESCRIPTOR cb;
4258 	bus_addr_t paddr;
4259 
4260 	paddr = req->req_pbuf;
4261 	paddr += MPT_RQSL(mpt);
4262 	memset(req->req_vbuf, 0, MPT_REQUEST_AREA);
4263 	MPT_TGT_STATE(mpt, req)->state = TGT_STATE_LOADING;
4264 
4265 	fc = req->req_vbuf;
4266 	fc->BufferCount = 1;
4267 	fc->Function = MPI_FUNCTION_TARGET_CMD_BUFFER_POST;
4268 	fc->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4269 
4270 	cb = &fc->Buffer[0];
4271 	cb->IoIndex = htole16(ioindex);
4272 	cb->u.PhysicalAddress32 = htole32((U32) paddr);
4273 
4274 	mpt_check_doorbell(mpt);
4275 	mpt_send_cmd(mpt, req);
4276 }
4277 
4278 static int
4279 mpt_add_els_buffers(struct mpt_softc *mpt)
4280 {
4281 	int i;
4282 
4283 	if (mpt->is_fc == 0) {
4284 		return (TRUE);
4285 	}
4286 
4287 	if (mpt->els_cmds_allocated) {
4288 		return (TRUE);
4289 	}
4290 
4291 	mpt->els_cmd_ptrs = malloc(MPT_MAX_ELS * sizeof (request_t *),
4292 	    M_DEVBUF, M_NOWAIT | M_ZERO);
4293 
4294 	if (mpt->els_cmd_ptrs == NULL) {
4295 		return (FALSE);
4296 	}
4297 
4298 	/*
4299 	 * Feed the chip some ELS buffer resources
4300 	 */
4301 	for (i = 0; i < MPT_MAX_ELS; i++) {
4302 		request_t *req = mpt_get_request(mpt, FALSE);
4303 		if (req == NULL) {
4304 			break;
4305 		}
4306 		req->state |= REQ_STATE_LOCKED;
4307 		mpt->els_cmd_ptrs[i] = req;
4308 		mpt_fc_post_els(mpt, req, i);
4309 	}
4310 
4311 	if (i == 0) {
4312 		mpt_prt(mpt, "unable to add ELS buffer resources\n");
4313 		free(mpt->els_cmd_ptrs, M_DEVBUF);
4314 		mpt->els_cmd_ptrs = NULL;
4315 		return (FALSE);
4316 	}
4317 	if (i != MPT_MAX_ELS) {
4318 		mpt_lprt(mpt, MPT_PRT_INFO,
4319 		    "only added %d of %d  ELS buffers\n", i, MPT_MAX_ELS);
4320 	}
4321 	mpt->els_cmds_allocated = i;
4322 	return(TRUE);
4323 }
4324 
4325 static int
4326 mpt_add_target_commands(struct mpt_softc *mpt)
4327 {
4328 	int i, max;
4329 
4330 	if (mpt->tgt_cmd_ptrs) {
4331 		return (TRUE);
4332 	}
4333 
4334 	max = MPT_MAX_REQUESTS(mpt) >> 1;
4335 	if (max > mpt->mpt_max_tgtcmds) {
4336 		max = mpt->mpt_max_tgtcmds;
4337 	}
4338 	mpt->tgt_cmd_ptrs =
4339 	    malloc(max * sizeof (request_t *), M_DEVBUF, M_NOWAIT | M_ZERO);
4340 	if (mpt->tgt_cmd_ptrs == NULL) {
4341 		mpt_prt(mpt,
4342 		    "mpt_add_target_commands: could not allocate cmd ptrs\n");
4343 		return (FALSE);
4344 	}
4345 
4346 	for (i = 0; i < max; i++) {
4347 		request_t *req;
4348 
4349 		req = mpt_get_request(mpt, FALSE);
4350 		if (req == NULL) {
4351 			break;
4352 		}
4353 		req->state |= REQ_STATE_LOCKED;
4354 		mpt->tgt_cmd_ptrs[i] = req;
4355 		mpt_post_target_command(mpt, req, i);
4356 	}
4357 
4358 
4359 	if (i == 0) {
4360 		mpt_lprt(mpt, MPT_PRT_ERROR, "could not add any target bufs\n");
4361 		free(mpt->tgt_cmd_ptrs, M_DEVBUF);
4362 		mpt->tgt_cmd_ptrs = NULL;
4363 		return (FALSE);
4364 	}
4365 
4366 	mpt->tgt_cmds_allocated = i;
4367 
4368 	if (i < max) {
4369 		mpt_lprt(mpt, MPT_PRT_INFO,
4370 		    "added %d of %d target bufs\n", i, max);
4371 	}
4372 	return (i);
4373 }
4374 
4375 static int
4376 mpt_enable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4377 {
4378 	if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4379 		mpt->twildcard = 1;
4380 	} else if (lun >= MPT_MAX_LUNS) {
4381 		return (EINVAL);
4382 	} else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4383 		return (EINVAL);
4384 	}
4385 	if (mpt->tenabled == 0) {
4386 		if (mpt->is_fc) {
4387 			(void) mpt_fc_reset_link(mpt, 0);
4388 		}
4389 		mpt->tenabled = 1;
4390 	}
4391 	if (lun == CAM_LUN_WILDCARD) {
4392 		mpt->trt_wildcard.enabled = 1;
4393 	} else {
4394 		mpt->trt[lun].enabled = 1;
4395 	}
4396 	return (0);
4397 }
4398 
4399 static int
4400 mpt_disable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4401 {
4402 	int i;
4403 	if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4404 		mpt->twildcard = 0;
4405 	} else if (lun >= MPT_MAX_LUNS) {
4406 		return (EINVAL);
4407 	} else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4408 		return (EINVAL);
4409 	}
4410 	if (lun == CAM_LUN_WILDCARD) {
4411 		mpt->trt_wildcard.enabled = 0;
4412 	} else {
4413 		mpt->trt[lun].enabled = 0;
4414 	}
4415 	for (i = 0; i < MPT_MAX_LUNS; i++) {
4416 		if (mpt->trt[lun].enabled) {
4417 			break;
4418 		}
4419 	}
4420 	if (i == MPT_MAX_LUNS && mpt->twildcard == 0) {
4421 		if (mpt->is_fc) {
4422 			(void) mpt_fc_reset_link(mpt, 0);
4423 		}
4424 		mpt->tenabled = 0;
4425 	}
4426 	return (0);
4427 }
4428 
4429 /*
4430  * Called with MPT lock held
4431  */
4432 static void
4433 mpt_target_start_io(struct mpt_softc *mpt, union ccb *ccb)
4434 {
4435 	struct ccb_scsiio *csio = &ccb->csio;
4436 	request_t *cmd_req = MPT_TAG_2_REQ(mpt, csio->tag_id);
4437 	mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
4438 
4439 	switch (tgt->state) {
4440 	case TGT_STATE_IN_CAM:
4441 		break;
4442 	case TGT_STATE_MOVING_DATA:
4443 		mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4444 		xpt_freeze_simq(mpt->sim, 1);
4445 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4446 		tgt->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4447 		MPTLOCK_2_CAMLOCK(mpt);
4448 		xpt_done(ccb);
4449 		CAMLOCK_2_MPTLOCK(mpt);
4450 		return;
4451 	default:
4452 		mpt_prt(mpt, "ccb %p flags 0x%x tag 0x%08x had bad request "
4453 		    "starting I/O\n", ccb, csio->ccb_h.flags, csio->tag_id);
4454 		mpt_tgt_dump_req_state(mpt, cmd_req);
4455 		mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
4456 		MPTLOCK_2_CAMLOCK(mpt);
4457 		xpt_done(ccb);
4458 		CAMLOCK_2_MPTLOCK(mpt);
4459 		return;
4460 	}
4461 
4462 	if (csio->dxfer_len) {
4463 		bus_dmamap_callback_t *cb;
4464 		PTR_MSG_TARGET_ASSIST_REQUEST ta;
4465 		request_t *req;
4466 
4467 		KASSERT((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE,
4468 		    ("dxfer_len %u but direction is NONE\n", csio->dxfer_len));
4469 
4470 		if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4471 			if (mpt->outofbeer == 0) {
4472 				mpt->outofbeer = 1;
4473 				xpt_freeze_simq(mpt->sim, 1);
4474 				mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4475 			}
4476 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4477 			mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4478 			MPTLOCK_2_CAMLOCK(mpt);
4479 			xpt_done(ccb);
4480 			CAMLOCK_2_MPTLOCK(mpt);
4481 			return;
4482 		}
4483 		ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4484 		if (sizeof (bus_addr_t) > 4) {
4485 			cb = mpt_execute_req_a64;
4486 		} else {
4487 			cb = mpt_execute_req;
4488 		}
4489 
4490 		req->ccb = ccb;
4491 		ccb->ccb_h.ccb_req_ptr = req;
4492 
4493 		/*
4494 		 * Record the currently active ccb and the
4495 		 * request for it in our target state area.
4496 		 */
4497 		tgt->ccb = ccb;
4498 		tgt->req = req;
4499 
4500 		memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4501 		ta = req->req_vbuf;
4502 
4503 		if (mpt->is_sas) {
4504 			PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4505 			     cmd_req->req_vbuf;
4506 			ta->QueueTag = ssp->InitiatorTag;
4507 		} else if (mpt->is_spi) {
4508 			PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4509 			     cmd_req->req_vbuf;
4510 			ta->QueueTag = sp->Tag;
4511 		}
4512 		ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4513 		ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4514 		ta->ReplyWord = htole32(tgt->reply_desc);
4515 		if (csio->ccb_h.target_lun > MPT_MAX_LUNS) {
4516 			ta->LUN[0] =
4517 			    0x40 | ((csio->ccb_h.target_lun >> 8) & 0x3f);
4518 			ta->LUN[1] = csio->ccb_h.target_lun & 0xff;
4519 		} else {
4520 			ta->LUN[1] = csio->ccb_h.target_lun;
4521 		}
4522 
4523 		ta->RelativeOffset = tgt->bytes_xfered;
4524 		ta->DataLength = ccb->csio.dxfer_len;
4525 		if (ta->DataLength > tgt->resid) {
4526 			ta->DataLength = tgt->resid;
4527 		}
4528 
4529 		/*
4530 		 * XXX Should be done after data transfer completes?
4531 		 */
4532 		tgt->resid -= csio->dxfer_len;
4533 		tgt->bytes_xfered += csio->dxfer_len;
4534 
4535 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4536 			ta->TargetAssistFlags |=
4537 			    TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4538 		}
4539 
4540 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4541 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
4542 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
4543 			ta->TargetAssistFlags |=
4544 			    TARGET_ASSIST_FLAGS_AUTO_STATUS;
4545 		}
4546 #endif
4547 		tgt->state = TGT_STATE_SETTING_UP_FOR_DATA;
4548 
4549 		mpt_lprt(mpt, MPT_PRT_DEBUG,
4550 		    "DATA_CCB %p tag %x %u bytes %u resid flg %x req %p:%u "
4551 		    "nxtstate=%d\n", csio, csio->tag_id, csio->dxfer_len,
4552 		    tgt->resid, ccb->ccb_h.flags, req, req->serno, tgt->state);
4553 
4554 		MPTLOCK_2_CAMLOCK(mpt);
4555 		if ((ccb->ccb_h.flags & CAM_SCATTER_VALID) == 0) {
4556 			if ((ccb->ccb_h.flags & CAM_DATA_PHYS) == 0) {
4557 				int error;
4558 				int s = splsoftvm();
4559 				error = bus_dmamap_load(mpt->buffer_dmat,
4560 				    req->dmap, csio->data_ptr, csio->dxfer_len,
4561 				    cb, req, 0);
4562 				splx(s);
4563 				if (error == EINPROGRESS) {
4564 					xpt_freeze_simq(mpt->sim, 1);
4565 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4566 				}
4567 			} else {
4568 				/*
4569 				 * We have been given a pointer to single
4570 				 * physical buffer.
4571 				 */
4572 				struct bus_dma_segment seg;
4573 				seg.ds_addr = (bus_addr_t)
4574 				    (vm_offset_t)csio->data_ptr;
4575 				seg.ds_len = csio->dxfer_len;
4576 				(*cb)(req, &seg, 1, 0);
4577 			}
4578 		} else {
4579 			/*
4580 			 * We have been given a list of addresses.
4581 			 * This case could be easily supported but they are not
4582 			 * currently generated by the CAM subsystem so there
4583 			 * is no point in wasting the time right now.
4584 			 */
4585 			struct bus_dma_segment *sgs;
4586 			if ((ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
4587 				(*cb)(req, NULL, 0, EFAULT);
4588 			} else {
4589 				/* Just use the segments provided */
4590 				sgs = (struct bus_dma_segment *)csio->data_ptr;
4591 				(*cb)(req, sgs, csio->sglist_cnt, 0);
4592 			}
4593 		}
4594 		CAMLOCK_2_MPTLOCK(mpt);
4595 	} else {
4596 		uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
4597 
4598 		/*
4599 		 * XXX: I don't know why this seems to happen, but
4600 		 * XXX: completing the CCB seems to make things happy.
4601 		 * XXX: This seems to happen if the initiator requests
4602 		 * XXX: enough data that we have to do multiple CTIOs.
4603 		 */
4604 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
4605 			mpt_lprt(mpt, MPT_PRT_DEBUG,
4606 			    "Meaningless STATUS CCB (%p): flags %x status %x "
4607 			    "resid %d bytes_xfered %u\n", ccb, ccb->ccb_h.flags,
4608 			    ccb->ccb_h.status, tgt->resid, tgt->bytes_xfered);
4609 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
4610 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4611 			MPTLOCK_2_CAMLOCK(mpt);
4612 			xpt_done(ccb);
4613 			CAMLOCK_2_MPTLOCK(mpt);
4614 			return;
4615 		}
4616 		if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
4617 			sp = sense;
4618 			memcpy(sp, &csio->sense_data,
4619 			   min(csio->sense_len, MPT_SENSE_SIZE));
4620 		}
4621 		mpt_scsi_tgt_status(mpt, ccb, cmd_req, csio->scsi_status, sp);
4622 	}
4623 }
4624 
4625 static void
4626 mpt_scsi_tgt_local(struct mpt_softc *mpt, request_t *cmd_req,
4627     uint32_t lun, int send, uint8_t *data, size_t length)
4628 {
4629 	mpt_tgt_state_t *tgt;
4630 	PTR_MSG_TARGET_ASSIST_REQUEST ta;
4631 	SGE_SIMPLE32 *se;
4632 	uint32_t flags;
4633 	uint8_t *dptr;
4634 	bus_addr_t pptr;
4635 	request_t *req;
4636 
4637 	/*
4638 	 * We enter with resid set to the data load for the command.
4639 	 */
4640 	tgt = MPT_TGT_STATE(mpt, cmd_req);
4641 	if (length == 0 || tgt->resid == 0) {
4642 		tgt->resid = 0;
4643 		mpt_scsi_tgt_status(mpt, NULL, cmd_req, 0, NULL);
4644 		return;
4645 	}
4646 
4647 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4648 		mpt_prt(mpt, "out of resources- dropping local response\n");
4649 		return;
4650 	}
4651 	tgt->is_local = 1;
4652 
4653 
4654 	memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4655 	ta = req->req_vbuf;
4656 
4657 	if (mpt->is_sas) {
4658 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp = cmd_req->req_vbuf;
4659 		ta->QueueTag = ssp->InitiatorTag;
4660 	} else if (mpt->is_spi) {
4661 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp = cmd_req->req_vbuf;
4662 		ta->QueueTag = sp->Tag;
4663 	}
4664 	ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4665 	ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4666 	ta->ReplyWord = htole32(tgt->reply_desc);
4667 	if (lun > MPT_MAX_LUNS) {
4668 		ta->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4669 		ta->LUN[1] = lun & 0xff;
4670 	} else {
4671 		ta->LUN[1] = lun;
4672 	}
4673 	ta->RelativeOffset = 0;
4674 	ta->DataLength = length;
4675 
4676 	dptr = req->req_vbuf;
4677 	dptr += MPT_RQSL(mpt);
4678 	pptr = req->req_pbuf;
4679 	pptr += MPT_RQSL(mpt);
4680 	memcpy(dptr, data, min(length, MPT_RQSL(mpt)));
4681 
4682 	se = (SGE_SIMPLE32 *) &ta->SGL[0];
4683 	memset(se, 0,sizeof (*se));
4684 
4685 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
4686 	if (send) {
4687 		ta->TargetAssistFlags |= TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4688 		flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
4689 	}
4690 	se->Address = pptr;
4691 	MPI_pSGE_SET_LENGTH(se, length);
4692 	flags |= MPI_SGE_FLAGS_LAST_ELEMENT;
4693 	flags |= MPI_SGE_FLAGS_END_OF_LIST | MPI_SGE_FLAGS_END_OF_BUFFER;
4694 	MPI_pSGE_SET_FLAGS(se, flags);
4695 
4696 	tgt->ccb = NULL;
4697 	tgt->req = req;
4698 	tgt->resid -= length;
4699 	tgt->bytes_xfered = length;
4700 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4701 	tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
4702 #else
4703 	tgt->state = TGT_STATE_MOVING_DATA;
4704 #endif
4705 	mpt_send_cmd(mpt, req);
4706 }
4707 
4708 /*
4709  * Abort queued up CCBs
4710  */
4711 static cam_status
4712 mpt_abort_target_ccb(struct mpt_softc *mpt, union ccb *ccb)
4713 {
4714 	struct mpt_hdr_stailq *lp;
4715 	struct ccb_hdr *srch;
4716 	int found = 0;
4717 	union ccb *accb = ccb->cab.abort_ccb;
4718 	tgt_resource_t *trtp;
4719 
4720 	mpt_lprt(mpt, MPT_PRT_DEBUG, "aborting ccb %p\n", accb);
4721 
4722 	if (ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
4723 		trtp = &mpt->trt_wildcard;
4724 	} else {
4725 		trtp = &mpt->trt[ccb->ccb_h.target_lun];
4726 	}
4727 
4728 	if (accb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
4729 		lp = &trtp->atios;
4730 	} else if (accb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
4731 		lp = &trtp->inots;
4732 	} else {
4733 		return (CAM_REQ_INVALID);
4734 	}
4735 
4736 	STAILQ_FOREACH(srch, lp, sim_links.stqe) {
4737 		if (srch == &accb->ccb_h) {
4738 			found = 1;
4739 			STAILQ_REMOVE(lp, srch, ccb_hdr, sim_links.stqe);
4740 			break;
4741 		}
4742 	}
4743 	if (found) {
4744 		accb->ccb_h.status = CAM_REQ_ABORTED;
4745 		xpt_done(accb);
4746 		return (CAM_REQ_CMP);
4747 	}
4748 	mpt_prt(mpt, "mpt_abort_tgt_ccb: CCB %p not found\n", ccb);
4749 	return (CAM_PATH_INVALID);
4750 }
4751 
4752 /*
4753  * Ask the MPT to abort the current target command
4754  */
4755 static int
4756 mpt_abort_target_cmd(struct mpt_softc *mpt, request_t *cmd_req)
4757 {
4758 	int error;
4759 	request_t *req;
4760 	PTR_MSG_TARGET_MODE_ABORT abtp;
4761 
4762 	req = mpt_get_request(mpt, FALSE);
4763 	if (req == NULL) {
4764 		return (-1);
4765 	}
4766 	abtp = req->req_vbuf;
4767 	memset(abtp, 0, sizeof (*abtp));
4768 
4769 	abtp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4770 	abtp->AbortType = TARGET_MODE_ABORT_TYPE_EXACT_IO;
4771 	abtp->Function = MPI_FUNCTION_TARGET_MODE_ABORT;
4772 	abtp->ReplyWord = htole32(MPT_TGT_STATE(mpt, cmd_req)->reply_desc);
4773 	error = 0;
4774 	if (mpt->is_fc || mpt->is_sas) {
4775 		mpt_send_cmd(mpt, req);
4776 	} else {
4777 		error = mpt_send_handshake_cmd(mpt, sizeof(*req), req);
4778 	}
4779 	return (error);
4780 }
4781 
4782 /*
4783  * WE_TRUST_AUTO_GOOD_STATUS- I've found that setting
4784  * TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS leads the
4785  * FC929 to set bogus FC_RSP fields (nonzero residuals
4786  * but w/o RESID fields set). This causes QLogic initiators
4787  * to think maybe that a frame was lost.
4788  *
4789  * WE_CAN_USE_AUTO_REPOST- we can't use AUTO_REPOST because
4790  * we use allocated requests to do TARGET_ASSIST and we
4791  * need to know when to release them.
4792  */
4793 
4794 static void
4795 mpt_scsi_tgt_status(struct mpt_softc *mpt, union ccb *ccb, request_t *cmd_req,
4796     uint8_t status, uint8_t const *sense_data)
4797 {
4798 	uint8_t *cmd_vbuf;
4799 	mpt_tgt_state_t *tgt;
4800 	PTR_MSG_TARGET_STATUS_SEND_REQUEST tp;
4801 	request_t *req;
4802 	bus_addr_t paddr;
4803 	int resplen = 0;
4804 	uint32_t fl;
4805 
4806 	cmd_vbuf = cmd_req->req_vbuf;
4807 	cmd_vbuf += MPT_RQSL(mpt);
4808 	tgt = MPT_TGT_STATE(mpt, cmd_req);
4809 
4810 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4811 		if (mpt->outofbeer == 0) {
4812 			mpt->outofbeer = 1;
4813 			xpt_freeze_simq(mpt->sim, 1);
4814 			mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4815 		}
4816 		if (ccb) {
4817 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4818 			mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4819 			MPTLOCK_2_CAMLOCK(mpt);
4820 			xpt_done(ccb);
4821 			CAMLOCK_2_MPTLOCK(mpt);
4822 		} else {
4823 			mpt_prt(mpt,
4824 			    "could not allocate status request- dropping\n");
4825 		}
4826 		return;
4827 	}
4828 	req->ccb = ccb;
4829 	if (ccb) {
4830 		ccb->ccb_h.ccb_mpt_ptr = mpt;
4831 		ccb->ccb_h.ccb_req_ptr = req;
4832 	}
4833 
4834 	/*
4835 	 * Record the currently active ccb, if any, and the
4836 	 * request for it in our target state area.
4837 	 */
4838 	tgt->ccb = ccb;
4839 	tgt->req = req;
4840 	tgt->state = TGT_STATE_SENDING_STATUS;
4841 
4842 	tp = req->req_vbuf;
4843 	paddr = req->req_pbuf;
4844 	paddr += MPT_RQSL(mpt);
4845 
4846 	memset(tp, 0, sizeof (*tp));
4847 	tp->Function = MPI_FUNCTION_TARGET_STATUS_SEND;
4848 	if (mpt->is_fc) {
4849 		PTR_MPI_TARGET_FCP_CMD_BUFFER fc =
4850 		    (PTR_MPI_TARGET_FCP_CMD_BUFFER) cmd_vbuf;
4851 		uint8_t *sts_vbuf;
4852 		uint32_t *rsp;
4853 
4854 		sts_vbuf = req->req_vbuf;
4855 		sts_vbuf += MPT_RQSL(mpt);
4856 		rsp = (uint32_t *) sts_vbuf;
4857 		memcpy(tp->LUN, fc->FcpLun, sizeof (tp->LUN));
4858 
4859 		/*
4860 		 * The MPI_TARGET_FCP_RSP_BUFFER define is unfortunate.
4861 		 * It has to be big-endian in memory and is organized
4862 		 * in 32 bit words, which are much easier to deal with
4863 		 * as words which are swizzled as needed.
4864 		 *
4865 		 * All we're filling here is the FC_RSP payload.
4866 		 * We may just have the chip synthesize it if
4867 		 * we have no residual and an OK status.
4868 		 *
4869 		 */
4870 		memset(rsp, 0, sizeof (MPI_TARGET_FCP_RSP_BUFFER));
4871 
4872 		rsp[2] = status;
4873 		if (tgt->resid) {
4874 			rsp[2] |= 0x800;	/* XXXX NEED MNEMONIC!!!! */
4875 			rsp[3] = htobe32(tgt->resid);
4876 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4877 			resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4878 #endif
4879 		}
4880 		if (status == SCSI_STATUS_CHECK_COND) {
4881 			int i;
4882 
4883 			rsp[2] |= 0x200;	/* XXXX NEED MNEMONIC!!!! */
4884 			rsp[4] = htobe32(MPT_SENSE_SIZE);
4885 			if (sense_data) {
4886 				memcpy(&rsp[8], sense_data, MPT_SENSE_SIZE);
4887 			} else {
4888 				mpt_prt(mpt, "mpt_scsi_tgt_status: CHECK CONDI"
4889 				    "TION but no sense data?\n");
4890 				memset(&rsp, 0, MPT_SENSE_SIZE);
4891 			}
4892 			for (i = 8; i < (8 + (MPT_SENSE_SIZE >> 2)); i++) {
4893 				rsp[i] = htobe32(rsp[i]);
4894 			}
4895 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4896 			resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4897 #endif
4898 		}
4899 #ifndef	WE_TRUST_AUTO_GOOD_STATUS
4900 		resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4901 #endif
4902 		rsp[2] = htobe32(rsp[2]);
4903 	} else if (mpt->is_sas) {
4904 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4905 		    (PTR_MPI_TARGET_SSP_CMD_BUFFER) cmd_vbuf;
4906 		memcpy(tp->LUN, ssp->LogicalUnitNumber, sizeof (tp->LUN));
4907 	} else {
4908 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4909 		    (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) cmd_vbuf;
4910 		tp->StatusCode = status;
4911 		tp->QueueTag = htole16(sp->Tag);
4912 		memcpy(tp->LUN, sp->LogicalUnitNumber, sizeof (tp->LUN));
4913 	}
4914 
4915 	tp->ReplyWord = htole32(tgt->reply_desc);
4916 	tp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4917 
4918 #ifdef	WE_CAN_USE_AUTO_REPOST
4919 	tp->MsgFlags = TARGET_STATUS_SEND_FLAGS_REPOST_CMD_BUFFER;
4920 #endif
4921 	if (status == SCSI_STATUS_OK && resplen == 0) {
4922 		tp->MsgFlags |= TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS;
4923 	} else {
4924 		tp->StatusDataSGE.u.Address32 = htole32((uint32_t) paddr);
4925 		fl =
4926 			MPI_SGE_FLAGS_HOST_TO_IOC	|
4927 			MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
4928 			MPI_SGE_FLAGS_LAST_ELEMENT	|
4929 			MPI_SGE_FLAGS_END_OF_LIST	|
4930 			MPI_SGE_FLAGS_END_OF_BUFFER;
4931 		fl <<= MPI_SGE_FLAGS_SHIFT;
4932 		fl |= resplen;
4933 		tp->StatusDataSGE.FlagsLength = htole32(fl);
4934 	}
4935 
4936 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4937 	    "STATUS_CCB %p (wit%s sense) tag %x req %p:%u resid %u\n",
4938 	    ccb, sense_data?"h" : "hout", ccb? ccb->csio.tag_id : -1, req,
4939 	    req->serno, tgt->resid);
4940 	if (ccb) {
4941 		ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4942 		mpt_req_timeout(req, 60 * hz, mpt_timeout, ccb);
4943 	}
4944 	mpt_send_cmd(mpt, req);
4945 }
4946 
4947 static void
4948 mpt_scsi_tgt_tsk_mgmt(struct mpt_softc *mpt, request_t *req, mpt_task_mgmt_t fc,
4949     tgt_resource_t *trtp, int init_id)
4950 {
4951 	struct ccb_immed_notify *inot;
4952 	mpt_tgt_state_t *tgt;
4953 
4954 	tgt = MPT_TGT_STATE(mpt, req);
4955 	inot = (struct ccb_immed_notify *) STAILQ_FIRST(&trtp->inots);
4956 	if (inot == NULL) {
4957 		mpt_lprt(mpt, MPT_PRT_WARN, "no INOTSs- sending back BSY\n");
4958 		mpt_scsi_tgt_status(mpt, NULL, req, SCSI_STATUS_BUSY, NULL);
4959 		return;
4960 	}
4961 	STAILQ_REMOVE_HEAD(&trtp->inots, sim_links.stqe);
4962 	mpt_lprt(mpt, MPT_PRT_DEBUG1,
4963 	    "Get FREE INOT %p lun %d\n", inot, inot->ccb_h.target_lun);
4964 
4965 	memset(&inot->sense_data, 0, sizeof (inot->sense_data));
4966 	inot->sense_len = 0;
4967 	memset(inot->message_args, 0, sizeof (inot->message_args));
4968 	inot->initiator_id = init_id;	/* XXX */
4969 
4970 	/*
4971 	 * This is a somewhat grotesque attempt to map from task management
4972 	 * to old style SCSI messages. God help us all.
4973 	 */
4974 	switch (fc) {
4975 	case MPT_ABORT_TASK_SET:
4976 		inot->message_args[0] = MSG_ABORT_TAG;
4977 		break;
4978 	case MPT_CLEAR_TASK_SET:
4979 		inot->message_args[0] = MSG_CLEAR_TASK_SET;
4980 		break;
4981 	case MPT_TARGET_RESET:
4982 		inot->message_args[0] = MSG_TARGET_RESET;
4983 		break;
4984 	case MPT_CLEAR_ACA:
4985 		inot->message_args[0] = MSG_CLEAR_ACA;
4986 		break;
4987 	case MPT_TERMINATE_TASK:
4988 		inot->message_args[0] = MSG_ABORT_TAG;
4989 		break;
4990 	default:
4991 		inot->message_args[0] = MSG_NOOP;
4992 		break;
4993 	}
4994 	tgt->ccb = (union ccb *) inot;
4995 	inot->ccb_h.status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
4996 	MPTLOCK_2_CAMLOCK(mpt);
4997 	xpt_done((union ccb *)inot);
4998 	CAMLOCK_2_MPTLOCK(mpt);
4999 }
5000 
5001 static void
5002 mpt_scsi_tgt_atio(struct mpt_softc *mpt, request_t *req, uint32_t reply_desc)
5003 {
5004 	static uint8_t null_iqd[SHORT_INQUIRY_LENGTH] = {
5005 	    0x7f, 0x00, 0x02, 0x02, 0x20, 0x00, 0x00, 0x32,
5006 	     'F',  'R',  'E',  'E',  'B',  'S',  'D',  ' ',
5007 	     'L',  'S',  'I',  '-',  'L',  'O',  'G',  'I',
5008 	     'C',  ' ',  'N',  'U',  'L',  'D',  'E',  'V',
5009 	     '0',  '0',  '0',  '1'
5010 	};
5011 	struct ccb_accept_tio *atiop;
5012 	lun_id_t lun;
5013 	int tag_action = 0;
5014 	mpt_tgt_state_t *tgt;
5015 	tgt_resource_t *trtp = NULL;
5016 	U8 *lunptr;
5017 	U8 *vbuf;
5018 	U16 itag;
5019 	U16 ioindex;
5020 	mpt_task_mgmt_t fct = MPT_NIL_TMT_VALUE;
5021 	uint8_t *cdbp;
5022 
5023 	/*
5024 	 * First, DMA sync the received command-
5025 	 * which is in the *request* * phys area.
5026 	 *
5027 	 * XXX: We could optimize this for a range
5028 	 */
5029 	bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
5030 	    BUS_DMASYNC_POSTREAD);
5031 
5032 	/*
5033 	 * Stash info for the current command where we can get at it later.
5034 	 */
5035 	vbuf = req->req_vbuf;
5036 	vbuf += MPT_RQSL(mpt);
5037 
5038 	/*
5039 	 * Get our state pointer set up.
5040 	 */
5041 	tgt = MPT_TGT_STATE(mpt, req);
5042 	if (tgt->state != TGT_STATE_LOADED) {
5043 		mpt_tgt_dump_req_state(mpt, req);
5044 		panic("bad target state in mpt_scsi_tgt_atio");
5045 	}
5046 	memset(tgt, 0, sizeof (mpt_tgt_state_t));
5047 	tgt->state = TGT_STATE_IN_CAM;
5048 	tgt->reply_desc = reply_desc;
5049 	ioindex = GET_IO_INDEX(reply_desc);
5050 	if (mpt->verbose >= MPT_PRT_DEBUG) {
5051 		mpt_dump_data(mpt, "mpt_scsi_tgt_atio response", vbuf,
5052 		    max(sizeof (MPI_TARGET_FCP_CMD_BUFFER),
5053 		    max(sizeof (MPI_TARGET_SSP_CMD_BUFFER),
5054 		    sizeof (MPI_TARGET_SCSI_SPI_CMD_BUFFER))));
5055 	}
5056 	if (mpt->is_fc) {
5057 		PTR_MPI_TARGET_FCP_CMD_BUFFER fc;
5058 		fc = (PTR_MPI_TARGET_FCP_CMD_BUFFER) vbuf;
5059 		if (fc->FcpCntl[2]) {
5060 			/*
5061 			 * Task Management Request
5062 			 */
5063 			switch (fc->FcpCntl[2]) {
5064 			case 0x2:
5065 				fct = MPT_ABORT_TASK_SET;
5066 				break;
5067 			case 0x4:
5068 				fct = MPT_CLEAR_TASK_SET;
5069 				break;
5070 			case 0x20:
5071 				fct = MPT_TARGET_RESET;
5072 				break;
5073 			case 0x40:
5074 				fct = MPT_CLEAR_ACA;
5075 				break;
5076 			case 0x80:
5077 				fct = MPT_TERMINATE_TASK;
5078 				break;
5079 			default:
5080 				mpt_prt(mpt, "CORRUPTED TASK MGMT BITS: 0x%x\n",
5081 				    fc->FcpCntl[2]);
5082 				mpt_scsi_tgt_status(mpt, 0, req,
5083 				    SCSI_STATUS_OK, 0);
5084 				return;
5085 			}
5086 		} else {
5087 			switch (fc->FcpCntl[1]) {
5088 			case 0:
5089 				tag_action = MSG_SIMPLE_Q_TAG;
5090 				break;
5091 			case 1:
5092 				tag_action = MSG_HEAD_OF_Q_TAG;
5093 				break;
5094 			case 2:
5095 				tag_action = MSG_ORDERED_Q_TAG;
5096 				break;
5097 			default:
5098 				/*
5099 				 * Bah. Ignore Untagged Queing and ACA
5100 				 */
5101 				tag_action = MSG_SIMPLE_Q_TAG;
5102 				break;
5103 			}
5104 		}
5105 		tgt->resid = be32toh(fc->FcpDl);
5106 		cdbp = fc->FcpCdb;
5107 		lunptr = fc->FcpLun;
5108 		itag = be16toh(fc->OptionalOxid);
5109 	} else if (mpt->is_sas) {
5110 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp;
5111 		ssp = (PTR_MPI_TARGET_SSP_CMD_BUFFER) vbuf;
5112 		cdbp = ssp->CDB;
5113 		lunptr = ssp->LogicalUnitNumber;
5114 		itag = ssp->InitiatorTag;
5115 	} else {
5116 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp;
5117 		sp = (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) vbuf;
5118 		cdbp = sp->CDB;
5119 		lunptr = sp->LogicalUnitNumber;
5120 		itag = sp->Tag;
5121 	}
5122 
5123 	/*
5124 	 * Generate a simple lun
5125 	 */
5126 	switch (lunptr[0] & 0xc0) {
5127 	case 0x40:
5128 		lun = ((lunptr[0] & 0x3f) << 8) | lunptr[1];
5129 		break;
5130 	case 0:
5131 		lun = lunptr[1];
5132 		break;
5133 	default:
5134 		mpt_lprt(mpt, MPT_PRT_ERROR, "cannot handle this type lun\n");
5135 		lun = 0xffff;
5136 		break;
5137 	}
5138 
5139 	/*
5140 	 * Deal with non-enabled or bad luns here.
5141 	 */
5142 	if (lun >= MPT_MAX_LUNS || mpt->tenabled == 0 ||
5143 	    mpt->trt[lun].enabled == 0) {
5144 		if (mpt->twildcard) {
5145 			trtp = &mpt->trt_wildcard;
5146 		} else if (fct == MPT_NIL_TMT_VALUE) {
5147 			/*
5148 			 * In this case, we haven't got an upstream listener
5149 			 * for either a specific lun or wildcard luns. We
5150 			 * have to make some sensible response. For regular
5151 			 * inquiry, just return some NOT HERE inquiry data.
5152 			 * For VPD inquiry, report illegal field in cdb.
5153 			 * For REQUEST SENSE, just return NO SENSE data.
5154 			 * REPORT LUNS gets illegal command.
5155 			 * All other commands get 'no such device'.
5156 			 */
5157 			uint8_t *sp, cond, buf[MPT_SENSE_SIZE];
5158 			size_t len;
5159 
5160 			memset(buf, 0, MPT_SENSE_SIZE);
5161 			cond = SCSI_STATUS_CHECK_COND;
5162 			buf[0] = 0xf0;
5163 			buf[2] = 0x5;
5164 			buf[7] = 0x8;
5165 			sp = buf;
5166 			tgt->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5167 
5168 			switch (cdbp[0]) {
5169 			case INQUIRY:
5170 			{
5171 				if (cdbp[1] != 0) {
5172 					buf[12] = 0x26;
5173 					buf[13] = 0x01;
5174 					break;
5175 				}
5176 				len = min(tgt->resid, cdbp[4]);
5177 				len = min(len, sizeof (null_iqd));
5178 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5179 				    "local inquiry %ld bytes\n", (long) len);
5180 				mpt_scsi_tgt_local(mpt, req, lun, 1,
5181 				    null_iqd, len);
5182 				return;
5183 			}
5184 			case REQUEST_SENSE:
5185 			{
5186 				buf[2] = 0x0;
5187 				len = min(tgt->resid, cdbp[4]);
5188 				len = min(len, sizeof (buf));
5189 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5190 				    "local reqsense %ld bytes\n", (long) len);
5191 				mpt_scsi_tgt_local(mpt, req, lun, 1,
5192 				    buf, len);
5193 				return;
5194 			}
5195 			case REPORT_LUNS:
5196 				mpt_lprt(mpt, MPT_PRT_DEBUG, "REPORT LUNS\n");
5197 				buf[12] = 0x26;
5198 				return;
5199 			default:
5200 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5201 				    "CMD 0x%x to unmanaged lun %u\n",
5202 				    cdbp[0], lun);
5203 				buf[12] = 0x25;
5204 				break;
5205 			}
5206 			mpt_scsi_tgt_status(mpt, NULL, req, cond, sp);
5207 			return;
5208 		}
5209 		/* otherwise, leave trtp NULL */
5210 	} else {
5211 		trtp = &mpt->trt[lun];
5212 	}
5213 
5214 	/*
5215 	 * Deal with any task management
5216 	 */
5217 	if (fct != MPT_NIL_TMT_VALUE) {
5218 		if (trtp == NULL) {
5219 			mpt_prt(mpt, "task mgmt function %x but no listener\n",
5220 			    fct);
5221 			mpt_scsi_tgt_status(mpt, 0, req,
5222 			    SCSI_STATUS_OK, 0);
5223 		} else {
5224 			mpt_scsi_tgt_tsk_mgmt(mpt, req, fct, trtp,
5225 			    GET_INITIATOR_INDEX(reply_desc));
5226 		}
5227 		return;
5228 	}
5229 
5230 
5231 	atiop = (struct ccb_accept_tio *) STAILQ_FIRST(&trtp->atios);
5232 	if (atiop == NULL) {
5233 		mpt_lprt(mpt, MPT_PRT_WARN,
5234 		    "no ATIOs for lun %u- sending back %s\n", lun,
5235 		    mpt->tenabled? "QUEUE FULL" : "BUSY");
5236 		mpt_scsi_tgt_status(mpt, NULL, req,
5237 		    mpt->tenabled? SCSI_STATUS_QUEUE_FULL : SCSI_STATUS_BUSY,
5238 		    NULL);
5239 		return;
5240 	}
5241 	STAILQ_REMOVE_HEAD(&trtp->atios, sim_links.stqe);
5242 	mpt_lprt(mpt, MPT_PRT_DEBUG1,
5243 	    "Get FREE ATIO %p lun %d\n", atiop, atiop->ccb_h.target_lun);
5244 	atiop->ccb_h.ccb_mpt_ptr = mpt;
5245 	atiop->ccb_h.status = CAM_CDB_RECVD;
5246 	atiop->ccb_h.target_lun = lun;
5247 	atiop->sense_len = 0;
5248 	atiop->init_id = GET_INITIATOR_INDEX(reply_desc);
5249 	atiop->cdb_len = mpt_cdblen(cdbp[0], 16);
5250 	memcpy(atiop->cdb_io.cdb_bytes, cdbp, atiop->cdb_len);
5251 
5252 	/*
5253 	 * The tag we construct here allows us to find the
5254 	 * original request that the command came in with.
5255 	 *
5256 	 * This way we don't have to depend on anything but the
5257 	 * tag to find things when CCBs show back up from CAM.
5258 	 */
5259 	atiop->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5260 	tgt->tag_id = atiop->tag_id;
5261 	if (tag_action) {
5262 		atiop->tag_action = tag_action;
5263 		atiop->ccb_h.flags = CAM_TAG_ACTION_VALID;
5264 	}
5265 	if (mpt->verbose >= MPT_PRT_DEBUG) {
5266 		int i;
5267 		mpt_prt(mpt, "START_CCB %p for lun %u CDB=<", atiop,
5268 		    atiop->ccb_h.target_lun);
5269 		for (i = 0; i < atiop->cdb_len; i++) {
5270 			mpt_prtc(mpt, "%02x%c", cdbp[i] & 0xff,
5271 			    (i == (atiop->cdb_len - 1))? '>' : ' ');
5272 		}
5273 		mpt_prtc(mpt, " itag %x tag %x rdesc %x dl=%u\n",
5274 	    	    itag, atiop->tag_id, tgt->reply_desc, tgt->resid);
5275 	}
5276 
5277 	MPTLOCK_2_CAMLOCK(mpt);
5278 	xpt_done((union ccb *)atiop);
5279 	CAMLOCK_2_MPTLOCK(mpt);
5280 }
5281 
5282 static void
5283 mpt_tgt_dump_tgt_state(struct mpt_softc *mpt, request_t *req)
5284 {
5285 	mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5286 
5287 	mpt_prt(mpt, "req %p:%u tgt:rdesc 0x%x resid %u xfrd %u ccb %p treq %p "
5288 	    "nx %d tag 0x%08x state=%d\n", req, req->serno, tgt->reply_desc,
5289 	    tgt->resid, tgt->bytes_xfered, tgt->ccb, tgt->req, tgt->nxfers,
5290 	    tgt->tag_id, tgt->state);
5291 }
5292 
5293 static void
5294 mpt_tgt_dump_req_state(struct mpt_softc *mpt, request_t *req)
5295 {
5296 	mpt_prt(mpt, "req %p:%u index %u (%x) state %x\n", req, req->serno,
5297 	    req->index, req->index, req->state);
5298 	mpt_tgt_dump_tgt_state(mpt, req);
5299 }
5300 
5301 static int
5302 mpt_scsi_tgt_reply_handler(struct mpt_softc *mpt, request_t *req,
5303     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
5304 {
5305 	int dbg;
5306 	union ccb *ccb;
5307 	U16 status;
5308 
5309 	if (reply_frame == NULL) {
5310 		/*
5311 		 * Figure out what the state of the command is.
5312 		 */
5313 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5314 
5315 #ifdef	INVARIANTS
5316 		mpt_req_spcl(mpt, req, "turbo scsi_tgt_reply", __LINE__);
5317 		if (tgt->req) {
5318 			mpt_req_not_spcl(mpt, tgt->req,
5319 			    "turbo scsi_tgt_reply associated req", __LINE__);
5320 		}
5321 #endif
5322 		switch(tgt->state) {
5323 		case TGT_STATE_LOADED:
5324 			/*
5325 			 * This is a new command starting.
5326 			 */
5327 			mpt_scsi_tgt_atio(mpt, req, reply_desc);
5328 			break;
5329 		case TGT_STATE_MOVING_DATA:
5330 		{
5331 			uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
5332 
5333 			ccb = tgt->ccb;
5334 			if (tgt->req == NULL) {
5335 				panic("mpt: turbo target reply with null "
5336 				    "associated request moving data");
5337 				/* NOTREACHED */
5338 			}
5339 			if (ccb == NULL) {
5340 				if (tgt->is_local == 0) {
5341 					panic("mpt: turbo target reply with "
5342 					    "null associated ccb moving data");
5343 					/* NOTREACHED */
5344 				}
5345 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5346 				    "TARGET_ASSIST local done\n");
5347 				TAILQ_REMOVE(&mpt->request_pending_list,
5348 				    tgt->req, links);
5349 				mpt_free_request(mpt, tgt->req);
5350 				tgt->req = NULL;
5351 				mpt_scsi_tgt_status(mpt, NULL, req,
5352 				    0, NULL);
5353 				return (TRUE);
5354 			}
5355 			tgt->ccb = NULL;
5356 			tgt->nxfers++;
5357 			mpt_req_untimeout(req, mpt_timeout, ccb);
5358 			mpt_lprt(mpt, MPT_PRT_DEBUG,
5359 			    "TARGET_ASSIST %p (req %p:%u) done tag 0x%x\n",
5360 			    ccb, tgt->req, tgt->req->serno, ccb->csio.tag_id);
5361 			/*
5362 			 * Free the Target Assist Request
5363 			 */
5364 			KASSERT(tgt->req->ccb == ccb,
5365 			    ("tgt->req %p:%u tgt->req->ccb %p", tgt->req,
5366 			    tgt->req->serno, tgt->req->ccb));
5367 			TAILQ_REMOVE(&mpt->request_pending_list,
5368 			    tgt->req, links);
5369 			mpt_free_request(mpt, tgt->req);
5370 			tgt->req = NULL;
5371 
5372 			/*
5373 			 * Do we need to send status now? That is, are
5374 			 * we done with all our data transfers?
5375 			 */
5376 			if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
5377 				mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5378 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5379 				KASSERT(ccb->ccb_h.status,
5380 				    ("zero ccb sts at %d\n", __LINE__));
5381 				tgt->state = TGT_STATE_IN_CAM;
5382 				if (mpt->outofbeer) {
5383 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5384 					mpt->outofbeer = 0;
5385 					mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5386 				}
5387 				MPTLOCK_2_CAMLOCK(mpt);
5388 				xpt_done(ccb);
5389 				CAMLOCK_2_MPTLOCK(mpt);
5390 				break;
5391 			}
5392 			/*
5393 			 * Otherwise, send status (and sense)
5394 			 */
5395 			if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5396 				sp = sense;
5397 				memcpy(sp, &ccb->csio.sense_data,
5398 				   min(ccb->csio.sense_len, MPT_SENSE_SIZE));
5399 			}
5400 			mpt_scsi_tgt_status(mpt, ccb, req,
5401 			    ccb->csio.scsi_status, sp);
5402 			break;
5403 		}
5404 		case TGT_STATE_SENDING_STATUS:
5405 		case TGT_STATE_MOVING_DATA_AND_STATUS:
5406 		{
5407 			int ioindex;
5408 			ccb = tgt->ccb;
5409 
5410 			if (tgt->req == NULL) {
5411 				panic("mpt: turbo target reply with null "
5412 				    "associated request sending status");
5413 				/* NOTREACHED */
5414 			}
5415 
5416 			if (ccb) {
5417 				tgt->ccb = NULL;
5418 				if (tgt->state ==
5419 				    TGT_STATE_MOVING_DATA_AND_STATUS) {
5420 					tgt->nxfers++;
5421 				}
5422 				mpt_req_untimeout(req, mpt_timeout, ccb);
5423 				if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5424 					ccb->ccb_h.status |= CAM_SENT_SENSE;
5425 				}
5426 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5427 				    "TARGET_STATUS tag %x sts %x flgs %x req "
5428 				    "%p\n", ccb->csio.tag_id, ccb->ccb_h.status,
5429 				    ccb->ccb_h.flags, tgt->req);
5430 				/*
5431 				 * Free the Target Send Status Request
5432 				 */
5433 				KASSERT(tgt->req->ccb == ccb,
5434 				    ("tgt->req %p:%u tgt->req->ccb %p",
5435 				    tgt->req, tgt->req->serno, tgt->req->ccb));
5436 				/*
5437 				 * Notify CAM that we're done
5438 				 */
5439 				mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5440 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5441 				KASSERT(ccb->ccb_h.status,
5442 				    ("ZERO ccb sts at %d\n", __LINE__));
5443 				tgt->ccb = NULL;
5444 			} else {
5445 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5446 				    "TARGET_STATUS non-CAM for  req %p:%u\n",
5447 				    tgt->req, tgt->req->serno);
5448 			}
5449 			TAILQ_REMOVE(&mpt->request_pending_list,
5450 			    tgt->req, links);
5451 			mpt_free_request(mpt, tgt->req);
5452 			tgt->req = NULL;
5453 
5454 			/*
5455 			 * And re-post the Command Buffer.
5456 			 * This will reset the state.
5457 			 */
5458 			ioindex = GET_IO_INDEX(reply_desc);
5459 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5460 			tgt->is_local = 0;
5461 			mpt_post_target_command(mpt, req, ioindex);
5462 
5463 			/*
5464 			 * And post a done for anyone who cares
5465 			 */
5466 			if (ccb) {
5467 				if (mpt->outofbeer) {
5468 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5469 					mpt->outofbeer = 0;
5470 					mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5471 				}
5472 				MPTLOCK_2_CAMLOCK(mpt);
5473 				xpt_done(ccb);
5474 				CAMLOCK_2_MPTLOCK(mpt);
5475 			}
5476 			break;
5477 		}
5478 		case TGT_STATE_NIL:	/* XXX This Never Happens XXX */
5479 			tgt->state = TGT_STATE_LOADED;
5480 			break;
5481 		default:
5482 			mpt_prt(mpt, "Unknown Target State 0x%x in Context "
5483 			    "Reply Function\n", tgt->state);
5484 		}
5485 		return (TRUE);
5486 	}
5487 
5488 	status = le16toh(reply_frame->IOCStatus);
5489 	if (status != MPI_IOCSTATUS_SUCCESS) {
5490 		dbg = MPT_PRT_ERROR;
5491 	} else {
5492 		dbg = MPT_PRT_DEBUG1;
5493 	}
5494 
5495 	mpt_lprt(mpt, dbg,
5496 	    "SCSI_TGT REPLY: req=%p:%u reply=%p func=%x IOCstatus 0x%x\n",
5497 	     req, req->serno, reply_frame, reply_frame->Function, status);
5498 
5499 	switch (reply_frame->Function) {
5500 	case MPI_FUNCTION_TARGET_CMD_BUFFER_POST:
5501 	{
5502 		mpt_tgt_state_t *tgt;
5503 #ifdef	INVARIANTS
5504 		mpt_req_spcl(mpt, req, "tgt reply BUFFER POST", __LINE__);
5505 #endif
5506 		if (status != MPI_IOCSTATUS_SUCCESS) {
5507 			/*
5508 			 * XXX What to do?
5509 			 */
5510 			break;
5511 		}
5512 		tgt = MPT_TGT_STATE(mpt, req);
5513 		KASSERT(tgt->state == TGT_STATE_LOADING,
5514 		    ("bad state 0x%x on reply to buffer post\n", tgt->state));
5515 		mpt_assign_serno(mpt, req);
5516 		tgt->state = TGT_STATE_LOADED;
5517 		break;
5518 	}
5519 	case MPI_FUNCTION_TARGET_ASSIST:
5520 #ifdef	INVARIANTS
5521 		mpt_req_not_spcl(mpt, req, "tgt reply TARGET ASSIST", __LINE__);
5522 #endif
5523 		mpt_prt(mpt, "target assist completion\n");
5524 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5525 		mpt_free_request(mpt, req);
5526 		break;
5527 	case MPI_FUNCTION_TARGET_STATUS_SEND:
5528 #ifdef	INVARIANTS
5529 		mpt_req_not_spcl(mpt, req, "tgt reply STATUS SEND", __LINE__);
5530 #endif
5531 		mpt_prt(mpt, "status send completion\n");
5532 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5533 		mpt_free_request(mpt, req);
5534 		break;
5535 	case MPI_FUNCTION_TARGET_MODE_ABORT:
5536 	{
5537 		PTR_MSG_TARGET_MODE_ABORT_REPLY abtrp =
5538 		    (PTR_MSG_TARGET_MODE_ABORT_REPLY) reply_frame;
5539 		PTR_MSG_TARGET_MODE_ABORT abtp =
5540 		    (PTR_MSG_TARGET_MODE_ABORT) req->req_vbuf;
5541 		uint32_t cc = GET_IO_INDEX(le32toh(abtp->ReplyWord));
5542 #ifdef	INVARIANTS
5543 		mpt_req_not_spcl(mpt, req, "tgt reply TMODE ABORT", __LINE__);
5544 #endif
5545 		mpt_prt(mpt, "ABORT RX_ID 0x%x Complete; status 0x%x cnt %u\n",
5546 		    cc, le16toh(abtrp->IOCStatus), le32toh(abtrp->AbortCount));
5547 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5548 		mpt_free_request(mpt, req);
5549 		break;
5550 	}
5551 	default:
5552 		mpt_prt(mpt, "Unknown Target Address Reply Function code: "
5553 		    "0x%x\n", reply_frame->Function);
5554 		break;
5555 	}
5556 	return (TRUE);
5557 }
5558