xref: /freebsd/sys/dev/mpt/mpt_cam.c (revision 9fd69f37d28cfd7438cac3eeb45fe9dd46b4d7dd)
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 		xpt_bus_deregister(cam_sim_path(mpt->sim));
1212 		cam_sim_free(mpt->sim, TRUE);
1213 		mpt->sim = NULL;
1214 	}
1215 
1216 	if (mpt->phydisk_sim != NULL) {
1217 		xpt_free_path(mpt->phydisk_path);
1218 		xpt_bus_deregister(cam_sim_path(mpt->phydisk_sim));
1219 		cam_sim_free(mpt->phydisk_sim, TRUE);
1220 		mpt->phydisk_sim = NULL;
1221 	}
1222 }
1223 
1224 /* This routine is used after a system crash to dump core onto the swap device.
1225  */
1226 static void
1227 mpt_poll(struct cam_sim *sim)
1228 {
1229 	struct mpt_softc *mpt;
1230 
1231 	mpt = (struct mpt_softc *)cam_sim_softc(sim);
1232 	mpt_intr(mpt);
1233 }
1234 
1235 /*
1236  * Watchdog timeout routine for SCSI requests.
1237  */
1238 static void
1239 mpt_timeout(void *arg)
1240 {
1241 	union ccb	 *ccb;
1242 	struct mpt_softc *mpt;
1243 	request_t	 *req;
1244 
1245 	ccb = (union ccb *)arg;
1246 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1247 
1248 #if __FreeBSD_version < 500000
1249 	MPT_LOCK(mpt);
1250 #endif
1251 	MPT_LOCK_ASSERT(mpt);
1252 	req = ccb->ccb_h.ccb_req_ptr;
1253 	mpt_prt(mpt, "request %p:%u timed out for ccb %p (req->ccb %p)\n", req,
1254 	    req->serno, ccb, req->ccb);
1255 /* XXX: WHAT ARE WE TRYING TO DO HERE? */
1256 	if ((req->state & REQ_STATE_QUEUED) == REQ_STATE_QUEUED) {
1257 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
1258 		TAILQ_INSERT_TAIL(&mpt->request_timeout_list, req, links);
1259 		req->state |= REQ_STATE_TIMEDOUT;
1260 		mpt_wakeup_recovery_thread(mpt);
1261 	}
1262 #if __FreeBSD_version < 500000
1263 	MPT_UNLOCK(mpt);
1264 #endif
1265 }
1266 
1267 /*
1268  * Callback routine from "bus_dmamap_load" or, in simple cases, called directly.
1269  *
1270  * Takes a list of physical segments and builds the SGL for SCSI IO command
1271  * and forwards the commard to the IOC after one last check that CAM has not
1272  * aborted the transaction.
1273  */
1274 static void
1275 mpt_execute_req_a64(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1276 {
1277 	request_t *req, *trq;
1278 	char *mpt_off;
1279 	union ccb *ccb;
1280 	struct mpt_softc *mpt;
1281 	int seg, first_lim;
1282 	uint32_t flags, nxt_off;
1283 	void *sglp = NULL;
1284 	MSG_REQUEST_HEADER *hdrp;
1285 	SGE_SIMPLE64 *se;
1286 	SGE_CHAIN64 *ce;
1287 	int istgt = 0;
1288 
1289 	req = (request_t *)arg;
1290 	ccb = req->ccb;
1291 
1292 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1293 	req = ccb->ccb_h.ccb_req_ptr;
1294 
1295 	hdrp = req->req_vbuf;
1296 	mpt_off = req->req_vbuf;
1297 
1298 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1299 		error = EFBIG;
1300 	}
1301 
1302 	if (error == 0) {
1303 		switch (hdrp->Function) {
1304 		case MPI_FUNCTION_SCSI_IO_REQUEST:
1305 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1306 			istgt = 0;
1307 			sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1308 			break;
1309 		case MPI_FUNCTION_TARGET_ASSIST:
1310 			istgt = 1;
1311 			sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1312 			break;
1313 		default:
1314 			mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req_a64\n",
1315 			    hdrp->Function);
1316 			error = EINVAL;
1317 			break;
1318 		}
1319 	}
1320 
1321 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1322 		error = EFBIG;
1323 		mpt_prt(mpt, "segment count %d too large (max %u)\n",
1324 		    nseg, mpt->max_seg_cnt);
1325 	}
1326 
1327 bad:
1328 	if (error != 0) {
1329 		if (error != EFBIG && error != ENOMEM) {
1330 			mpt_prt(mpt, "mpt_execute_req_a64: err %d\n", error);
1331 		}
1332 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1333 			cam_status status;
1334 			mpt_freeze_ccb(ccb);
1335 			if (error == EFBIG) {
1336 				status = CAM_REQ_TOO_BIG;
1337 			} else if (error == ENOMEM) {
1338 				if (mpt->outofbeer == 0) {
1339 					mpt->outofbeer = 1;
1340 					xpt_freeze_simq(mpt->sim, 1);
1341 					mpt_lprt(mpt, MPT_PRT_DEBUG,
1342 					    "FREEZEQ\n");
1343 				}
1344 				status = CAM_REQUEUE_REQ;
1345 			} else {
1346 				status = CAM_REQ_CMP_ERR;
1347 			}
1348 			mpt_set_ccb_status(ccb, status);
1349 		}
1350 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1351 			request_t *cmd_req =
1352 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1353 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1354 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1355 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1356 		}
1357 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1358 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1359 		xpt_done(ccb);
1360 		CAMLOCK_2_MPTLOCK(mpt);
1361 		mpt_free_request(mpt, req);
1362 		MPTLOCK_2_CAMLOCK(mpt);
1363 		return;
1364 	}
1365 
1366 	/*
1367 	 * No data to transfer?
1368 	 * Just make a single simple SGL with zero length.
1369 	 */
1370 
1371 	if (mpt->verbose >= MPT_PRT_DEBUG) {
1372 		int tidx = ((char *)sglp) - mpt_off;
1373 		memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1374 	}
1375 
1376 	if (nseg == 0) {
1377 		SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1378 		MPI_pSGE_SET_FLAGS(se1,
1379 		    (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1380 		    MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1381 		se1->FlagsLength = htole32(se1->FlagsLength);
1382 		goto out;
1383 	}
1384 
1385 
1386 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1387 	if (istgt == 0) {
1388 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1389 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1390 		}
1391 	} else {
1392 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1393 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1394 		}
1395 	}
1396 
1397 	if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1398 		bus_dmasync_op_t op;
1399 		if (istgt == 0) {
1400 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1401 				op = BUS_DMASYNC_PREREAD;
1402 			} else {
1403 				op = BUS_DMASYNC_PREWRITE;
1404 			}
1405 		} else {
1406 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1407 				op = BUS_DMASYNC_PREWRITE;
1408 			} else {
1409 				op = BUS_DMASYNC_PREREAD;
1410 			}
1411 		}
1412 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1413 	}
1414 
1415 	/*
1416 	 * Okay, fill in what we can at the end of the command frame.
1417 	 * If we have up to MPT_NSGL_FIRST, we can fit them all into
1418 	 * the command frame.
1419 	 *
1420 	 * Otherwise, we fill up through MPT_NSGL_FIRST less one
1421 	 * SIMPLE64 pointers and start doing CHAIN64 entries after
1422 	 * that.
1423 	 */
1424 
1425 	if (nseg < MPT_NSGL_FIRST(mpt)) {
1426 		first_lim = nseg;
1427 	} else {
1428 		/*
1429 		 * Leave room for CHAIN element
1430 		 */
1431 		first_lim = MPT_NSGL_FIRST(mpt) - 1;
1432 	}
1433 
1434 	se = (SGE_SIMPLE64 *) sglp;
1435 	for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1436 		uint32_t tf;
1437 
1438 		memset(se, 0, sizeof (*se));
1439 		se->Address.Low = htole32(dm_segs->ds_addr & 0xffffffff);
1440 		if (sizeof(bus_addr_t) > 4) {
1441 			se->Address.High =
1442 			    htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1443 		}
1444 		MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1445 		tf = flags;
1446 		if (seg == first_lim - 1) {
1447 			tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1448 		}
1449 		if (seg == nseg - 1) {
1450 			tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1451 				MPI_SGE_FLAGS_END_OF_BUFFER;
1452 		}
1453 		MPI_pSGE_SET_FLAGS(se, tf);
1454 		se->FlagsLength = htole32(se->FlagsLength);
1455 	}
1456 
1457 	if (seg == nseg) {
1458 		goto out;
1459 	}
1460 
1461 	/*
1462 	 * Tell the IOC where to find the first chain element.
1463 	 */
1464 	hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1465 	nxt_off = MPT_RQSL(mpt);
1466 	trq = req;
1467 
1468 	/*
1469 	 * Make up the rest of the data segments out of a chain element
1470 	 * (contiained in the current request frame) which points to
1471 	 * SIMPLE64 elements in the next request frame, possibly ending
1472 	 * with *another* chain element (if there's more).
1473 	 */
1474 	while (seg < nseg) {
1475 		int this_seg_lim;
1476 		uint32_t tf, cur_off;
1477 		bus_addr_t chain_list_addr;
1478 
1479 		/*
1480 		 * Point to the chain descriptor. Note that the chain
1481 		 * descriptor is at the end of the *previous* list (whether
1482 		 * chain or simple).
1483 		 */
1484 		ce = (SGE_CHAIN64 *) se;
1485 
1486 		/*
1487 		 * Before we change our current pointer, make  sure we won't
1488 		 * overflow the request area with this frame. Note that we
1489 		 * test against 'greater than' here as it's okay in this case
1490 		 * to have next offset be just outside the request area.
1491 		 */
1492 		if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1493 			nxt_off = MPT_REQUEST_AREA;
1494 			goto next_chain;
1495 		}
1496 
1497 		/*
1498 		 * Set our SGE element pointer to the beginning of the chain
1499 		 * list and update our next chain list offset.
1500 		 */
1501 		se = (SGE_SIMPLE64 *) &mpt_off[nxt_off];
1502 		cur_off = nxt_off;
1503 		nxt_off += MPT_RQSL(mpt);
1504 
1505 		/*
1506 		 * Now initialized the chain descriptor.
1507 		 */
1508 		memset(ce, 0, sizeof (*ce));
1509 
1510 		/*
1511 		 * Get the physical address of the chain list.
1512 		 */
1513 		chain_list_addr = trq->req_pbuf;
1514 		chain_list_addr += cur_off;
1515 		if (sizeof (bus_addr_t) > 4) {
1516 			ce->Address.High =
1517 			    htole32(((uint64_t)chain_list_addr) >> 32);
1518 		}
1519 		ce->Address.Low = htole32(chain_list_addr & 0xffffffff);
1520 		ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT |
1521 			    MPI_SGE_FLAGS_64_BIT_ADDRESSING;
1522 
1523 		/*
1524 		 * If we have more than a frame's worth of segments left,
1525 		 * set up the chain list to have the last element be another
1526 		 * chain descriptor.
1527 		 */
1528 		if ((nseg - seg) > MPT_NSGL(mpt)) {
1529 			this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1530 			/*
1531 			 * The length of the chain is the length in bytes of the
1532 			 * number of segments plus the next chain element.
1533 			 *
1534 			 * The next chain descriptor offset is the length,
1535 			 * in words, of the number of segments.
1536 			 */
1537 			ce->Length = (this_seg_lim - seg) *
1538 			    sizeof (SGE_SIMPLE64);
1539 			ce->NextChainOffset = ce->Length >> 2;
1540 			ce->Length += sizeof (SGE_CHAIN64);
1541 		} else {
1542 			this_seg_lim = nseg;
1543 			ce->Length = (this_seg_lim - seg) *
1544 			    sizeof (SGE_SIMPLE64);
1545 		}
1546 		ce->Length = htole16(ce->Length);
1547 
1548 		/*
1549 		 * Fill in the chain list SGE elements with our segment data.
1550 		 *
1551 		 * If we're the last element in this chain list, set the last
1552 		 * element flag. If we're the completely last element period,
1553 		 * set the end of list and end of buffer flags.
1554 		 */
1555 		while (seg < this_seg_lim) {
1556 			memset(se, 0, sizeof (*se));
1557 			se->Address.Low = htole32(dm_segs->ds_addr &
1558 			    0xffffffff);
1559 			if (sizeof (bus_addr_t) > 4) {
1560 				se->Address.High =
1561 				    htole32(((uint64_t)dm_segs->ds_addr) >> 32);
1562 			}
1563 			MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1564 			tf = flags;
1565 			if (seg ==  this_seg_lim - 1) {
1566 				tf |=	MPI_SGE_FLAGS_LAST_ELEMENT;
1567 			}
1568 			if (seg == nseg - 1) {
1569 				tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1570 					MPI_SGE_FLAGS_END_OF_BUFFER;
1571 			}
1572 			MPI_pSGE_SET_FLAGS(se, tf);
1573 			se->FlagsLength = htole32(se->FlagsLength);
1574 			se++;
1575 			seg++;
1576 			dm_segs++;
1577 		}
1578 
1579     next_chain:
1580 		/*
1581 		 * If we have more segments to do and we've used up all of
1582 		 * the space in a request area, go allocate another one
1583 		 * and chain to that.
1584 		 */
1585 		if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1586 			request_t *nrq;
1587 
1588 			CAMLOCK_2_MPTLOCK(mpt);
1589 			nrq = mpt_get_request(mpt, FALSE);
1590 			MPTLOCK_2_CAMLOCK(mpt);
1591 
1592 			if (nrq == NULL) {
1593 				error = ENOMEM;
1594 				goto bad;
1595 			}
1596 
1597 			/*
1598 			 * Append the new request area on the tail of our list.
1599 			 */
1600 			if ((trq = req->chain) == NULL) {
1601 				req->chain = nrq;
1602 			} else {
1603 				while (trq->chain != NULL) {
1604 					trq = trq->chain;
1605 				}
1606 				trq->chain = nrq;
1607 			}
1608 			trq = nrq;
1609 			mpt_off = trq->req_vbuf;
1610 			if (mpt->verbose >= MPT_PRT_DEBUG) {
1611 				memset(mpt_off, 0xff, MPT_REQUEST_AREA);
1612 			}
1613 			nxt_off = 0;
1614 		}
1615 	}
1616 out:
1617 
1618 	/*
1619 	 * Last time we need to check if this CCB needs to be aborted.
1620 	 */
1621 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
1622 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1623 			request_t *cmd_req =
1624 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1625 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1626 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1627 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1628 		}
1629 		mpt_prt(mpt,
1630 		    "mpt_execute_req_a64: I/O cancelled (status 0x%x)\n",
1631 		    ccb->ccb_h.status & CAM_STATUS_MASK);
1632 		if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
1633 			bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
1634 		}
1635 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1636 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1637 		xpt_done(ccb);
1638 		CAMLOCK_2_MPTLOCK(mpt);
1639 		mpt_free_request(mpt, req);
1640 		MPTLOCK_2_CAMLOCK(mpt);
1641 		return;
1642 	}
1643 
1644 	ccb->ccb_h.status |= CAM_SIM_QUEUED;
1645 	if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
1646 		mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
1647 		    mpt_timeout, ccb);
1648 	}
1649 	if (mpt->verbose > MPT_PRT_DEBUG) {
1650 		int nc = 0;
1651 		mpt_print_request(req->req_vbuf);
1652 		for (trq = req->chain; trq; trq = trq->chain) {
1653 			printf("  Additional Chain Area %d\n", nc++);
1654 			mpt_dump_sgl(trq->req_vbuf, 0);
1655 		}
1656 	}
1657 
1658 	if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1659 		request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1660 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
1661 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
1662 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1663 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
1664 			tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
1665 		} else {
1666 			tgt->state = TGT_STATE_MOVING_DATA;
1667 		}
1668 #else
1669 		tgt->state = TGT_STATE_MOVING_DATA;
1670 #endif
1671 	}
1672 	CAMLOCK_2_MPTLOCK(mpt);
1673 	mpt_send_cmd(mpt, req);
1674 	MPTLOCK_2_CAMLOCK(mpt);
1675 }
1676 
1677 static void
1678 mpt_execute_req(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
1679 {
1680 	request_t *req, *trq;
1681 	char *mpt_off;
1682 	union ccb *ccb;
1683 	struct mpt_softc *mpt;
1684 	int seg, first_lim;
1685 	uint32_t flags, nxt_off;
1686 	void *sglp = NULL;
1687 	MSG_REQUEST_HEADER *hdrp;
1688 	SGE_SIMPLE32 *se;
1689 	SGE_CHAIN32 *ce;
1690 	int istgt = 0;
1691 
1692 	req = (request_t *)arg;
1693 	ccb = req->ccb;
1694 
1695 	mpt = ccb->ccb_h.ccb_mpt_ptr;
1696 	req = ccb->ccb_h.ccb_req_ptr;
1697 
1698 	hdrp = req->req_vbuf;
1699 	mpt_off = req->req_vbuf;
1700 
1701 
1702 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1703 		error = EFBIG;
1704 	}
1705 
1706 	if (error == 0) {
1707 		switch (hdrp->Function) {
1708 		case MPI_FUNCTION_SCSI_IO_REQUEST:
1709 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
1710 			sglp = &((PTR_MSG_SCSI_IO_REQUEST)hdrp)->SGL;
1711 			break;
1712 		case MPI_FUNCTION_TARGET_ASSIST:
1713 			istgt = 1;
1714 			sglp = &((PTR_MSG_TARGET_ASSIST_REQUEST)hdrp)->SGL;
1715 			break;
1716 		default:
1717 			mpt_prt(mpt, "bad fct 0x%x in mpt_execute_req\n",
1718 			    hdrp->Function);
1719 			error = EINVAL;
1720 			break;
1721 		}
1722 	}
1723 
1724 	if (error == 0 && ((uint32_t)nseg) >= mpt->max_seg_cnt) {
1725 		error = EFBIG;
1726 		mpt_prt(mpt, "segment count %d too large (max %u)\n",
1727 		    nseg, mpt->max_seg_cnt);
1728 	}
1729 
1730 bad:
1731 	if (error != 0) {
1732 		if (error != EFBIG && error != ENOMEM) {
1733 			mpt_prt(mpt, "mpt_execute_req: err %d\n", error);
1734 		}
1735 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_INPROG) {
1736 			cam_status status;
1737 			mpt_freeze_ccb(ccb);
1738 			if (error == EFBIG) {
1739 				status = CAM_REQ_TOO_BIG;
1740 			} else if (error == ENOMEM) {
1741 				if (mpt->outofbeer == 0) {
1742 					mpt->outofbeer = 1;
1743 					xpt_freeze_simq(mpt->sim, 1);
1744 					mpt_lprt(mpt, MPT_PRT_DEBUG,
1745 					    "FREEZEQ\n");
1746 				}
1747 				status = CAM_REQUEUE_REQ;
1748 			} else {
1749 				status = CAM_REQ_CMP_ERR;
1750 			}
1751 			mpt_set_ccb_status(ccb, status);
1752 		}
1753 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
1754 			request_t *cmd_req =
1755 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
1756 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
1757 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
1758 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
1759 		}
1760 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1761 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
1762 		xpt_done(ccb);
1763 		CAMLOCK_2_MPTLOCK(mpt);
1764 		mpt_free_request(mpt, req);
1765 		MPTLOCK_2_CAMLOCK(mpt);
1766 		return;
1767 	}
1768 
1769 	/*
1770 	 * No data to transfer?
1771 	 * Just make a single simple SGL with zero length.
1772 	 */
1773 
1774 	if (mpt->verbose >= MPT_PRT_DEBUG) {
1775 		int tidx = ((char *)sglp) - mpt_off;
1776 		memset(&mpt_off[tidx], 0xff, MPT_REQUEST_AREA - tidx);
1777 	}
1778 
1779 	if (nseg == 0) {
1780 		SGE_SIMPLE32 *se1 = (SGE_SIMPLE32 *) sglp;
1781 		MPI_pSGE_SET_FLAGS(se1,
1782 		    (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1783 		    MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_LIST));
1784 		se1->FlagsLength = htole32(se1->FlagsLength);
1785 		goto out;
1786 	}
1787 
1788 
1789 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
1790 	if (istgt == 0) {
1791 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
1792 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1793 		}
1794 	} else {
1795 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1796 			flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
1797 		}
1798 	}
1799 
1800 	if (!(ccb->ccb_h.flags & (CAM_SG_LIST_PHYS|CAM_DATA_PHYS))) {
1801 		bus_dmasync_op_t op;
1802 		if (istgt) {
1803 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1804 				op = BUS_DMASYNC_PREREAD;
1805 			} else {
1806 				op = BUS_DMASYNC_PREWRITE;
1807 			}
1808 		} else {
1809 			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1810 				op = BUS_DMASYNC_PREWRITE;
1811 			} else {
1812 				op = BUS_DMASYNC_PREREAD;
1813 			}
1814 		}
1815 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
1816 	}
1817 
1818 	/*
1819 	 * Okay, fill in what we can at the end of the command frame.
1820 	 * If we have up to MPT_NSGL_FIRST, we can fit them all into
1821 	 * the command frame.
1822 	 *
1823 	 * Otherwise, we fill up through MPT_NSGL_FIRST less one
1824 	 * SIMPLE32 pointers and start doing CHAIN32 entries after
1825 	 * that.
1826 	 */
1827 
1828 	if (nseg < MPT_NSGL_FIRST(mpt)) {
1829 		first_lim = nseg;
1830 	} else {
1831 		/*
1832 		 * Leave room for CHAIN element
1833 		 */
1834 		first_lim = MPT_NSGL_FIRST(mpt) - 1;
1835 	}
1836 
1837 	se = (SGE_SIMPLE32 *) sglp;
1838 	for (seg = 0; seg < first_lim; seg++, se++, dm_segs++) {
1839 		uint32_t tf;
1840 
1841 		memset(se, 0,sizeof (*se));
1842 		se->Address = htole32(dm_segs->ds_addr);
1843 
1844 
1845 
1846 		MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1847 		tf = flags;
1848 		if (seg == first_lim - 1) {
1849 			tf |= MPI_SGE_FLAGS_LAST_ELEMENT;
1850 		}
1851 		if (seg == nseg - 1) {
1852 			tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1853 				MPI_SGE_FLAGS_END_OF_BUFFER;
1854 		}
1855 		MPI_pSGE_SET_FLAGS(se, tf);
1856 		se->FlagsLength = htole32(se->FlagsLength);
1857 	}
1858 
1859 	if (seg == nseg) {
1860 		goto out;
1861 	}
1862 
1863 	/*
1864 	 * Tell the IOC where to find the first chain element.
1865 	 */
1866 	hdrp->ChainOffset = ((char *)se - (char *)hdrp) >> 2;
1867 	nxt_off = MPT_RQSL(mpt);
1868 	trq = req;
1869 
1870 	/*
1871 	 * Make up the rest of the data segments out of a chain element
1872 	 * (contiained in the current request frame) which points to
1873 	 * SIMPLE32 elements in the next request frame, possibly ending
1874 	 * with *another* chain element (if there's more).
1875 	 */
1876 	while (seg < nseg) {
1877 		int this_seg_lim;
1878 		uint32_t tf, cur_off;
1879 		bus_addr_t chain_list_addr;
1880 
1881 		/*
1882 		 * Point to the chain descriptor. Note that the chain
1883 		 * descriptor is at the end of the *previous* list (whether
1884 		 * chain or simple).
1885 		 */
1886 		ce = (SGE_CHAIN32 *) se;
1887 
1888 		/*
1889 		 * Before we change our current pointer, make  sure we won't
1890 		 * overflow the request area with this frame. Note that we
1891 		 * test against 'greater than' here as it's okay in this case
1892 		 * to have next offset be just outside the request area.
1893 		 */
1894 		if ((nxt_off + MPT_RQSL(mpt)) > MPT_REQUEST_AREA) {
1895 			nxt_off = MPT_REQUEST_AREA;
1896 			goto next_chain;
1897 		}
1898 
1899 		/*
1900 		 * Set our SGE element pointer to the beginning of the chain
1901 		 * list and update our next chain list offset.
1902 		 */
1903 		se = (SGE_SIMPLE32 *) &mpt_off[nxt_off];
1904 		cur_off = nxt_off;
1905 		nxt_off += MPT_RQSL(mpt);
1906 
1907 		/*
1908 		 * Now initialized the chain descriptor.
1909 		 */
1910 		memset(ce, 0, sizeof (*ce));
1911 
1912 		/*
1913 		 * Get the physical address of the chain list.
1914 		 */
1915 		chain_list_addr = trq->req_pbuf;
1916 		chain_list_addr += cur_off;
1917 
1918 
1919 
1920 		ce->Address = htole32(chain_list_addr);
1921 		ce->Flags = MPI_SGE_FLAGS_CHAIN_ELEMENT;
1922 
1923 
1924 		/*
1925 		 * If we have more than a frame's worth of segments left,
1926 		 * set up the chain list to have the last element be another
1927 		 * chain descriptor.
1928 		 */
1929 		if ((nseg - seg) > MPT_NSGL(mpt)) {
1930 			this_seg_lim = seg + MPT_NSGL(mpt) - 1;
1931 			/*
1932 			 * The length of the chain is the length in bytes of the
1933 			 * number of segments plus the next chain element.
1934 			 *
1935 			 * The next chain descriptor offset is the length,
1936 			 * in words, of the number of segments.
1937 			 */
1938 			ce->Length = (this_seg_lim - seg) *
1939 			    sizeof (SGE_SIMPLE32);
1940 			ce->NextChainOffset = ce->Length >> 2;
1941 			ce->Length += sizeof (SGE_CHAIN32);
1942 		} else {
1943 			this_seg_lim = nseg;
1944 			ce->Length = (this_seg_lim - seg) *
1945 			    sizeof (SGE_SIMPLE32);
1946 		}
1947 		ce->Length = htole16(ce->Length);
1948 
1949 		/*
1950 		 * Fill in the chain list SGE elements with our segment data.
1951 		 *
1952 		 * If we're the last element in this chain list, set the last
1953 		 * element flag. If we're the completely last element period,
1954 		 * set the end of list and end of buffer flags.
1955 		 */
1956 		while (seg < this_seg_lim) {
1957 			memset(se, 0, sizeof (*se));
1958 			se->Address = htole32(dm_segs->ds_addr);
1959 
1960 
1961 
1962 
1963 			MPI_pSGE_SET_LENGTH(se, dm_segs->ds_len);
1964 			tf = flags;
1965 			if (seg ==  this_seg_lim - 1) {
1966 				tf |=	MPI_SGE_FLAGS_LAST_ELEMENT;
1967 			}
1968 			if (seg == nseg - 1) {
1969 				tf |=	MPI_SGE_FLAGS_END_OF_LIST |
1970 					MPI_SGE_FLAGS_END_OF_BUFFER;
1971 			}
1972 			MPI_pSGE_SET_FLAGS(se, tf);
1973 			se->FlagsLength = htole32(se->FlagsLength);
1974 			se++;
1975 			seg++;
1976 			dm_segs++;
1977 		}
1978 
1979     next_chain:
1980 		/*
1981 		 * If we have more segments to do and we've used up all of
1982 		 * the space in a request area, go allocate another one
1983 		 * and chain to that.
1984 		 */
1985 		if (seg < nseg && nxt_off >= MPT_REQUEST_AREA) {
1986 			request_t *nrq;
1987 
1988 			CAMLOCK_2_MPTLOCK(mpt);
1989 			nrq = mpt_get_request(mpt, FALSE);
1990 			MPTLOCK_2_CAMLOCK(mpt);
1991 
1992 			if (nrq == NULL) {
1993 				error = ENOMEM;
1994 				goto bad;
1995 			}
1996 
1997 			/*
1998 			 * Append the new request area on the tail of our list.
1999 			 */
2000 			if ((trq = req->chain) == NULL) {
2001 				req->chain = nrq;
2002 			} else {
2003 				while (trq->chain != NULL) {
2004 					trq = trq->chain;
2005 				}
2006 				trq->chain = nrq;
2007 			}
2008 			trq = nrq;
2009 			mpt_off = trq->req_vbuf;
2010 			if (mpt->verbose >= MPT_PRT_DEBUG) {
2011 				memset(mpt_off, 0xff, MPT_REQUEST_AREA);
2012 			}
2013 			nxt_off = 0;
2014 		}
2015 	}
2016 out:
2017 
2018 	/*
2019 	 * Last time we need to check if this CCB needs to be aborted.
2020 	 */
2021 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2022 		if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2023 			request_t *cmd_req =
2024 				MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2025 			MPT_TGT_STATE(mpt, cmd_req)->state = TGT_STATE_IN_CAM;
2026 			MPT_TGT_STATE(mpt, cmd_req)->ccb = NULL;
2027 			MPT_TGT_STATE(mpt, cmd_req)->req = NULL;
2028 		}
2029 		mpt_prt(mpt,
2030 		    "mpt_execute_req: I/O cancelled (status 0x%x)\n",
2031 		    ccb->ccb_h.status & CAM_STATUS_MASK);
2032 		if (nseg && (ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
2033 			bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2034 		}
2035 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2036 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2037 		xpt_done(ccb);
2038 		CAMLOCK_2_MPTLOCK(mpt);
2039 		mpt_free_request(mpt, req);
2040 		MPTLOCK_2_CAMLOCK(mpt);
2041 		return;
2042 	}
2043 
2044 	ccb->ccb_h.status |= CAM_SIM_QUEUED;
2045 	if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) {
2046 		mpt_req_timeout(req, (ccb->ccb_h.timeout * hz) / 1000,
2047 		    mpt_timeout, ccb);
2048 	}
2049 	if (mpt->verbose > MPT_PRT_DEBUG) {
2050 		int nc = 0;
2051 		mpt_print_request(req->req_vbuf);
2052 		for (trq = req->chain; trq; trq = trq->chain) {
2053 			printf("  Additional Chain Area %d\n", nc++);
2054 			mpt_dump_sgl(trq->req_vbuf, 0);
2055 		}
2056 	}
2057 
2058 	if (hdrp->Function == MPI_FUNCTION_TARGET_ASSIST) {
2059 		request_t *cmd_req = MPT_TAG_2_REQ(mpt, ccb->csio.tag_id);
2060 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
2061 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
2062 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
2063 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
2064 			tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
2065 		} else {
2066 			tgt->state = TGT_STATE_MOVING_DATA;
2067 		}
2068 #else
2069 		tgt->state = TGT_STATE_MOVING_DATA;
2070 #endif
2071 	}
2072 	CAMLOCK_2_MPTLOCK(mpt);
2073 	mpt_send_cmd(mpt, req);
2074 	MPTLOCK_2_CAMLOCK(mpt);
2075 }
2076 
2077 static void
2078 mpt_start(struct cam_sim *sim, union ccb *ccb)
2079 {
2080 	request_t *req;
2081 	struct mpt_softc *mpt;
2082 	MSG_SCSI_IO_REQUEST *mpt_req;
2083 	struct ccb_scsiio *csio = &ccb->csio;
2084 	struct ccb_hdr *ccbh = &ccb->ccb_h;
2085 	bus_dmamap_callback_t *cb;
2086 	target_id_t tgt;
2087 	int raid_passthru;
2088 
2089 	/* Get the pointer for the physical addapter */
2090 	mpt = ccb->ccb_h.ccb_mpt_ptr;
2091 	raid_passthru = (sim == mpt->phydisk_sim);
2092 
2093 	CAMLOCK_2_MPTLOCK(mpt);
2094 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
2095 		if (mpt->outofbeer == 0) {
2096 			mpt->outofbeer = 1;
2097 			xpt_freeze_simq(mpt->sim, 1);
2098 			mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
2099 		}
2100 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2101 		mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
2102 		MPTLOCK_2_CAMLOCK(mpt);
2103 		xpt_done(ccb);
2104 		return;
2105 	}
2106 #ifdef	INVARIANTS
2107 	mpt_req_not_spcl(mpt, req, "mpt_start", __LINE__);
2108 #endif
2109 	MPTLOCK_2_CAMLOCK(mpt);
2110 
2111 	if (sizeof (bus_addr_t) > 4) {
2112 		cb = mpt_execute_req_a64;
2113 	} else {
2114 		cb = mpt_execute_req;
2115 	}
2116 
2117 	/*
2118 	 * Link the ccb and the request structure so we can find
2119 	 * the other knowing either the request or the ccb
2120 	 */
2121 	req->ccb = ccb;
2122 	ccb->ccb_h.ccb_req_ptr = req;
2123 
2124 	/* Now we build the command for the IOC */
2125 	mpt_req = req->req_vbuf;
2126 	memset(mpt_req, 0, sizeof (MSG_SCSI_IO_REQUEST));
2127 
2128 	mpt_req->Function = MPI_FUNCTION_SCSI_IO_REQUEST;
2129 	if (raid_passthru) {
2130 		mpt_req->Function = MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH;
2131 		CAMLOCK_2_MPTLOCK(mpt);
2132 		if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
2133 			MPTLOCK_2_CAMLOCK(mpt);
2134 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2135 			mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
2136 			xpt_done(ccb);
2137 			return;
2138 		}
2139 		MPTLOCK_2_CAMLOCK(mpt);
2140 		mpt_req->Bus = 0;	/* we never set bus here */
2141 	} else {
2142 		tgt = ccb->ccb_h.target_id;
2143 		mpt_req->Bus = 0;	/* XXX */
2144 
2145 	}
2146 	mpt_req->SenseBufferLength =
2147 		(csio->sense_len < MPT_SENSE_SIZE) ?
2148 		 csio->sense_len : MPT_SENSE_SIZE;
2149 
2150 	/*
2151 	 * We use the message context to find the request structure when we
2152 	 * Get the command completion interrupt from the IOC.
2153 	 */
2154 	mpt_req->MsgContext = htole32(req->index | scsi_io_handler_id);
2155 
2156 	/* Which physical device to do the I/O on */
2157 	mpt_req->TargetID = tgt;
2158 
2159 	/* We assume a single level LUN type */
2160 	if (ccb->ccb_h.target_lun >= MPT_MAX_LUNS) {
2161 		mpt_req->LUN[0] = 0x40 | ((ccb->ccb_h.target_lun >> 8) & 0x3f);
2162 		mpt_req->LUN[1] = ccb->ccb_h.target_lun & 0xff;
2163 	} else {
2164 		mpt_req->LUN[1] = ccb->ccb_h.target_lun;
2165 	}
2166 
2167 	/* Set the direction of the transfer */
2168 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2169 		mpt_req->Control = MPI_SCSIIO_CONTROL_READ;
2170 	} else if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_OUT) {
2171 		mpt_req->Control = MPI_SCSIIO_CONTROL_WRITE;
2172 	} else {
2173 		mpt_req->Control = MPI_SCSIIO_CONTROL_NODATATRANSFER;
2174 	}
2175 
2176 	if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
2177 		switch(ccb->csio.tag_action) {
2178 		case MSG_HEAD_OF_Q_TAG:
2179 			mpt_req->Control |= MPI_SCSIIO_CONTROL_HEADOFQ;
2180 			break;
2181 		case MSG_ACA_TASK:
2182 			mpt_req->Control |= MPI_SCSIIO_CONTROL_ACAQ;
2183 			break;
2184 		case MSG_ORDERED_Q_TAG:
2185 			mpt_req->Control |= MPI_SCSIIO_CONTROL_ORDEREDQ;
2186 			break;
2187 		case MSG_SIMPLE_Q_TAG:
2188 		default:
2189 			mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2190 			break;
2191 		}
2192 	} else {
2193 		if (mpt->is_fc || mpt->is_sas) {
2194 			mpt_req->Control |= MPI_SCSIIO_CONTROL_SIMPLEQ;
2195 		} else {
2196 			/* XXX No such thing for a target doing packetized. */
2197 			mpt_req->Control |= MPI_SCSIIO_CONTROL_UNTAGGED;
2198 		}
2199 	}
2200 
2201 	if (mpt->is_spi) {
2202 		if (ccb->ccb_h.flags & CAM_DIS_DISCONNECT) {
2203 			mpt_req->Control |= MPI_SCSIIO_CONTROL_NO_DISCONNECT;
2204 		}
2205 	}
2206 	mpt_req->Control = htole32(mpt_req->Control);
2207 
2208 	/* Copy the scsi command block into place */
2209 	if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
2210 		bcopy(csio->cdb_io.cdb_ptr, mpt_req->CDB, csio->cdb_len);
2211 	} else {
2212 		bcopy(csio->cdb_io.cdb_bytes, mpt_req->CDB, csio->cdb_len);
2213 	}
2214 
2215 	mpt_req->CDBLength = csio->cdb_len;
2216 	mpt_req->DataLength = htole32(csio->dxfer_len);
2217 	mpt_req->SenseBufferLowAddr = htole32(req->sense_pbuf);
2218 
2219 	/*
2220 	 * Do a *short* print here if we're set to MPT_PRT_DEBUG
2221 	 */
2222 	if (mpt->verbose == MPT_PRT_DEBUG) {
2223 		U32 df;
2224 		mpt_prt(mpt, "mpt_start: %s op 0x%x ",
2225 		    (mpt_req->Function == MPI_FUNCTION_SCSI_IO_REQUEST)?
2226 		    "SCSI_IO_REQUEST" : "SCSI_IO_PASSTHRU", mpt_req->CDB[0]);
2227 		df = mpt_req->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK;
2228 		if (df != MPI_SCSIIO_CONTROL_NODATATRANSFER) {
2229 			mpt_prtc(mpt, "(%s %u byte%s ",
2230 			    (df == MPI_SCSIIO_CONTROL_READ)?
2231 			    "read" : "write",  csio->dxfer_len,
2232 			    (csio->dxfer_len == 1)? ")" : "s)");
2233 		}
2234 		mpt_prtc(mpt, "tgt %u lun %u req %p:%u\n", tgt,
2235 		    ccb->ccb_h.target_lun, req, req->serno);
2236 	}
2237 
2238 	/*
2239 	 * If we have any data to send with this command map it into bus space.
2240 	 */
2241 	if ((ccbh->flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2242 		if ((ccbh->flags & CAM_SCATTER_VALID) == 0) {
2243 			/*
2244 			 * We've been given a pointer to a single buffer.
2245 			 */
2246 			if ((ccbh->flags & CAM_DATA_PHYS) == 0) {
2247 				/*
2248 				 * Virtual address that needs to translated into
2249 				 * one or more physical address ranges.
2250 				 */
2251 				int error;
2252 				int s = splsoftvm();
2253 				error = bus_dmamap_load(mpt->buffer_dmat,
2254 				    req->dmap, csio->data_ptr, csio->dxfer_len,
2255 				    cb, req, 0);
2256 				splx(s);
2257 				if (error == EINPROGRESS) {
2258 					/*
2259 					 * So as to maintain ordering,
2260 					 * freeze the controller queue
2261 					 * until our mapping is
2262 					 * returned.
2263 					 */
2264 					xpt_freeze_simq(mpt->sim, 1);
2265 					ccbh->status |= CAM_RELEASE_SIMQ;
2266 				}
2267 			} else {
2268 				/*
2269 				 * We have been given a pointer to single
2270 				 * physical buffer.
2271 				 */
2272 				struct bus_dma_segment seg;
2273 				seg.ds_addr =
2274 				    (bus_addr_t)(vm_offset_t)csio->data_ptr;
2275 				seg.ds_len = csio->dxfer_len;
2276 				(*cb)(req, &seg, 1, 0);
2277 			}
2278 		} else {
2279 			/*
2280 			 * We have been given a list of addresses.
2281 			 * This case could be easily supported but they are not
2282 			 * currently generated by the CAM subsystem so there
2283 			 * is no point in wasting the time right now.
2284 			 */
2285 			struct bus_dma_segment *segs;
2286 			if ((ccbh->flags & CAM_SG_LIST_PHYS) == 0) {
2287 				(*cb)(req, NULL, 0, EFAULT);
2288 			} else {
2289 				/* Just use the segments provided */
2290 				segs = (struct bus_dma_segment *)csio->data_ptr;
2291 				(*cb)(req, segs, csio->sglist_cnt, 0);
2292 			}
2293 		}
2294 	} else {
2295 		(*cb)(req, NULL, 0, 0);
2296 	}
2297 }
2298 
2299 static int
2300 mpt_bus_reset(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun,
2301     int sleep_ok)
2302 {
2303 	int   error;
2304 	uint16_t status;
2305 	uint8_t response;
2306 
2307 	error = mpt_scsi_send_tmf(mpt,
2308 	    (tgt != CAM_TARGET_WILDCARD || lun != CAM_LUN_WILDCARD) ?
2309 	    MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET :
2310 	    MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
2311 	    mpt->is_fc ? MPI_SCSITASKMGMT_MSGFLAGS_LIP_RESET_OPTION : 0,
2312 	    0,	/* XXX How do I get the channel ID? */
2313 	    tgt != CAM_TARGET_WILDCARD ? tgt : 0,
2314 	    lun != CAM_LUN_WILDCARD ? lun : 0,
2315 	    0, sleep_ok);
2316 
2317 	if (error != 0) {
2318 		/*
2319 		 * mpt_scsi_send_tmf hard resets on failure, so no
2320 		 * need to do so here.
2321 		 */
2322 		mpt_prt(mpt,
2323 		    "mpt_bus_reset: mpt_scsi_send_tmf returned %d\n", error);
2324 		return (EIO);
2325 	}
2326 
2327 	/* Wait for bus reset to be processed by the IOC. */
2328 	error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
2329 	    REQ_STATE_DONE, sleep_ok, 5000);
2330 
2331 	status = le16toh(mpt->tmf_req->IOCStatus);
2332 	response = mpt->tmf_req->ResponseCode;
2333 	mpt->tmf_req->state = REQ_STATE_FREE;
2334 
2335 	if (error) {
2336 		mpt_prt(mpt, "mpt_bus_reset: Reset timed-out. "
2337 		    "Resetting controller.\n");
2338 		mpt_reset(mpt, TRUE);
2339 		return (ETIMEDOUT);
2340 	}
2341 
2342 	if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
2343 		mpt_prt(mpt, "mpt_bus_reset: TMF IOC Status 0x%x. "
2344 		    "Resetting controller.\n", status);
2345 		mpt_reset(mpt, TRUE);
2346 		return (EIO);
2347 	}
2348 
2349 	if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
2350 	    response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
2351 		mpt_prt(mpt, "mpt_bus_reset: TMF Response 0x%x. "
2352 		    "Resetting controller.\n", response);
2353 		mpt_reset(mpt, TRUE);
2354 		return (EIO);
2355 	}
2356 	return (0);
2357 }
2358 
2359 static int
2360 mpt_fc_reset_link(struct mpt_softc *mpt, int dowait)
2361 {
2362 	int r = 0;
2363 	request_t *req;
2364 	PTR_MSG_FC_PRIMITIVE_SEND_REQUEST fc;
2365 
2366  	req = mpt_get_request(mpt, FALSE);
2367 	if (req == NULL) {
2368 		return (ENOMEM);
2369 	}
2370 	fc = req->req_vbuf;
2371 	memset(fc, 0, sizeof(*fc));
2372 	fc->SendFlags = MPI_FC_PRIM_SEND_FLAGS_RESET_LINK;
2373 	fc->Function = MPI_FUNCTION_FC_PRIMITIVE_SEND;
2374 	fc->MsgContext = htole32(req->index | fc_els_handler_id);
2375 	mpt_send_cmd(mpt, req);
2376 	if (dowait) {
2377 		r = mpt_wait_req(mpt, req, REQ_STATE_DONE,
2378 		    REQ_STATE_DONE, FALSE, 60 * 1000);
2379 		if (r == 0) {
2380 			mpt_free_request(mpt, req);
2381 		}
2382 	}
2383 	return (r);
2384 }
2385 
2386 static int
2387 mpt_cam_event(struct mpt_softc *mpt, request_t *req,
2388 	      MSG_EVENT_NOTIFY_REPLY *msg)
2389 {
2390 	uint32_t data0, data1;
2391 
2392 	data0 = le32toh(msg->Data[0]);
2393 	data1 = le32toh(msg->Data[1]);
2394 	switch(msg->Event & 0xFF) {
2395 	case MPI_EVENT_UNIT_ATTENTION:
2396 		mpt_prt(mpt, "UNIT ATTENTION: Bus: 0x%02x TargetID: 0x%02x\n",
2397 		    (data0 >> 8) & 0xff, data0 & 0xff);
2398 		break;
2399 
2400 	case MPI_EVENT_IOC_BUS_RESET:
2401 		/* We generated a bus reset */
2402 		mpt_prt(mpt, "IOC Generated Bus Reset Port: %d\n",
2403 		    (data0 >> 8) & 0xff);
2404 		xpt_async(AC_BUS_RESET, mpt->path, NULL);
2405 		break;
2406 
2407 	case MPI_EVENT_EXT_BUS_RESET:
2408 		/* Someone else generated a bus reset */
2409 		mpt_prt(mpt, "External Bus Reset Detected\n");
2410 		/*
2411 		 * These replies don't return EventData like the MPI
2412 		 * spec says they do
2413 		 */
2414 		xpt_async(AC_BUS_RESET, mpt->path, NULL);
2415 		break;
2416 
2417 	case MPI_EVENT_RESCAN:
2418 #if __FreeBSD_version >= 600000
2419 	{
2420 		union ccb *ccb;
2421 		uint32_t pathid;
2422 		/*
2423 		 * In general this means a device has been added to the loop.
2424 		 */
2425 		mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2426 		if (mpt->ready == 0) {
2427 			break;
2428 		}
2429 		if (mpt->phydisk_sim) {
2430 			pathid = cam_sim_path(mpt->phydisk_sim);
2431 		} else {
2432 			pathid = cam_sim_path(mpt->sim);
2433 		}
2434 		MPTLOCK_2_CAMLOCK(mpt);
2435 		/*
2436 		 * Allocate a CCB, create a wildcard path for this bus,
2437 		 * and schedule a rescan.
2438 		 */
2439 		ccb = xpt_alloc_ccb_nowait();
2440 		if (ccb == NULL) {
2441 			mpt_prt(mpt, "unable to alloc CCB for rescan\n");
2442 			CAMLOCK_2_MPTLOCK(mpt);
2443 			break;
2444 		}
2445 
2446 		if (xpt_create_path(&ccb->ccb_h.path, xpt_periph, pathid,
2447 		    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
2448 			CAMLOCK_2_MPTLOCK(mpt);
2449 			mpt_prt(mpt, "unable to create path for rescan\n");
2450 			xpt_free_ccb(ccb);
2451 			break;
2452 		}
2453 		xpt_rescan(ccb);
2454 		CAMLOCK_2_MPTLOCK(mpt);
2455 		break;
2456 	}
2457 #else
2458 		mpt_prt(mpt, "Rescan Port: %d\n", (data0 >> 8) & 0xff);
2459 		break;
2460 #endif
2461 	case MPI_EVENT_LINK_STATUS_CHANGE:
2462 		mpt_prt(mpt, "Port %d: LinkState: %s\n",
2463 		    (data1 >> 8) & 0xff,
2464 		    ((data0 & 0xff) == 0)?  "Failed" : "Active");
2465 		break;
2466 
2467 	case MPI_EVENT_LOOP_STATE_CHANGE:
2468 		switch ((data0 >> 16) & 0xff) {
2469 		case 0x01:
2470 			mpt_prt(mpt,
2471 			    "Port 0x%x: FC LinkEvent: LIP(%02x,%02x) "
2472 			    "(Loop Initialization)\n",
2473 			    (data1 >> 8) & 0xff,
2474 			    (data0 >> 8) & 0xff,
2475 			    (data0     ) & 0xff);
2476 			switch ((data0 >> 8) & 0xff) {
2477 			case 0xF7:
2478 				if ((data0 & 0xff) == 0xF7) {
2479 					mpt_prt(mpt, "Device needs AL_PA\n");
2480 				} else {
2481 					mpt_prt(mpt, "Device %02x doesn't like "
2482 					    "FC performance\n",
2483 					    data0 & 0xFF);
2484 				}
2485 				break;
2486 			case 0xF8:
2487 				if ((data0 & 0xff) == 0xF7) {
2488 					mpt_prt(mpt, "Device had loop failure "
2489 					    "at its receiver prior to acquiring"
2490 					    " AL_PA\n");
2491 				} else {
2492 					mpt_prt(mpt, "Device %02x detected loop"
2493 					    " failure at its receiver\n",
2494 					    data0 & 0xFF);
2495 				}
2496 				break;
2497 			default:
2498 				mpt_prt(mpt, "Device %02x requests that device "
2499 				    "%02x reset itself\n",
2500 				    data0 & 0xFF,
2501 				    (data0 >> 8) & 0xFF);
2502 				break;
2503 			}
2504 			break;
2505 		case 0x02:
2506 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2507 			    "LPE(%02x,%02x) (Loop Port Enable)\n",
2508 			    (data1 >> 8) & 0xff, /* Port */
2509 			    (data0 >>  8) & 0xff, /* Character 3 */
2510 			    (data0      ) & 0xff  /* Character 4 */);
2511 			break;
2512 		case 0x03:
2513 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: "
2514 			    "LPB(%02x,%02x) (Loop Port Bypass)\n",
2515 			    (data1 >> 8) & 0xff, /* Port */
2516 			    (data0 >> 8) & 0xff, /* Character 3 */
2517 			    (data0     ) & 0xff  /* Character 4 */);
2518 			break;
2519 		default:
2520 			mpt_prt(mpt, "Port 0x%x: FC LinkEvent: Unknown "
2521 			    "FC event (%02x %02x %02x)\n",
2522 			    (data1 >> 8) & 0xff, /* Port */
2523 			    (data0 >> 16) & 0xff, /* Event */
2524 			    (data0 >>  8) & 0xff, /* Character 3 */
2525 			    (data0      ) & 0xff  /* Character 4 */);
2526 		}
2527 		break;
2528 
2529 	case MPI_EVENT_LOGOUT:
2530 		mpt_prt(mpt, "FC Logout Port: %d N_PortID: %02x\n",
2531 		    (data1 >> 8) & 0xff, data0);
2532 		break;
2533 	case MPI_EVENT_QUEUE_FULL:
2534 	{
2535 		struct cam_sim *sim;
2536 		struct cam_path *tmppath;
2537 		struct ccb_relsim crs;
2538 		PTR_EVENT_DATA_QUEUE_FULL pqf;
2539 		lun_id_t lun_id;
2540 
2541 		pqf = (PTR_EVENT_DATA_QUEUE_FULL)msg->Data;
2542 		pqf->CurrentDepth = le16toh(pqf->CurrentDepth);
2543 		mpt_prt(mpt, "QUEUE FULL EVENT: Bus 0x%02x Target 0x%02x Depth "
2544 		    "%d\n", pqf->Bus, pqf->TargetID, pqf->CurrentDepth);
2545 		if (mpt->phydisk_sim) {
2546 			sim = mpt->phydisk_sim;
2547 		} else {
2548 			sim = mpt->sim;
2549 		}
2550 		MPTLOCK_2_CAMLOCK(mpt);
2551 		for (lun_id = 0; lun_id < MPT_MAX_LUNS; lun_id++) {
2552 			if (xpt_create_path(&tmppath, NULL, cam_sim_path(sim),
2553 			    pqf->TargetID, lun_id) != CAM_REQ_CMP) {
2554 				mpt_prt(mpt, "unable to create a path to send "
2555 				    "XPT_REL_SIMQ");
2556 				CAMLOCK_2_MPTLOCK(mpt);
2557 				break;
2558 			}
2559 			xpt_setup_ccb(&crs.ccb_h, tmppath, 5);
2560 			crs.ccb_h.func_code = XPT_REL_SIMQ;
2561 			crs.ccb_h.flags = CAM_DEV_QFREEZE;
2562 			crs.release_flags = RELSIM_ADJUST_OPENINGS;
2563 			crs.openings = pqf->CurrentDepth - 1;
2564 			xpt_action((union ccb *)&crs);
2565 			if (crs.ccb_h.status != CAM_REQ_CMP) {
2566 				mpt_prt(mpt, "XPT_REL_SIMQ failed\n");
2567 			}
2568 			xpt_free_path(tmppath);
2569 		}
2570 		CAMLOCK_2_MPTLOCK(mpt);
2571 		break;
2572 	}
2573 	case MPI_EVENT_EVENT_CHANGE:
2574 	case MPI_EVENT_INTEGRATED_RAID:
2575 	case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
2576 	case MPI_EVENT_SAS_SES:
2577 		break;
2578 	default:
2579 		mpt_lprt(mpt, MPT_PRT_WARN, "mpt_cam_event: 0x%x\n",
2580 		    msg->Event & 0xFF);
2581 		return (0);
2582 	}
2583 	return (1);
2584 }
2585 
2586 /*
2587  * Reply path for all SCSI I/O requests, called from our
2588  * interrupt handler by extracting our handler index from
2589  * the MsgContext field of the reply from the IOC.
2590  *
2591  * This routine is optimized for the common case of a
2592  * completion without error.  All exception handling is
2593  * offloaded to non-inlined helper routines to minimize
2594  * cache footprint.
2595  */
2596 static int
2597 mpt_scsi_reply_handler(struct mpt_softc *mpt, request_t *req,
2598     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2599 {
2600 	MSG_SCSI_IO_REQUEST *scsi_req;
2601 	union ccb *ccb;
2602 
2603 	if (req->state == REQ_STATE_FREE) {
2604 		mpt_prt(mpt, "mpt_scsi_reply_handler: req already free\n");
2605 		return (TRUE);
2606 	}
2607 
2608 	scsi_req = (MSG_SCSI_IO_REQUEST *)req->req_vbuf;
2609 	ccb = req->ccb;
2610 	if (ccb == NULL) {
2611 		mpt_prt(mpt, "mpt_scsi_reply_handler: req %p:%u with no ccb\n",
2612 		    req, req->serno);
2613 		return (TRUE);
2614 	}
2615 
2616 	mpt_req_untimeout(req, mpt_timeout, ccb);
2617 	ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2618 
2619 	if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
2620 		bus_dmasync_op_t op;
2621 
2622 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
2623 			op = BUS_DMASYNC_POSTREAD;
2624 		else
2625 			op = BUS_DMASYNC_POSTWRITE;
2626 		bus_dmamap_sync(mpt->buffer_dmat, req->dmap, op);
2627 		bus_dmamap_unload(mpt->buffer_dmat, req->dmap);
2628 	}
2629 
2630 	if (reply_frame == NULL) {
2631 		/*
2632 		 * Context only reply, completion without error status.
2633 		 */
2634 		ccb->csio.resid = 0;
2635 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
2636 		ccb->csio.scsi_status = SCSI_STATUS_OK;
2637 	} else {
2638 		mpt_scsi_reply_frame_handler(mpt, req, reply_frame);
2639 	}
2640 
2641 	if (mpt->outofbeer) {
2642 		ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
2643 		mpt->outofbeer = 0;
2644 		mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
2645 	}
2646 	if (scsi_req->CDB[0] == INQUIRY && (scsi_req->CDB[1] & SI_EVPD) == 0) {
2647 		struct scsi_inquiry_data *iq =
2648 		    (struct scsi_inquiry_data *)ccb->csio.data_ptr;
2649 		if (scsi_req->Function ==
2650 		    MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH) {
2651 			/*
2652 			 * Fake out the device type so that only the
2653 			 * pass-thru device will attach.
2654 			 */
2655 			iq->device &= ~0x1F;
2656 			iq->device |= T_NODEVICE;
2657 		}
2658 	}
2659 	if (mpt->verbose == MPT_PRT_DEBUG) {
2660 		mpt_prt(mpt, "mpt_scsi_reply_handler: %p:%u complete\n",
2661 		    req, req->serno);
2662 	}
2663 	KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
2664 	MPTLOCK_2_CAMLOCK(mpt);
2665 	xpt_done(ccb);
2666 	CAMLOCK_2_MPTLOCK(mpt);
2667 	if ((req->state & REQ_STATE_TIMEDOUT) == 0) {
2668 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2669 	} else {
2670 		mpt_prt(mpt, "completing timedout/aborted req %p:%u\n",
2671 		    req, req->serno);
2672 		TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
2673 	}
2674 	KASSERT((req->state & REQ_STATE_NEED_WAKEUP) == 0,
2675 	    ("CCB req needed wakeup"));
2676 #ifdef	INVARIANTS
2677 	mpt_req_not_spcl(mpt, req, "mpt_scsi_reply_handler", __LINE__);
2678 #endif
2679 	mpt_free_request(mpt, req);
2680 	return (TRUE);
2681 }
2682 
2683 static int
2684 mpt_scsi_tmf_reply_handler(struct mpt_softc *mpt, request_t *req,
2685     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2686 {
2687 	MSG_SCSI_TASK_MGMT_REPLY *tmf_reply;
2688 
2689 	KASSERT(req == mpt->tmf_req, ("TMF Reply not using mpt->tmf_req"));
2690 #ifdef	INVARIANTS
2691 	mpt_req_not_spcl(mpt, req, "mpt_scsi_tmf_reply_handler", __LINE__);
2692 #endif
2693 	tmf_reply = (MSG_SCSI_TASK_MGMT_REPLY *)reply_frame;
2694 	/* Record IOC Status and Response Code of TMF for any waiters. */
2695 	req->IOCStatus = le16toh(tmf_reply->IOCStatus);
2696 	req->ResponseCode = tmf_reply->ResponseCode;
2697 
2698 	mpt_lprt(mpt, MPT_PRT_DEBUG, "TMF complete: req %p:%u status 0x%x\n",
2699 	    req, req->serno, le16toh(tmf_reply->IOCStatus));
2700 	TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2701 	if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
2702 		req->state |= REQ_STATE_DONE;
2703 		wakeup(req);
2704 	} else {
2705 		mpt->tmf_req->state = REQ_STATE_FREE;
2706 	}
2707 	return (TRUE);
2708 }
2709 
2710 /*
2711  * XXX: Move to definitions file
2712  */
2713 #define	ELS	0x22
2714 #define	FC4LS	0x32
2715 #define	ABTS	0x81
2716 #define	BA_ACC	0x84
2717 
2718 #define	LS_RJT	0x01
2719 #define	LS_ACC	0x02
2720 #define	PLOGI	0x03
2721 #define	LOGO	0x05
2722 #define SRR	0x14
2723 #define PRLI	0x20
2724 #define PRLO	0x21
2725 #define ADISC	0x52
2726 #define RSCN	0x61
2727 
2728 static void
2729 mpt_fc_els_send_response(struct mpt_softc *mpt, request_t *req,
2730     PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp, U8 length)
2731 {
2732 	uint32_t fl;
2733 	MSG_LINK_SERVICE_RSP_REQUEST tmp;
2734 	PTR_MSG_LINK_SERVICE_RSP_REQUEST rsp;
2735 
2736 	/*
2737 	 * We are going to reuse the ELS request to send this response back.
2738 	 */
2739 	rsp = &tmp;
2740 	memset(rsp, 0, sizeof(*rsp));
2741 
2742 #ifdef	USE_IMMEDIATE_LINK_DATA
2743 	/*
2744 	 * Apparently the IMMEDIATE stuff doesn't seem to work.
2745 	 */
2746 	rsp->RspFlags = LINK_SERVICE_RSP_FLAGS_IMMEDIATE;
2747 #endif
2748 	rsp->RspLength = length;
2749 	rsp->Function = MPI_FUNCTION_FC_LINK_SRVC_RSP;
2750 	rsp->MsgContext = htole32(req->index | fc_els_handler_id);
2751 
2752 	/*
2753 	 * Copy over information from the original reply frame to
2754 	 * it's correct place in the response.
2755 	 */
2756 	memcpy((U8 *)rsp + 0x0c, (U8 *)rp + 0x1c, 24);
2757 
2758 	/*
2759 	 * And now copy back the temporary area to the original frame.
2760 	 */
2761 	memcpy(req->req_vbuf, rsp, sizeof (MSG_LINK_SERVICE_RSP_REQUEST));
2762 	rsp = req->req_vbuf;
2763 
2764 #ifdef	USE_IMMEDIATE_LINK_DATA
2765 	memcpy((U8 *)&rsp->SGL, &((U8 *)req->req_vbuf)[MPT_RQSL(mpt)], length);
2766 #else
2767 {
2768 	PTR_SGE_SIMPLE32 se = (PTR_SGE_SIMPLE32) &rsp->SGL;
2769 	bus_addr_t paddr = req->req_pbuf;
2770 	paddr += MPT_RQSL(mpt);
2771 
2772 	fl =
2773 		MPI_SGE_FLAGS_HOST_TO_IOC	|
2774 		MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
2775 		MPI_SGE_FLAGS_LAST_ELEMENT	|
2776 		MPI_SGE_FLAGS_END_OF_LIST	|
2777 		MPI_SGE_FLAGS_END_OF_BUFFER;
2778 	fl <<= MPI_SGE_FLAGS_SHIFT;
2779 	fl |= (length);
2780 	se->FlagsLength = htole32(fl);
2781 	se->Address = htole32((uint32_t) paddr);
2782 }
2783 #endif
2784 
2785 	/*
2786 	 * Send it on...
2787 	 */
2788 	mpt_send_cmd(mpt, req);
2789 }
2790 
2791 static int
2792 mpt_fc_els_reply_handler(struct mpt_softc *mpt, request_t *req,
2793     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
2794 {
2795 	PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY rp =
2796 	    (PTR_MSG_LINK_SERVICE_BUFFER_POST_REPLY) reply_frame;
2797 	U8 rctl;
2798 	U8 type;
2799 	U8 cmd;
2800 	U16 status = le16toh(reply_frame->IOCStatus);
2801 	U32 *elsbuf;
2802 	int ioindex;
2803 	int do_refresh = TRUE;
2804 
2805 #ifdef	INVARIANTS
2806 	KASSERT(mpt_req_on_free_list(mpt, req) == 0,
2807 	    ("fc_els_reply_handler: req %p:%u for function %x on freelist!",
2808 	    req, req->serno, rp->Function));
2809 	if (rp->Function != MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2810 		mpt_req_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2811 	} else {
2812 		mpt_req_not_spcl(mpt, req, "fc_els_reply_handler", __LINE__);
2813 	}
2814 #endif
2815 	mpt_lprt(mpt, MPT_PRT_DEBUG,
2816 	    "FC_ELS Complete: req %p:%u, reply %p function %x\n",
2817 	    req, req->serno, reply_frame, reply_frame->Function);
2818 
2819 	if  (status != MPI_IOCSTATUS_SUCCESS) {
2820 		mpt_prt(mpt, "ELS REPLY STATUS 0x%x for Function %x\n",
2821 		    status, reply_frame->Function);
2822 		if (status == MPI_IOCSTATUS_INVALID_STATE) {
2823 			/*
2824 			 * XXX: to get around shutdown issue
2825 			 */
2826 			mpt->disabled = 1;
2827 			return (TRUE);
2828 		}
2829 		return (TRUE);
2830 	}
2831 
2832 	/*
2833 	 * If the function of a link service response, we recycle the
2834 	 * response to be a refresh for a new link service request.
2835 	 *
2836 	 * The request pointer is bogus in this case and we have to fetch
2837 	 * it based upon the TransactionContext.
2838 	 */
2839 	if (rp->Function == MPI_FUNCTION_FC_LINK_SRVC_RSP) {
2840 		/* Freddie Uncle Charlie Katie */
2841 		/* We don't get the IOINDEX as part of the Link Svc Rsp */
2842 		for (ioindex = 0; ioindex < mpt->els_cmds_allocated; ioindex++)
2843 			if (mpt->els_cmd_ptrs[ioindex] == req) {
2844 				break;
2845 			}
2846 
2847 		KASSERT(ioindex < mpt->els_cmds_allocated,
2848 		    ("can't find my mommie!"));
2849 
2850 		/* remove from active list as we're going to re-post it */
2851 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2852 		req->state &= ~REQ_STATE_QUEUED;
2853 		req->state |= REQ_STATE_DONE;
2854 		mpt_fc_post_els(mpt, req, ioindex);
2855 		return (TRUE);
2856 	}
2857 
2858 	if (rp->Function == MPI_FUNCTION_FC_PRIMITIVE_SEND) {
2859 		/* remove from active list as we're done */
2860 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2861 		req->state &= ~REQ_STATE_QUEUED;
2862 		req->state |= REQ_STATE_DONE;
2863 		if (req->state & REQ_STATE_TIMEDOUT) {
2864 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2865 			    "Sync Primitive Send Completed After Timeout\n");
2866 			mpt_free_request(mpt, req);
2867 		} else if ((req->state & REQ_STATE_NEED_WAKEUP) == 0) {
2868 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2869 			    "Async Primitive Send Complete\n");
2870 			mpt_free_request(mpt, req);
2871 		} else {
2872 			mpt_lprt(mpt, MPT_PRT_DEBUG,
2873 			    "Sync Primitive Send Complete- Waking Waiter\n");
2874 			wakeup(req);
2875 		}
2876 		return (TRUE);
2877 	}
2878 
2879 	if (rp->Function != MPI_FUNCTION_FC_LINK_SRVC_BUF_POST) {
2880 		mpt_prt(mpt, "unexpected ELS_REPLY: Function 0x%x Flags %x "
2881 		    "Length %d Message Flags %x\n", rp->Function, rp->Flags,
2882 		    rp->MsgLength, rp->MsgFlags);
2883 		return (TRUE);
2884 	}
2885 
2886 	if (rp->MsgLength <= 5) {
2887 		/*
2888 		 * This is just a ack of an original ELS buffer post
2889 		 */
2890 		mpt_lprt(mpt, MPT_PRT_DEBUG,
2891 		    "RECV'd ACK of FC_ELS buf post %p:%u\n", req, req->serno);
2892 		return (TRUE);
2893 	}
2894 
2895 
2896 	rctl = (le32toh(rp->Rctl_Did) & MPI_FC_RCTL_MASK) >> MPI_FC_RCTL_SHIFT;
2897 	type = (le32toh(rp->Type_Fctl) & MPI_FC_TYPE_MASK) >> MPI_FC_TYPE_SHIFT;
2898 
2899 	elsbuf = &((U32 *)req->req_vbuf)[MPT_RQSL(mpt)/sizeof (U32)];
2900 	cmd = be32toh(elsbuf[0]) >> 24;
2901 
2902 	if (rp->Flags & MPI_LS_BUF_POST_REPLY_FLAG_NO_RSP_NEEDED) {
2903 		mpt_lprt(mpt, MPT_PRT_ALWAYS, "ELS_REPLY: response unneeded\n");
2904 		return (TRUE);
2905 	}
2906 
2907 	ioindex = le32toh(rp->TransactionContext);
2908 	req = mpt->els_cmd_ptrs[ioindex];
2909 
2910 	if (rctl == ELS && type == 1) {
2911 		switch (cmd) {
2912 		case PRLI:
2913 			/*
2914 			 * Send back a PRLI ACC
2915 			 */
2916 			mpt_prt(mpt, "PRLI from 0x%08x%08x\n",
2917 			    le32toh(rp->Wwn.PortNameHigh),
2918 			    le32toh(rp->Wwn.PortNameLow));
2919 			elsbuf[0] = htobe32(0x02100014);
2920 			elsbuf[1] |= htobe32(0x00000100);
2921 			elsbuf[4] = htobe32(0x00000002);
2922 			if (mpt->role & MPT_ROLE_TARGET)
2923 				elsbuf[4] |= htobe32(0x00000010);
2924 			if (mpt->role & MPT_ROLE_INITIATOR)
2925 				elsbuf[4] |= htobe32(0x00000020);
2926 			/* remove from active list as we're done */
2927 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2928 			req->state &= ~REQ_STATE_QUEUED;
2929 			req->state |= REQ_STATE_DONE;
2930 			mpt_fc_els_send_response(mpt, req, rp, 20);
2931 			do_refresh = FALSE;
2932 			break;
2933 		case PRLO:
2934 			memset(elsbuf, 0, 5 * (sizeof (U32)));
2935 			elsbuf[0] = htobe32(0x02100014);
2936 			elsbuf[1] = htobe32(0x08000100);
2937 			mpt_prt(mpt, "PRLO from 0x%08x%08x\n",
2938 			    le32toh(rp->Wwn.PortNameHigh),
2939 			    le32toh(rp->Wwn.PortNameLow));
2940 			/* remove from active list as we're done */
2941 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
2942 			req->state &= ~REQ_STATE_QUEUED;
2943 			req->state |= REQ_STATE_DONE;
2944 			mpt_fc_els_send_response(mpt, req, rp, 20);
2945 			do_refresh = FALSE;
2946 			break;
2947 		default:
2948 			mpt_prt(mpt, "ELS TYPE 1 COMMAND: %x\n", cmd);
2949 			break;
2950 		}
2951 	} else if (rctl == ABTS && type == 0) {
2952 		uint16_t rx_id = le16toh(rp->Rxid);
2953 		uint16_t ox_id = le16toh(rp->Oxid);
2954 		request_t *tgt_req = NULL;
2955 
2956 		mpt_prt(mpt,
2957 		    "ELS: ABTS OX_ID 0x%x RX_ID 0x%x from 0x%08x%08x\n",
2958 		    ox_id, rx_id, le32toh(rp->Wwn.PortNameHigh),
2959 		    le32toh(rp->Wwn.PortNameLow));
2960 		if (rx_id >= mpt->mpt_max_tgtcmds) {
2961 			mpt_prt(mpt, "Bad RX_ID 0x%x\n", rx_id);
2962 		} else if (mpt->tgt_cmd_ptrs == NULL) {
2963 			mpt_prt(mpt, "No TGT CMD PTRS\n");
2964 		} else {
2965 			tgt_req = mpt->tgt_cmd_ptrs[rx_id];
2966 		}
2967 		if (tgt_req) {
2968 			mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, tgt_req);
2969 			union ccb *ccb = tgt->ccb;
2970 			uint32_t ct_id;
2971 
2972 			/*
2973 			 * Check to make sure we have the correct command
2974 			 * The reply descriptor in the target state should
2975 			 * should contain an IoIndex that should match the
2976 			 * RX_ID.
2977 			 *
2978 			 * It'd be nice to have OX_ID to crosscheck with
2979 			 * as well.
2980 			 */
2981 			ct_id = GET_IO_INDEX(tgt->reply_desc);
2982 
2983 			if (ct_id != rx_id) {
2984 				mpt_lprt(mpt, MPT_PRT_ERROR, "ABORT Mismatch: "
2985 				    "RX_ID received=0x%x; RX_ID in cmd=0x%x\n",
2986 				    rx_id, ct_id);
2987 				goto skip;
2988 			}
2989 
2990 			ccb = tgt->ccb;
2991 			if (ccb) {
2992 				mpt_prt(mpt,
2993 				    "CCB (%p): lun %u flags %x status %x\n",
2994 				    ccb, ccb->ccb_h.target_lun,
2995 				    ccb->ccb_h.flags, ccb->ccb_h.status);
2996 			}
2997 			mpt_prt(mpt, "target state 0x%x resid %u xfrd %u rpwrd "
2998 			    "%x nxfers %x\n", tgt->state,
2999 			    tgt->resid, tgt->bytes_xfered, tgt->reply_desc,
3000 			    tgt->nxfers);
3001   skip:
3002 			if (mpt_abort_target_cmd(mpt, tgt_req)) {
3003 				mpt_prt(mpt, "unable to start TargetAbort\n");
3004 			}
3005 		} else {
3006 			mpt_prt(mpt, "no back pointer for RX_ID 0x%x\n", rx_id);
3007 		}
3008 		memset(elsbuf, 0, 5 * (sizeof (U32)));
3009 		elsbuf[0] = htobe32(0);
3010 		elsbuf[1] = htobe32((ox_id << 16) | rx_id);
3011 		elsbuf[2] = htobe32(0x000ffff);
3012 		/*
3013 		 * Dork with the reply frame so that the reponse to it
3014 		 * will be correct.
3015 		 */
3016 		rp->Rctl_Did += ((BA_ACC - ABTS) << MPI_FC_RCTL_SHIFT);
3017 		/* remove from active list as we're done */
3018 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3019 		req->state &= ~REQ_STATE_QUEUED;
3020 		req->state |= REQ_STATE_DONE;
3021 		mpt_fc_els_send_response(mpt, req, rp, 12);
3022 		do_refresh = FALSE;
3023 	} else {
3024 		mpt_prt(mpt, "ELS: RCTL %x TYPE %x CMD %x\n", rctl, type, cmd);
3025 	}
3026 	if (do_refresh == TRUE) {
3027 		/* remove from active list as we're done */
3028 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
3029 		req->state &= ~REQ_STATE_QUEUED;
3030 		req->state |= REQ_STATE_DONE;
3031 		mpt_fc_post_els(mpt, req, ioindex);
3032 	}
3033 	return (TRUE);
3034 }
3035 
3036 /*
3037  * Clean up all SCSI Initiator personality state in response
3038  * to a controller reset.
3039  */
3040 static void
3041 mpt_cam_ioc_reset(struct mpt_softc *mpt, int type)
3042 {
3043 	/*
3044 	 * The pending list is already run down by
3045 	 * the generic handler.  Perform the same
3046 	 * operation on the timed out request list.
3047 	 */
3048 	mpt_complete_request_chain(mpt, &mpt->request_timeout_list,
3049 				   MPI_IOCSTATUS_INVALID_STATE);
3050 
3051 	/*
3052 	 * XXX: We need to repost ELS and Target Command Buffers?
3053 	 */
3054 
3055 	/*
3056 	 * Inform the XPT that a bus reset has occurred.
3057 	 */
3058 	xpt_async(AC_BUS_RESET, mpt->path, NULL);
3059 }
3060 
3061 /*
3062  * Parse additional completion information in the reply
3063  * frame for SCSI I/O requests.
3064  */
3065 static int
3066 mpt_scsi_reply_frame_handler(struct mpt_softc *mpt, request_t *req,
3067 			     MSG_DEFAULT_REPLY *reply_frame)
3068 {
3069 	union ccb *ccb;
3070 	MSG_SCSI_IO_REPLY *scsi_io_reply;
3071 	u_int ioc_status;
3072 	u_int sstate;
3073 
3074 	MPT_DUMP_REPLY_FRAME(mpt, reply_frame);
3075 	KASSERT(reply_frame->Function == MPI_FUNCTION_SCSI_IO_REQUEST
3076 	     || reply_frame->Function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH,
3077 		("MPT SCSI I/O Handler called with incorrect reply type"));
3078 	KASSERT((reply_frame->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY) == 0,
3079 		("MPT SCSI I/O Handler called with continuation reply"));
3080 
3081 	scsi_io_reply = (MSG_SCSI_IO_REPLY *)reply_frame;
3082 	ioc_status = le16toh(scsi_io_reply->IOCStatus);
3083 	ioc_status &= MPI_IOCSTATUS_MASK;
3084 	sstate = scsi_io_reply->SCSIState;
3085 
3086 	ccb = req->ccb;
3087 	ccb->csio.resid =
3088 	    ccb->csio.dxfer_len - le32toh(scsi_io_reply->TransferCount);
3089 
3090 	if ((sstate & MPI_SCSI_STATE_AUTOSENSE_VALID) != 0
3091 	 && (ccb->ccb_h.flags & (CAM_SENSE_PHYS | CAM_SENSE_PTR)) == 0) {
3092 		ccb->ccb_h.status |= CAM_AUTOSNS_VALID;
3093 		ccb->csio.sense_resid =
3094 		    ccb->csio.sense_len - le32toh(scsi_io_reply->SenseCount);
3095 		bcopy(req->sense_vbuf, &ccb->csio.sense_data,
3096 		    min(ccb->csio.sense_len,
3097 		    le32toh(scsi_io_reply->SenseCount)));
3098 	}
3099 
3100 	if ((sstate & MPI_SCSI_STATE_QUEUE_TAG_REJECTED) != 0) {
3101 		/*
3102 		 * Tag messages rejected, but non-tagged retry
3103 		 * was successful.
3104 XXXX
3105 		mpt_set_tags(mpt, devinfo, MPT_QUEUE_NONE);
3106 		 */
3107 	}
3108 
3109 	switch(ioc_status) {
3110 	case MPI_IOCSTATUS_SCSI_RESIDUAL_MISMATCH:
3111 		/*
3112 		 * XXX
3113 		 * Linux driver indicates that a zero
3114 		 * transfer length with this error code
3115 		 * indicates a CRC error.
3116 		 *
3117 		 * No need to swap the bytes for checking
3118 		 * against zero.
3119 		 */
3120 		if (scsi_io_reply->TransferCount == 0) {
3121 			mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3122 			break;
3123 		}
3124 		/* FALLTHROUGH */
3125 	case MPI_IOCSTATUS_SCSI_DATA_UNDERRUN:
3126 	case MPI_IOCSTATUS_SUCCESS:
3127 	case MPI_IOCSTATUS_SCSI_RECOVERED_ERROR:
3128 		if ((sstate & MPI_SCSI_STATE_NO_SCSI_STATUS) != 0) {
3129 			/*
3130 			 * Status was never returned for this transaction.
3131 			 */
3132 			mpt_set_ccb_status(ccb, CAM_UNEXP_BUSFREE);
3133 		} else if (scsi_io_reply->SCSIStatus != SCSI_STATUS_OK) {
3134 			ccb->csio.scsi_status = scsi_io_reply->SCSIStatus;
3135 			mpt_set_ccb_status(ccb, CAM_SCSI_STATUS_ERROR);
3136 			if ((sstate & MPI_SCSI_STATE_AUTOSENSE_FAILED) != 0)
3137 				mpt_set_ccb_status(ccb, CAM_AUTOSENSE_FAIL);
3138 		} else if ((sstate & MPI_SCSI_STATE_RESPONSE_INFO_VALID) != 0) {
3139 
3140 			/* XXX Handle SPI-Packet and FCP-2 reponse info. */
3141 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3142 		} else
3143 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3144 		break;
3145 	case MPI_IOCSTATUS_SCSI_DATA_OVERRUN:
3146 		mpt_set_ccb_status(ccb, CAM_DATA_RUN_ERR);
3147 		break;
3148 	case MPI_IOCSTATUS_SCSI_IO_DATA_ERROR:
3149 		mpt_set_ccb_status(ccb, CAM_UNCOR_PARITY);
3150 		break;
3151 	case MPI_IOCSTATUS_SCSI_DEVICE_NOT_THERE:
3152 		/*
3153 		 * Since selection timeouts and "device really not
3154 		 * there" are grouped into this error code, report
3155 		 * selection timeout.  Selection timeouts are
3156 		 * typically retried before giving up on the device
3157 		 * whereas "device not there" errors are considered
3158 		 * unretryable.
3159 		 */
3160 		mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3161 		break;
3162 	case MPI_IOCSTATUS_SCSI_PROTOCOL_ERROR:
3163 		mpt_set_ccb_status(ccb, CAM_SEQUENCE_FAIL);
3164 		break;
3165 	case MPI_IOCSTATUS_SCSI_INVALID_BUS:
3166 		mpt_set_ccb_status(ccb, CAM_PATH_INVALID);
3167 		break;
3168 	case MPI_IOCSTATUS_SCSI_INVALID_TARGETID:
3169 		mpt_set_ccb_status(ccb, CAM_TID_INVALID);
3170 		break;
3171 	case MPI_IOCSTATUS_SCSI_TASK_MGMT_FAILED:
3172 		ccb->ccb_h.status = CAM_UA_TERMIO;
3173 		break;
3174 	case MPI_IOCSTATUS_INVALID_STATE:
3175 		/*
3176 		 * The IOC has been reset.  Emulate a bus reset.
3177 		 */
3178 		/* FALLTHROUGH */
3179 	case MPI_IOCSTATUS_SCSI_EXT_TERMINATED:
3180 		ccb->ccb_h.status = CAM_SCSI_BUS_RESET;
3181 		break;
3182 	case MPI_IOCSTATUS_SCSI_TASK_TERMINATED:
3183 	case MPI_IOCSTATUS_SCSI_IOC_TERMINATED:
3184 		/*
3185 		 * Don't clobber any timeout status that has
3186 		 * already been set for this transaction.  We
3187 		 * want the SCSI layer to be able to differentiate
3188 		 * between the command we aborted due to timeout
3189 		 * and any innocent bystanders.
3190 		 */
3191 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG)
3192 			break;
3193 		mpt_set_ccb_status(ccb, CAM_REQ_TERMIO);
3194 		break;
3195 
3196 	case MPI_IOCSTATUS_INSUFFICIENT_RESOURCES:
3197 		mpt_set_ccb_status(ccb, CAM_RESRC_UNAVAIL);
3198 		break;
3199 	case MPI_IOCSTATUS_BUSY:
3200 		mpt_set_ccb_status(ccb, CAM_BUSY);
3201 		break;
3202 	case MPI_IOCSTATUS_INVALID_FUNCTION:
3203 	case MPI_IOCSTATUS_INVALID_SGL:
3204 	case MPI_IOCSTATUS_INTERNAL_ERROR:
3205 	case MPI_IOCSTATUS_INVALID_FIELD:
3206 	default:
3207 		/* XXX
3208 		 * Some of the above may need to kick
3209 		 * of a recovery action!!!!
3210 		 */
3211 		ccb->ccb_h.status = CAM_UNREC_HBA_ERROR;
3212 		break;
3213 	}
3214 
3215 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3216 		mpt_freeze_ccb(ccb);
3217 	}
3218 
3219 	return (TRUE);
3220 }
3221 
3222 static void
3223 mpt_action(struct cam_sim *sim, union ccb *ccb)
3224 {
3225 	struct mpt_softc *mpt;
3226 	struct ccb_trans_settings *cts;
3227 	target_id_t tgt;
3228 	lun_id_t lun;
3229 	int raid_passthru;
3230 
3231 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("mpt_action\n"));
3232 
3233 	mpt = (struct mpt_softc *)cam_sim_softc(sim);
3234 	raid_passthru = (sim == mpt->phydisk_sim);
3235 	MPT_LOCK_ASSERT(mpt);
3236 
3237 	tgt = ccb->ccb_h.target_id;
3238 	lun = ccb->ccb_h.target_lun;
3239 	if (raid_passthru &&
3240 	    ccb->ccb_h.func_code != XPT_PATH_INQ &&
3241 	    ccb->ccb_h.func_code != XPT_RESET_BUS &&
3242 	    ccb->ccb_h.func_code != XPT_RESET_DEV) {
3243 		CAMLOCK_2_MPTLOCK(mpt);
3244 		if (mpt_map_physdisk(mpt, ccb, &tgt) != 0) {
3245 			MPTLOCK_2_CAMLOCK(mpt);
3246 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3247 			mpt_set_ccb_status(ccb, CAM_DEV_NOT_THERE);
3248 			xpt_done(ccb);
3249 			return;
3250 		}
3251 		MPTLOCK_2_CAMLOCK(mpt);
3252 	}
3253 	ccb->ccb_h.ccb_mpt_ptr = mpt;
3254 
3255 	switch (ccb->ccb_h.func_code) {
3256 	case XPT_SCSI_IO:	/* Execute the requested I/O operation */
3257 		/*
3258 		 * Do a couple of preliminary checks...
3259 		 */
3260 		if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
3261 			if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
3262 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3263 				mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3264 				break;
3265 			}
3266 		}
3267 		/* Max supported CDB length is 16 bytes */
3268 		/* XXX Unless we implement the new 32byte message type */
3269 		if (ccb->csio.cdb_len >
3270 		    sizeof (((PTR_MSG_SCSI_IO_REQUEST)0)->CDB)) {
3271 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3272 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3273 			break;
3274 		}
3275 #ifdef	MPT_TEST_MULTIPATH
3276 		if (mpt->failure_id == ccb->ccb_h.target_id) {
3277 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3278 			mpt_set_ccb_status(ccb, CAM_SEL_TIMEOUT);
3279 			break;
3280 		}
3281 #endif
3282 		ccb->csio.scsi_status = SCSI_STATUS_OK;
3283 		mpt_start(sim, ccb);
3284 		return;
3285 
3286 	case XPT_RESET_BUS:
3287 		if (raid_passthru) {
3288 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3289 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3290 			break;
3291 		}
3292 	case XPT_RESET_DEV:
3293 		if (ccb->ccb_h.func_code == XPT_RESET_BUS) {
3294 			if (bootverbose) {
3295 				xpt_print(ccb->ccb_h.path, "reset bus\n");
3296 			}
3297 		} else {
3298 			xpt_print(ccb->ccb_h.path, "reset device\n");
3299 		}
3300 		CAMLOCK_2_MPTLOCK(mpt);
3301 		(void) mpt_bus_reset(mpt, tgt, lun, FALSE);
3302 		MPTLOCK_2_CAMLOCK(mpt);
3303 
3304 		/*
3305 		 * mpt_bus_reset is always successful in that it
3306 		 * will fall back to a hard reset should a bus
3307 		 * reset attempt fail.
3308 		 */
3309 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3310 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3311 		break;
3312 
3313 	case XPT_ABORT:
3314 	{
3315 		union ccb *accb = ccb->cab.abort_ccb;
3316 		CAMLOCK_2_MPTLOCK(mpt);
3317 		switch (accb->ccb_h.func_code) {
3318 		case XPT_ACCEPT_TARGET_IO:
3319 		case XPT_IMMED_NOTIFY:
3320 			ccb->ccb_h.status = mpt_abort_target_ccb(mpt, ccb);
3321 			break;
3322 		case XPT_CONT_TARGET_IO:
3323 			mpt_prt(mpt, "cannot abort active CTIOs yet\n");
3324 			ccb->ccb_h.status = CAM_UA_ABORT;
3325 			break;
3326 		case XPT_SCSI_IO:
3327 			ccb->ccb_h.status = CAM_UA_ABORT;
3328 			break;
3329 		default:
3330 			ccb->ccb_h.status = CAM_REQ_INVALID;
3331 			break;
3332 		}
3333 		MPTLOCK_2_CAMLOCK(mpt);
3334 		break;
3335 	}
3336 
3337 #ifdef	CAM_NEW_TRAN_CODE
3338 #define	IS_CURRENT_SETTINGS(c)	((c)->type == CTS_TYPE_CURRENT_SETTINGS)
3339 #else
3340 #define	IS_CURRENT_SETTINGS(c)	((c)->flags & CCB_TRANS_CURRENT_SETTINGS)
3341 #endif
3342 #define	DP_DISC_ENABLE	0x1
3343 #define	DP_DISC_DISABL	0x2
3344 #define	DP_DISC		(DP_DISC_ENABLE|DP_DISC_DISABL)
3345 
3346 #define	DP_TQING_ENABLE	0x4
3347 #define	DP_TQING_DISABL	0x8
3348 #define	DP_TQING	(DP_TQING_ENABLE|DP_TQING_DISABL)
3349 
3350 #define	DP_WIDE		0x10
3351 #define	DP_NARROW	0x20
3352 #define	DP_WIDTH	(DP_WIDE|DP_NARROW)
3353 
3354 #define	DP_SYNC		0x40
3355 
3356 	case XPT_SET_TRAN_SETTINGS:	/* Nexus Settings */
3357 	{
3358 #ifdef	CAM_NEW_TRAN_CODE
3359 		struct ccb_trans_settings_scsi *scsi;
3360 		struct ccb_trans_settings_spi *spi;
3361 #endif
3362 		uint8_t dval;
3363 		u_int period;
3364 		u_int offset;
3365 		int i, j;
3366 
3367 		cts = &ccb->cts;
3368 
3369 		if (mpt->is_fc || mpt->is_sas) {
3370 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3371 			break;
3372 		}
3373 
3374 #ifdef	CAM_NEW_TRAN_CODE
3375 		scsi = &cts->proto_specific.scsi;
3376 		spi = &cts->xport_specific.spi;
3377 
3378 		/*
3379 		 * We can be called just to valid transport and proto versions
3380 		 */
3381 		if (scsi->valid == 0 && spi->valid == 0) {
3382 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3383 			break;
3384 		}
3385 #endif
3386 
3387 		/*
3388 		 * Skip attempting settings on RAID volume disks.
3389 		 * Other devices on the bus get the normal treatment.
3390 		 */
3391 		if (mpt->phydisk_sim && raid_passthru == 0 &&
3392 		    mpt_is_raid_volume(mpt, tgt) != 0) {
3393 			mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3394 			    "no transfer settings for RAID vols\n");
3395 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3396 			break;
3397 		}
3398 
3399 		i = mpt->mpt_port_page2.PortSettings &
3400 		    MPI_SCSIPORTPAGE2_PORT_MASK_NEGO_MASTER_SETTINGS;
3401 		j = mpt->mpt_port_page2.PortFlags &
3402 		    MPI_SCSIPORTPAGE2_PORT_FLAGS_DV_MASK;
3403 		if (i == MPI_SCSIPORTPAGE2_PORT_ALL_MASTER_SETTINGS &&
3404 		    j == MPI_SCSIPORTPAGE2_PORT_FLAGS_OFF_DV) {
3405 			mpt_lprt(mpt, MPT_PRT_ALWAYS,
3406 			    "honoring BIOS transfer negotiations\n");
3407 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3408 			break;
3409 		}
3410 
3411 		dval = 0;
3412 		period = 0;
3413 		offset = 0;
3414 
3415 #ifndef	CAM_NEW_TRAN_CODE
3416 		if ((cts->valid & CCB_TRANS_DISC_VALID) != 0) {
3417 			dval |= (cts->flags & CCB_TRANS_DISC_ENB) ?
3418 			    DP_DISC_ENABLE : DP_DISC_DISABL;
3419 		}
3420 
3421 		if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
3422 			dval |= (cts->flags & CCB_TRANS_TAG_ENB) ?
3423 			    DP_TQING_ENABLE : DP_TQING_DISABL;
3424 		}
3425 
3426 		if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) != 0) {
3427 			dval |= cts->bus_width ? DP_WIDE : DP_NARROW;
3428 		}
3429 
3430 		if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) &&
3431 		    (cts->valid & CCB_TRANS_SYNC_OFFSET_VALID)) {
3432 			dval |= DP_SYNC;
3433 			period = cts->sync_period;
3434 			offset = cts->sync_offset;
3435 		}
3436 #else
3437 		if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
3438 			dval |= ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0) ?
3439 			    DP_DISC_ENABLE : DP_DISC_DISABL;
3440 		}
3441 
3442 		if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
3443 			dval |= ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0) ?
3444 			    DP_TQING_ENABLE : DP_TQING_DISABL;
3445 		}
3446 
3447 		if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
3448 			dval |= (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT) ?
3449 			    DP_WIDE : DP_NARROW;
3450 		}
3451 
3452 		if (spi->valid & CTS_SPI_VALID_SYNC_OFFSET) {
3453 			dval |= DP_SYNC;
3454 			offset = spi->sync_offset;
3455 		} else {
3456 			PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3457 			    &mpt->mpt_dev_page1[tgt];
3458 			offset = ptr->RequestedParameters;
3459 			offset &= MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3460 	    		offset >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3461 		}
3462 		if (spi->valid & CTS_SPI_VALID_SYNC_RATE) {
3463 			dval |= DP_SYNC;
3464 			period = spi->sync_period;
3465 		} else {
3466 			PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr =
3467 			    &mpt->mpt_dev_page1[tgt];
3468 			period = ptr->RequestedParameters;
3469 			period &= MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3470 	    		period >>= MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3471 		}
3472 #endif
3473 		CAMLOCK_2_MPTLOCK(mpt);
3474 		if (dval & DP_DISC_ENABLE) {
3475 			mpt->mpt_disc_enable |= (1 << tgt);
3476 		} else if (dval & DP_DISC_DISABL) {
3477 			mpt->mpt_disc_enable &= ~(1 << tgt);
3478 		}
3479 		if (dval & DP_TQING_ENABLE) {
3480 			mpt->mpt_tag_enable |= (1 << tgt);
3481 		} else if (dval & DP_TQING_DISABL) {
3482 			mpt->mpt_tag_enable &= ~(1 << tgt);
3483 		}
3484 		if (dval & DP_WIDTH) {
3485 			mpt_setwidth(mpt, tgt, 1);
3486 		}
3487 		if (dval & DP_SYNC) {
3488 			mpt_setsync(mpt, tgt, period, offset);
3489 		}
3490 		if (dval == 0) {
3491 			MPTLOCK_2_CAMLOCK(mpt);
3492 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3493 			break;
3494 		}
3495 		mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3496 		    "set [%d]: 0x%x period 0x%x offset %d\n",
3497 		    tgt, dval, period, offset);
3498 		if (mpt_update_spi_config(mpt, tgt)) {
3499 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3500 		} else {
3501 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3502 		}
3503 		MPTLOCK_2_CAMLOCK(mpt);
3504 		break;
3505 	}
3506 	case XPT_GET_TRAN_SETTINGS:
3507 	{
3508 #ifdef	CAM_NEW_TRAN_CODE
3509 		struct ccb_trans_settings_scsi *scsi;
3510 		cts = &ccb->cts;
3511 		cts->protocol = PROTO_SCSI;
3512 		if (mpt->is_fc) {
3513 			struct ccb_trans_settings_fc *fc =
3514 			    &cts->xport_specific.fc;
3515 			cts->protocol_version = SCSI_REV_SPC;
3516 			cts->transport = XPORT_FC;
3517 			cts->transport_version = 0;
3518 			fc->valid = CTS_FC_VALID_SPEED;
3519 			fc->bitrate = 100000;
3520 		} else if (mpt->is_sas) {
3521 			struct ccb_trans_settings_sas *sas =
3522 			    &cts->xport_specific.sas;
3523 			cts->protocol_version = SCSI_REV_SPC2;
3524 			cts->transport = XPORT_SAS;
3525 			cts->transport_version = 0;
3526 			sas->valid = CTS_SAS_VALID_SPEED;
3527 			sas->bitrate = 300000;
3528 		} else {
3529 			cts->protocol_version = SCSI_REV_2;
3530 			cts->transport = XPORT_SPI;
3531 			cts->transport_version = 2;
3532 			if (mpt_get_spi_settings(mpt, cts) != 0) {
3533 				mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3534 				break;
3535 			}
3536 		}
3537 		scsi = &cts->proto_specific.scsi;
3538 		scsi->valid = CTS_SCSI_VALID_TQ;
3539 		scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3540 #else
3541 		cts = &ccb->cts;
3542 		if (mpt->is_fc) {
3543 			cts->flags = CCB_TRANS_TAG_ENB | CCB_TRANS_DISC_ENB;
3544 			cts->valid = CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3545 			cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3546 		} else if (mpt->is_sas) {
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_get_spi_settings(mpt, cts) != 0) {
3551 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3552 			break;
3553 		}
3554 #endif
3555 		mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3556 		break;
3557 	}
3558 	case XPT_CALC_GEOMETRY:
3559 	{
3560 		struct ccb_calc_geometry *ccg;
3561 
3562 		ccg = &ccb->ccg;
3563 		if (ccg->block_size == 0) {
3564 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3565 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3566 			break;
3567 		}
3568 		mpt_calc_geometry(ccg, /*extended*/1);
3569 		KASSERT(ccb->ccb_h.status, ("zero ccb sts at %d\n", __LINE__));
3570 		break;
3571 	}
3572 	case XPT_PATH_INQ:		/* Path routing inquiry */
3573 	{
3574 		struct ccb_pathinq *cpi = &ccb->cpi;
3575 
3576 		cpi->version_num = 1;
3577 		cpi->target_sprt = 0;
3578 		cpi->hba_eng_cnt = 0;
3579 		cpi->max_target = mpt->port_facts[0].MaxDevices - 1;
3580 		/*
3581 		 * FC cards report MAX_DEVICES of 512, but
3582 		 * the MSG_SCSI_IO_REQUEST target id field
3583 		 * is only 8 bits. Until we fix the driver
3584 		 * to support 'channels' for bus overflow,
3585 		 * just limit it.
3586 		 */
3587 		if (cpi->max_target > 255) {
3588 			cpi->max_target = 255;
3589 		}
3590 
3591 		/*
3592 		 * VMware ESX reports > 16 devices and then dies when we probe.
3593 		 */
3594 		if (mpt->is_spi && cpi->max_target > 15) {
3595 			cpi->max_target = 15;
3596 		}
3597 		if (mpt->is_spi)
3598 			cpi->max_lun = 7;
3599 		else
3600 			cpi->max_lun = MPT_MAX_LUNS;
3601 		cpi->initiator_id = mpt->mpt_ini_id;
3602 		cpi->bus_id = cam_sim_bus(sim);
3603 
3604 		/*
3605 		 * The base speed is the speed of the underlying connection.
3606 		 */
3607 #ifdef	CAM_NEW_TRAN_CODE
3608 		cpi->protocol = PROTO_SCSI;
3609 		if (mpt->is_fc) {
3610 			cpi->hba_misc = PIM_NOBUSRESET;
3611 			cpi->base_transfer_speed = 100000;
3612 			cpi->hba_inquiry = PI_TAG_ABLE;
3613 			cpi->transport = XPORT_FC;
3614 			cpi->transport_version = 0;
3615 			cpi->protocol_version = SCSI_REV_SPC;
3616 		} else if (mpt->is_sas) {
3617 			cpi->hba_misc = PIM_NOBUSRESET;
3618 			cpi->base_transfer_speed = 300000;
3619 			cpi->hba_inquiry = PI_TAG_ABLE;
3620 			cpi->transport = XPORT_SAS;
3621 			cpi->transport_version = 0;
3622 			cpi->protocol_version = SCSI_REV_SPC2;
3623 		} else {
3624 			cpi->hba_misc = PIM_SEQSCAN;
3625 			cpi->base_transfer_speed = 3300;
3626 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3627 			cpi->transport = XPORT_SPI;
3628 			cpi->transport_version = 2;
3629 			cpi->protocol_version = SCSI_REV_2;
3630 		}
3631 #else
3632 		if (mpt->is_fc) {
3633 			cpi->hba_misc = PIM_NOBUSRESET;
3634 			cpi->base_transfer_speed = 100000;
3635 			cpi->hba_inquiry = PI_TAG_ABLE;
3636 		} else if (mpt->is_sas) {
3637 			cpi->hba_misc = PIM_NOBUSRESET;
3638 			cpi->base_transfer_speed = 300000;
3639 			cpi->hba_inquiry = PI_TAG_ABLE;
3640 		} else {
3641 			cpi->hba_misc = PIM_SEQSCAN;
3642 			cpi->base_transfer_speed = 3300;
3643 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
3644 		}
3645 #endif
3646 
3647 		/*
3648 		 * We give our fake RAID passhtru bus a width that is MaxVolumes
3649 		 * wide and restrict it to one lun.
3650 		 */
3651 		if (raid_passthru) {
3652 			cpi->max_target = mpt->ioc_page2->MaxPhysDisks - 1;
3653 			cpi->initiator_id = cpi->max_target + 1;
3654 			cpi->max_lun = 0;
3655 		}
3656 
3657 		if ((mpt->role & MPT_ROLE_INITIATOR) == 0) {
3658 			cpi->hba_misc |= PIM_NOINITIATOR;
3659 		}
3660 		if (mpt->is_fc && (mpt->role & MPT_ROLE_TARGET)) {
3661 			cpi->target_sprt =
3662 			    PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
3663 		} else {
3664 			cpi->target_sprt = 0;
3665 		}
3666 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
3667 		strncpy(cpi->hba_vid, "LSI", HBA_IDLEN);
3668 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
3669 		cpi->unit_number = cam_sim_unit(sim);
3670 		cpi->ccb_h.status = CAM_REQ_CMP;
3671 		break;
3672 	}
3673 	case XPT_EN_LUN:		/* Enable LUN as a target */
3674 	{
3675 		int result;
3676 
3677 		CAMLOCK_2_MPTLOCK(mpt);
3678 		if (ccb->cel.enable)
3679 			result = mpt_enable_lun(mpt,
3680 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3681 		else
3682 			result = mpt_disable_lun(mpt,
3683 			    ccb->ccb_h.target_id, ccb->ccb_h.target_lun);
3684 		MPTLOCK_2_CAMLOCK(mpt);
3685 		if (result == 0) {
3686 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
3687 		} else {
3688 			mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
3689 		}
3690 		break;
3691 	}
3692 	case XPT_NOTIFY_ACK:		/* recycle notify ack */
3693 	case XPT_IMMED_NOTIFY:		/* Add Immediate Notify Resource */
3694 	case XPT_ACCEPT_TARGET_IO:	/* Add Accept Target IO Resource */
3695 	{
3696 		tgt_resource_t *trtp;
3697 		lun_id_t lun = ccb->ccb_h.target_lun;
3698 		ccb->ccb_h.sim_priv.entries[0].field = 0;
3699 		ccb->ccb_h.sim_priv.entries[1].ptr = mpt;
3700 		ccb->ccb_h.flags = 0;
3701 
3702 		if (lun == CAM_LUN_WILDCARD) {
3703 			if (ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
3704 				mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3705 				break;
3706 			}
3707 			trtp = &mpt->trt_wildcard;
3708 		} else if (lun >= MPT_MAX_LUNS) {
3709 			mpt_set_ccb_status(ccb, CAM_REQ_INVALID);
3710 			break;
3711 		} else {
3712 			trtp = &mpt->trt[lun];
3713 		}
3714 		CAMLOCK_2_MPTLOCK(mpt);
3715 		if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
3716 			mpt_lprt(mpt, MPT_PRT_DEBUG1,
3717 			    "Put FREE ATIO %p lun %d\n", ccb, lun);
3718 			STAILQ_INSERT_TAIL(&trtp->atios, &ccb->ccb_h,
3719 			    sim_links.stqe);
3720 		} else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
3721 			mpt_lprt(mpt, MPT_PRT_DEBUG1,
3722 			    "Put FREE INOT lun %d\n", lun);
3723 			STAILQ_INSERT_TAIL(&trtp->inots, &ccb->ccb_h,
3724 			    sim_links.stqe);
3725 		} else {
3726 			mpt_lprt(mpt, MPT_PRT_ALWAYS, "Got Notify ACK\n");
3727 		}
3728 		mpt_set_ccb_status(ccb, CAM_REQ_INPROG);
3729 		MPTLOCK_2_CAMLOCK(mpt);
3730 		return;
3731 	}
3732 	case XPT_CONT_TARGET_IO:
3733 		CAMLOCK_2_MPTLOCK(mpt);
3734 		mpt_target_start_io(mpt, ccb);
3735 		MPTLOCK_2_CAMLOCK(mpt);
3736 		return;
3737 
3738 	default:
3739 		ccb->ccb_h.status = CAM_REQ_INVALID;
3740 		break;
3741 	}
3742 	xpt_done(ccb);
3743 }
3744 
3745 static int
3746 mpt_get_spi_settings(struct mpt_softc *mpt, struct ccb_trans_settings *cts)
3747 {
3748 #ifdef	CAM_NEW_TRAN_CODE
3749 	struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3750 	struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3751 #endif
3752 	target_id_t tgt;
3753 	uint32_t dval, pval, oval;
3754 	int rv;
3755 
3756 	if (IS_CURRENT_SETTINGS(cts) == 0) {
3757 		tgt = cts->ccb_h.target_id;
3758 	} else if (xpt_path_sim(cts->ccb_h.path) == mpt->phydisk_sim) {
3759 		if (mpt_map_physdisk(mpt, (union ccb *)cts, &tgt)) {
3760 			return (-1);
3761 		}
3762 	} else {
3763 		tgt = cts->ccb_h.target_id;
3764 	}
3765 
3766 	/*
3767 	 * We aren't looking at Port Page 2 BIOS settings here-
3768 	 * sometimes these have been known to be bogus XXX.
3769 	 *
3770 	 * For user settings, we pick the max from port page 0
3771 	 *
3772 	 * For current settings we read the current settings out from
3773 	 * device page 0 for that target.
3774 	 */
3775 	if (IS_CURRENT_SETTINGS(cts)) {
3776 		CONFIG_PAGE_SCSI_DEVICE_0 tmp;
3777 		dval = 0;
3778 
3779 		CAMLOCK_2_MPTLOCK(mpt);
3780 		tmp = mpt->mpt_dev_page0[tgt];
3781 		rv = mpt_read_cur_cfg_page(mpt, tgt, &tmp.Header,
3782 		    sizeof(tmp), FALSE, 5000);
3783 		if (rv) {
3784 			MPTLOCK_2_CAMLOCK(mpt);
3785 			mpt_prt(mpt, "can't get tgt %d config page 0\n", tgt);
3786 			return (rv);
3787 		}
3788 		mpt2host_config_page_scsi_device_0(&tmp);
3789 
3790 		MPTLOCK_2_CAMLOCK(mpt);
3791 		mpt_lprt(mpt, MPT_PRT_DEBUG,
3792 		    "mpt_get_spi_settings[%d]: current NP %x Info %x\n", tgt,
3793 		    tmp.NegotiatedParameters, tmp.Information);
3794 		dval |= (tmp.NegotiatedParameters & MPI_SCSIDEVPAGE0_NP_WIDE) ?
3795 		    DP_WIDE : DP_NARROW;
3796 		dval |= (mpt->mpt_disc_enable & (1 << tgt)) ?
3797 		    DP_DISC_ENABLE : DP_DISC_DISABL;
3798 		dval |= (mpt->mpt_tag_enable & (1 << tgt)) ?
3799 		    DP_TQING_ENABLE : DP_TQING_DISABL;
3800 		oval = tmp.NegotiatedParameters;
3801 		oval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK;
3802 		oval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_OFFSET;
3803 		pval = tmp.NegotiatedParameters;
3804 		pval &= MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK;
3805 		pval >>= MPI_SCSIDEVPAGE0_NP_SHIFT_SYNC_PERIOD;
3806 		mpt->mpt_dev_page0[tgt] = tmp;
3807 	} else {
3808 		dval = DP_WIDE|DP_DISC_ENABLE|DP_TQING_ENABLE|DP_SYNC;
3809 		oval = mpt->mpt_port_page0.Capabilities;
3810 		oval = MPI_SCSIPORTPAGE0_CAP_GET_MAX_SYNC_OFFSET(oval);
3811 		pval = mpt->mpt_port_page0.Capabilities;
3812 		pval = MPI_SCSIPORTPAGE0_CAP_GET_MIN_SYNC_PERIOD(pval);
3813 	}
3814 
3815 #ifndef	CAM_NEW_TRAN_CODE
3816 	cts->flags &= ~(CCB_TRANS_DISC_ENB|CCB_TRANS_TAG_ENB);
3817 	cts->valid = 0;
3818 	cts->sync_period = pval;
3819 	cts->sync_offset = oval;
3820 	cts->valid |= CCB_TRANS_SYNC_RATE_VALID;
3821 	cts->valid |= CCB_TRANS_SYNC_OFFSET_VALID;
3822 	cts->valid |= CCB_TRANS_BUS_WIDTH_VALID;
3823 	if (dval & DP_WIDE) {
3824 		cts->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3825 	} else {
3826 		cts->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3827 	}
3828 	if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3829 		cts->valid |= CCB_TRANS_DISC_VALID | CCB_TRANS_TQ_VALID;
3830 		if (dval & DP_DISC_ENABLE) {
3831 			cts->flags |= CCB_TRANS_DISC_ENB;
3832 		}
3833 		if (dval & DP_TQING_ENABLE) {
3834 			cts->flags |= CCB_TRANS_TAG_ENB;
3835 		}
3836 	}
3837 #else
3838 	spi->valid = 0;
3839 	scsi->valid = 0;
3840 	spi->flags = 0;
3841 	scsi->flags = 0;
3842 	spi->sync_offset = oval;
3843 	spi->sync_period = pval;
3844 	spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
3845 	spi->valid |= CTS_SPI_VALID_SYNC_RATE;
3846 	spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
3847 	if (dval & DP_WIDE) {
3848 		spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3849 	} else {
3850 		spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3851 	}
3852 	if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3853 		scsi->valid = CTS_SCSI_VALID_TQ;
3854 		if (dval & DP_TQING_ENABLE) {
3855 			scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
3856 		}
3857 		spi->valid |= CTS_SPI_VALID_DISC;
3858 		if (dval & DP_DISC_ENABLE) {
3859 			spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
3860 		}
3861 	}
3862 #endif
3863 	mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3864 	    "mpt_get_spi_settings[%d]: %s flags 0x%x per 0x%x off=%d\n", tgt,
3865 	    IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM ", dval, pval, oval);
3866 	return (0);
3867 }
3868 
3869 static void
3870 mpt_setwidth(struct mpt_softc *mpt, int tgt, int onoff)
3871 {
3872 	PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3873 
3874 	ptr = &mpt->mpt_dev_page1[tgt];
3875 	if (onoff) {
3876 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_WIDE;
3877 	} else {
3878 		ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_WIDE;
3879 	}
3880 }
3881 
3882 static void
3883 mpt_setsync(struct mpt_softc *mpt, int tgt, int period, int offset)
3884 {
3885 	PTR_CONFIG_PAGE_SCSI_DEVICE_1 ptr;
3886 
3887 	ptr = &mpt->mpt_dev_page1[tgt];
3888 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MIN_SYNC_PERIOD_MASK;
3889 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_MAX_SYNC_OFFSET_MASK;
3890 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_DT;
3891 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_QAS;
3892 	ptr->RequestedParameters &= ~MPI_SCSIDEVPAGE1_RP_IU;
3893 	if (period == 0) {
3894 		return;
3895 	}
3896 	ptr->RequestedParameters |=
3897 	    period << MPI_SCSIDEVPAGE1_RP_SHIFT_MIN_SYNC_PERIOD;
3898 	ptr->RequestedParameters |=
3899 	    offset << MPI_SCSIDEVPAGE1_RP_SHIFT_MAX_SYNC_OFFSET;
3900 	if (period < 0xa) {
3901 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_DT;
3902 	}
3903 	if (period < 0x9) {
3904 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_QAS;
3905 		ptr->RequestedParameters |= MPI_SCSIDEVPAGE1_RP_IU;
3906 	}
3907 }
3908 
3909 static int
3910 mpt_update_spi_config(struct mpt_softc *mpt, int tgt)
3911 {
3912 	CONFIG_PAGE_SCSI_DEVICE_1 tmp;
3913 	int rv;
3914 
3915 	mpt_lprt(mpt, MPT_PRT_NEGOTIATION,
3916 	    "mpt_update_spi_config[%d].page1: Requested Params 0x%08x\n",
3917 	    tgt, mpt->mpt_dev_page1[tgt].RequestedParameters);
3918 	tmp = mpt->mpt_dev_page1[tgt];
3919 	host2mpt_config_page_scsi_device_1(&tmp);
3920 	rv = mpt_write_cur_cfg_page(mpt, tgt,
3921 	    &tmp.Header, sizeof(tmp), FALSE, 5000);
3922 	if (rv) {
3923 		mpt_prt(mpt, "mpt_update_spi_config: write cur page failed\n");
3924 		return (-1);
3925 	}
3926 	return (0);
3927 }
3928 
3929 static void
3930 mpt_calc_geometry(struct ccb_calc_geometry *ccg, int extended)
3931 {
3932 #if __FreeBSD_version >= 500000
3933 	cam_calc_geometry(ccg, extended);
3934 #else
3935 	uint32_t size_mb;
3936 	uint32_t secs_per_cylinder;
3937 
3938 	if (ccg->block_size == 0) {
3939 		ccg->ccb_h.status = CAM_REQ_INVALID;
3940 		return;
3941 	}
3942 	size_mb = ccg->volume_size / ((1024L * 1024L) / ccg->block_size);
3943 	if (size_mb > 1024 && extended) {
3944 		ccg->heads = 255;
3945 		ccg->secs_per_track = 63;
3946 	} else {
3947 		ccg->heads = 64;
3948 		ccg->secs_per_track = 32;
3949 	}
3950 	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
3951 	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
3952 	ccg->ccb_h.status = CAM_REQ_CMP;
3953 #endif
3954 }
3955 
3956 /****************************** Timeout Recovery ******************************/
3957 static int
3958 mpt_spawn_recovery_thread(struct mpt_softc *mpt)
3959 {
3960 	int error;
3961 
3962 	error = mpt_kthread_create(mpt_recovery_thread, mpt,
3963 	    &mpt->recovery_thread, /*flags*/0,
3964 	    /*altstack*/0, "mpt_recovery%d", mpt->unit);
3965 	return (error);
3966 }
3967 
3968 static void
3969 mpt_terminate_recovery_thread(struct mpt_softc *mpt)
3970 {
3971 	if (mpt->recovery_thread == NULL) {
3972 		return;
3973 	}
3974 	mpt->shutdwn_recovery = 1;
3975 	wakeup(mpt);
3976 	/*
3977 	 * Sleep on a slightly different location
3978 	 * for this interlock just for added safety.
3979 	 */
3980 	mpt_sleep(mpt, &mpt->recovery_thread, PUSER, "thtrm", 0);
3981 }
3982 
3983 static void
3984 mpt_recovery_thread(void *arg)
3985 {
3986 	struct mpt_softc *mpt;
3987 
3988 	mpt = (struct mpt_softc *)arg;
3989 	MPT_LOCK(mpt);
3990 	for (;;) {
3991 		if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
3992 			if (mpt->shutdwn_recovery == 0) {
3993 				mpt_sleep(mpt, mpt, PUSER, "idle", 0);
3994 			}
3995 		}
3996 		if (mpt->shutdwn_recovery != 0) {
3997 			break;
3998 		}
3999 		mpt_recover_commands(mpt);
4000 	}
4001 	mpt->recovery_thread = NULL;
4002 	wakeup(&mpt->recovery_thread);
4003 	MPT_UNLOCK(mpt);
4004 	mpt_kthread_exit(0);
4005 }
4006 
4007 static int
4008 mpt_scsi_send_tmf(struct mpt_softc *mpt, u_int type, u_int flags,
4009     u_int channel, u_int target, u_int lun, u_int abort_ctx, int sleep_ok)
4010 {
4011 	MSG_SCSI_TASK_MGMT *tmf_req;
4012 	int		    error;
4013 
4014 	/*
4015 	 * Wait for any current TMF request to complete.
4016 	 * We're only allowed to issue one TMF at a time.
4017 	 */
4018 	error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_FREE, REQ_STATE_FREE,
4019 	    sleep_ok, MPT_TMF_MAX_TIMEOUT);
4020 	if (error != 0) {
4021 		mpt_reset(mpt, TRUE);
4022 		return (ETIMEDOUT);
4023 	}
4024 
4025 	mpt_assign_serno(mpt, mpt->tmf_req);
4026 	mpt->tmf_req->state = REQ_STATE_ALLOCATED|REQ_STATE_QUEUED;
4027 
4028 	tmf_req = (MSG_SCSI_TASK_MGMT *)mpt->tmf_req->req_vbuf;
4029 	memset(tmf_req, 0, sizeof(*tmf_req));
4030 	tmf_req->TargetID = target;
4031 	tmf_req->Bus = channel;
4032 	tmf_req->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
4033 	tmf_req->TaskType = type;
4034 	tmf_req->MsgFlags = flags;
4035 	tmf_req->MsgContext =
4036 	    htole32(mpt->tmf_req->index | scsi_tmf_handler_id);
4037 	if (lun > MPT_MAX_LUNS) {
4038 		tmf_req->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4039 		tmf_req->LUN[1] = lun & 0xff;
4040 	} else {
4041 		tmf_req->LUN[1] = lun;
4042 	}
4043 	tmf_req->TaskMsgContext = abort_ctx;
4044 
4045 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4046 	    "Issuing TMF %p:%u with MsgContext of 0x%x\n", mpt->tmf_req,
4047 	    mpt->tmf_req->serno, tmf_req->MsgContext);
4048 	if (mpt->verbose > MPT_PRT_DEBUG) {
4049 		mpt_print_request(tmf_req);
4050 	}
4051 
4052 	KASSERT(mpt_req_on_pending_list(mpt, mpt->tmf_req) == 0,
4053 	    ("mpt_scsi_send_tmf: tmf_req already on pending list"));
4054 	TAILQ_INSERT_HEAD(&mpt->request_pending_list, mpt->tmf_req, links);
4055 	error = mpt_send_handshake_cmd(mpt, sizeof(*tmf_req), tmf_req);
4056 	if (error != MPT_OK) {
4057 		TAILQ_REMOVE(&mpt->request_pending_list, mpt->tmf_req, links);
4058 		mpt->tmf_req->state = REQ_STATE_FREE;
4059 		mpt_reset(mpt, TRUE);
4060 	}
4061 	return (error);
4062 }
4063 
4064 /*
4065  * When a command times out, it is placed on the requeust_timeout_list
4066  * and we wake our recovery thread.  The MPT-Fusion architecture supports
4067  * only a single TMF operation at a time, so we serially abort/bdr, etc,
4068  * the timedout transactions.  The next TMF is issued either by the
4069  * completion handler of the current TMF waking our recovery thread,
4070  * or the TMF timeout handler causing a hard reset sequence.
4071  */
4072 static void
4073 mpt_recover_commands(struct mpt_softc *mpt)
4074 {
4075 	request_t	   *req;
4076 	union ccb	   *ccb;
4077 	int		    error;
4078 
4079 	if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4080 		/*
4081 		 * No work to do- leave.
4082 		 */
4083 		mpt_prt(mpt, "mpt_recover_commands: no requests.\n");
4084 		return;
4085 	}
4086 
4087 	/*
4088 	 * Flush any commands whose completion coincides with their timeout.
4089 	 */
4090 	mpt_intr(mpt);
4091 
4092 	if (TAILQ_EMPTY(&mpt->request_timeout_list) != 0) {
4093 		/*
4094 		 * The timedout commands have already
4095 		 * completed.  This typically means
4096 		 * that either the timeout value was on
4097 		 * the hairy edge of what the device
4098 		 * requires or - more likely - interrupts
4099 		 * are not happening.
4100 		 */
4101 		mpt_prt(mpt, "Timedout requests already complete. "
4102 		    "Interrupts may not be functioning.\n");
4103 		mpt_enable_ints(mpt);
4104 		return;
4105 	}
4106 
4107 	/*
4108 	 * We have no visibility into the current state of the
4109 	 * controller, so attempt to abort the commands in the
4110 	 * order they timed-out. For initiator commands, we
4111 	 * depend on the reply handler pulling requests off
4112 	 * the timeout list.
4113 	 */
4114 	while ((req = TAILQ_FIRST(&mpt->request_timeout_list)) != NULL) {
4115 		uint16_t status;
4116 		uint8_t response;
4117 		MSG_REQUEST_HEADER *hdrp = req->req_vbuf;
4118 
4119 		mpt_prt(mpt, "attempting to abort req %p:%u function %x\n",
4120 		    req, req->serno, hdrp->Function);
4121 		ccb = req->ccb;
4122 		if (ccb == NULL) {
4123 			mpt_prt(mpt, "null ccb in timed out request. "
4124 			    "Resetting Controller.\n");
4125 			mpt_reset(mpt, TRUE);
4126 			continue;
4127 		}
4128 		mpt_set_ccb_status(ccb, CAM_CMD_TIMEOUT);
4129 
4130 		/*
4131 		 * Check to see if this is not an initiator command and
4132 		 * deal with it differently if it is.
4133 		 */
4134 		switch (hdrp->Function) {
4135 		case MPI_FUNCTION_SCSI_IO_REQUEST:
4136 		case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
4137 			break;
4138 		default:
4139 			/*
4140 			 * XXX: FIX ME: need to abort target assists...
4141 			 */
4142 			mpt_prt(mpt, "just putting it back on the pend q\n");
4143 			TAILQ_REMOVE(&mpt->request_timeout_list, req, links);
4144 			TAILQ_INSERT_HEAD(&mpt->request_pending_list, req,
4145 			    links);
4146 			continue;
4147 		}
4148 
4149 		error = mpt_scsi_send_tmf(mpt,
4150 		    MPI_SCSITASKMGMT_TASKTYPE_ABORT_TASK,
4151 		    0, 0, ccb->ccb_h.target_id, ccb->ccb_h.target_lun,
4152 		    htole32(req->index | scsi_io_handler_id), TRUE);
4153 
4154 		if (error != 0) {
4155 			/*
4156 			 * mpt_scsi_send_tmf hard resets on failure, so no
4157 			 * need to do so here.  Our queue should be emptied
4158 			 * by the hard reset.
4159 			 */
4160 			continue;
4161 		}
4162 
4163 		error = mpt_wait_req(mpt, mpt->tmf_req, REQ_STATE_DONE,
4164 		    REQ_STATE_DONE, TRUE, 500);
4165 
4166 		status = le16toh(mpt->tmf_req->IOCStatus);
4167 		response = mpt->tmf_req->ResponseCode;
4168 		mpt->tmf_req->state = REQ_STATE_FREE;
4169 
4170 		if (error != 0) {
4171 			/*
4172 			 * If we've errored out,, reset the controller.
4173 			 */
4174 			mpt_prt(mpt, "mpt_recover_commands: abort timed-out. "
4175 			    "Resetting controller\n");
4176 			mpt_reset(mpt, TRUE);
4177 			continue;
4178 		}
4179 
4180 		if ((status & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
4181 			mpt_prt(mpt, "mpt_recover_commands: IOC Status 0x%x. "
4182 			    "Resetting controller.\n", status);
4183 			mpt_reset(mpt, TRUE);
4184 			continue;
4185 		}
4186 
4187 		if (response != MPI_SCSITASKMGMT_RSP_TM_SUCCEEDED &&
4188 		    response != MPI_SCSITASKMGMT_RSP_TM_COMPLETE) {
4189 			mpt_prt(mpt, "mpt_recover_commands: TMF Response 0x%x. "
4190 			    "Resetting controller.\n", response);
4191 			mpt_reset(mpt, TRUE);
4192 			continue;
4193 		}
4194 		mpt_prt(mpt, "abort of req %p:%u completed\n", req, req->serno);
4195 	}
4196 }
4197 
4198 /************************ Target Mode Support ****************************/
4199 static void
4200 mpt_fc_post_els(struct mpt_softc *mpt, request_t *req, int ioindex)
4201 {
4202 	MSG_LINK_SERVICE_BUFFER_POST_REQUEST *fc;
4203 	PTR_SGE_TRANSACTION32 tep;
4204 	PTR_SGE_SIMPLE32 se;
4205 	bus_addr_t paddr;
4206 	uint32_t fl;
4207 
4208 	paddr = req->req_pbuf;
4209 	paddr += MPT_RQSL(mpt);
4210 
4211 	fc = req->req_vbuf;
4212 	memset(fc, 0, MPT_REQUEST_AREA);
4213 	fc->BufferCount = 1;
4214 	fc->Function = MPI_FUNCTION_FC_LINK_SRVC_BUF_POST;
4215 	fc->MsgContext = htole32(req->index | fc_els_handler_id);
4216 
4217 	/*
4218 	 * Okay, set up ELS buffer pointers. ELS buffer pointers
4219 	 * consist of a TE SGL element (with details length of zero)
4220 	 * followe by a SIMPLE SGL element which holds the address
4221 	 * of the buffer.
4222 	 */
4223 
4224 	tep = (PTR_SGE_TRANSACTION32) &fc->SGL;
4225 
4226 	tep->ContextSize = 4;
4227 	tep->Flags = 0;
4228 	tep->TransactionContext[0] = htole32(ioindex);
4229 
4230 	se = (PTR_SGE_SIMPLE32) &tep->TransactionDetails[0];
4231 	fl =
4232 		MPI_SGE_FLAGS_HOST_TO_IOC	|
4233 		MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
4234 		MPI_SGE_FLAGS_LAST_ELEMENT	|
4235 		MPI_SGE_FLAGS_END_OF_LIST	|
4236 		MPI_SGE_FLAGS_END_OF_BUFFER;
4237 	fl <<= MPI_SGE_FLAGS_SHIFT;
4238 	fl |= (MPT_NRFM(mpt) - MPT_RQSL(mpt));
4239 	se->FlagsLength = htole32(fl);
4240 	se->Address = htole32((uint32_t) paddr);
4241 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4242 	    "add ELS index %d ioindex %d for %p:%u\n",
4243 	    req->index, ioindex, req, req->serno);
4244 	KASSERT(((req->state & REQ_STATE_LOCKED) != 0),
4245 	    ("mpt_fc_post_els: request not locked"));
4246 	mpt_send_cmd(mpt, req);
4247 }
4248 
4249 static void
4250 mpt_post_target_command(struct mpt_softc *mpt, request_t *req, int ioindex)
4251 {
4252 	PTR_MSG_TARGET_CMD_BUFFER_POST_REQUEST fc;
4253 	PTR_CMD_BUFFER_DESCRIPTOR cb;
4254 	bus_addr_t paddr;
4255 
4256 	paddr = req->req_pbuf;
4257 	paddr += MPT_RQSL(mpt);
4258 	memset(req->req_vbuf, 0, MPT_REQUEST_AREA);
4259 	MPT_TGT_STATE(mpt, req)->state = TGT_STATE_LOADING;
4260 
4261 	fc = req->req_vbuf;
4262 	fc->BufferCount = 1;
4263 	fc->Function = MPI_FUNCTION_TARGET_CMD_BUFFER_POST;
4264 	fc->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4265 
4266 	cb = &fc->Buffer[0];
4267 	cb->IoIndex = htole16(ioindex);
4268 	cb->u.PhysicalAddress32 = htole32((U32) paddr);
4269 
4270 	mpt_check_doorbell(mpt);
4271 	mpt_send_cmd(mpt, req);
4272 }
4273 
4274 static int
4275 mpt_add_els_buffers(struct mpt_softc *mpt)
4276 {
4277 	int i;
4278 
4279 	if (mpt->is_fc == 0) {
4280 		return (TRUE);
4281 	}
4282 
4283 	if (mpt->els_cmds_allocated) {
4284 		return (TRUE);
4285 	}
4286 
4287 	mpt->els_cmd_ptrs = malloc(MPT_MAX_ELS * sizeof (request_t *),
4288 	    M_DEVBUF, M_NOWAIT | M_ZERO);
4289 
4290 	if (mpt->els_cmd_ptrs == NULL) {
4291 		return (FALSE);
4292 	}
4293 
4294 	/*
4295 	 * Feed the chip some ELS buffer resources
4296 	 */
4297 	for (i = 0; i < MPT_MAX_ELS; i++) {
4298 		request_t *req = mpt_get_request(mpt, FALSE);
4299 		if (req == NULL) {
4300 			break;
4301 		}
4302 		req->state |= REQ_STATE_LOCKED;
4303 		mpt->els_cmd_ptrs[i] = req;
4304 		mpt_fc_post_els(mpt, req, i);
4305 	}
4306 
4307 	if (i == 0) {
4308 		mpt_prt(mpt, "unable to add ELS buffer resources\n");
4309 		free(mpt->els_cmd_ptrs, M_DEVBUF);
4310 		mpt->els_cmd_ptrs = NULL;
4311 		return (FALSE);
4312 	}
4313 	if (i != MPT_MAX_ELS) {
4314 		mpt_lprt(mpt, MPT_PRT_INFO,
4315 		    "only added %d of %d  ELS buffers\n", i, MPT_MAX_ELS);
4316 	}
4317 	mpt->els_cmds_allocated = i;
4318 	return(TRUE);
4319 }
4320 
4321 static int
4322 mpt_add_target_commands(struct mpt_softc *mpt)
4323 {
4324 	int i, max;
4325 
4326 	if (mpt->tgt_cmd_ptrs) {
4327 		return (TRUE);
4328 	}
4329 
4330 	max = MPT_MAX_REQUESTS(mpt) >> 1;
4331 	if (max > mpt->mpt_max_tgtcmds) {
4332 		max = mpt->mpt_max_tgtcmds;
4333 	}
4334 	mpt->tgt_cmd_ptrs =
4335 	    malloc(max * sizeof (request_t *), M_DEVBUF, M_NOWAIT | M_ZERO);
4336 	if (mpt->tgt_cmd_ptrs == NULL) {
4337 		mpt_prt(mpt,
4338 		    "mpt_add_target_commands: could not allocate cmd ptrs\n");
4339 		return (FALSE);
4340 	}
4341 
4342 	for (i = 0; i < max; i++) {
4343 		request_t *req;
4344 
4345 		req = mpt_get_request(mpt, FALSE);
4346 		if (req == NULL) {
4347 			break;
4348 		}
4349 		req->state |= REQ_STATE_LOCKED;
4350 		mpt->tgt_cmd_ptrs[i] = req;
4351 		mpt_post_target_command(mpt, req, i);
4352 	}
4353 
4354 
4355 	if (i == 0) {
4356 		mpt_lprt(mpt, MPT_PRT_ERROR, "could not add any target bufs\n");
4357 		free(mpt->tgt_cmd_ptrs, M_DEVBUF);
4358 		mpt->tgt_cmd_ptrs = NULL;
4359 		return (FALSE);
4360 	}
4361 
4362 	mpt->tgt_cmds_allocated = i;
4363 
4364 	if (i < max) {
4365 		mpt_lprt(mpt, MPT_PRT_INFO,
4366 		    "added %d of %d target bufs\n", i, max);
4367 	}
4368 	return (i);
4369 }
4370 
4371 static int
4372 mpt_enable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4373 {
4374 	if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4375 		mpt->twildcard = 1;
4376 	} else if (lun >= MPT_MAX_LUNS) {
4377 		return (EINVAL);
4378 	} else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4379 		return (EINVAL);
4380 	}
4381 	if (mpt->tenabled == 0) {
4382 		if (mpt->is_fc) {
4383 			(void) mpt_fc_reset_link(mpt, 0);
4384 		}
4385 		mpt->tenabled = 1;
4386 	}
4387 	if (lun == CAM_LUN_WILDCARD) {
4388 		mpt->trt_wildcard.enabled = 1;
4389 	} else {
4390 		mpt->trt[lun].enabled = 1;
4391 	}
4392 	return (0);
4393 }
4394 
4395 static int
4396 mpt_disable_lun(struct mpt_softc *mpt, target_id_t tgt, lun_id_t lun)
4397 {
4398 	int i;
4399 	if (tgt == CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
4400 		mpt->twildcard = 0;
4401 	} else if (lun >= MPT_MAX_LUNS) {
4402 		return (EINVAL);
4403 	} else if (tgt != CAM_TARGET_WILDCARD && tgt != 0) {
4404 		return (EINVAL);
4405 	}
4406 	if (lun == CAM_LUN_WILDCARD) {
4407 		mpt->trt_wildcard.enabled = 0;
4408 	} else {
4409 		mpt->trt[lun].enabled = 0;
4410 	}
4411 	for (i = 0; i < MPT_MAX_LUNS; i++) {
4412 		if (mpt->trt[lun].enabled) {
4413 			break;
4414 		}
4415 	}
4416 	if (i == MPT_MAX_LUNS && mpt->twildcard == 0) {
4417 		if (mpt->is_fc) {
4418 			(void) mpt_fc_reset_link(mpt, 0);
4419 		}
4420 		mpt->tenabled = 0;
4421 	}
4422 	return (0);
4423 }
4424 
4425 /*
4426  * Called with MPT lock held
4427  */
4428 static void
4429 mpt_target_start_io(struct mpt_softc *mpt, union ccb *ccb)
4430 {
4431 	struct ccb_scsiio *csio = &ccb->csio;
4432 	request_t *cmd_req = MPT_TAG_2_REQ(mpt, csio->tag_id);
4433 	mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, cmd_req);
4434 
4435 	switch (tgt->state) {
4436 	case TGT_STATE_IN_CAM:
4437 		break;
4438 	case TGT_STATE_MOVING_DATA:
4439 		mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4440 		xpt_freeze_simq(mpt->sim, 1);
4441 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4442 		tgt->ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4443 		MPTLOCK_2_CAMLOCK(mpt);
4444 		xpt_done(ccb);
4445 		CAMLOCK_2_MPTLOCK(mpt);
4446 		return;
4447 	default:
4448 		mpt_prt(mpt, "ccb %p flags 0x%x tag 0x%08x had bad request "
4449 		    "starting I/O\n", ccb, csio->ccb_h.flags, csio->tag_id);
4450 		mpt_tgt_dump_req_state(mpt, cmd_req);
4451 		mpt_set_ccb_status(ccb, CAM_REQ_CMP_ERR);
4452 		MPTLOCK_2_CAMLOCK(mpt);
4453 		xpt_done(ccb);
4454 		CAMLOCK_2_MPTLOCK(mpt);
4455 		return;
4456 	}
4457 
4458 	if (csio->dxfer_len) {
4459 		bus_dmamap_callback_t *cb;
4460 		PTR_MSG_TARGET_ASSIST_REQUEST ta;
4461 		request_t *req;
4462 
4463 		KASSERT((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE,
4464 		    ("dxfer_len %u but direction is NONE\n", csio->dxfer_len));
4465 
4466 		if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4467 			if (mpt->outofbeer == 0) {
4468 				mpt->outofbeer = 1;
4469 				xpt_freeze_simq(mpt->sim, 1);
4470 				mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4471 			}
4472 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4473 			mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4474 			MPTLOCK_2_CAMLOCK(mpt);
4475 			xpt_done(ccb);
4476 			CAMLOCK_2_MPTLOCK(mpt);
4477 			return;
4478 		}
4479 		ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4480 		if (sizeof (bus_addr_t) > 4) {
4481 			cb = mpt_execute_req_a64;
4482 		} else {
4483 			cb = mpt_execute_req;
4484 		}
4485 
4486 		req->ccb = ccb;
4487 		ccb->ccb_h.ccb_req_ptr = req;
4488 
4489 		/*
4490 		 * Record the currently active ccb and the
4491 		 * request for it in our target state area.
4492 		 */
4493 		tgt->ccb = ccb;
4494 		tgt->req = req;
4495 
4496 		memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4497 		ta = req->req_vbuf;
4498 
4499 		if (mpt->is_sas) {
4500 			PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4501 			     cmd_req->req_vbuf;
4502 			ta->QueueTag = ssp->InitiatorTag;
4503 		} else if (mpt->is_spi) {
4504 			PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4505 			     cmd_req->req_vbuf;
4506 			ta->QueueTag = sp->Tag;
4507 		}
4508 		ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4509 		ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4510 		ta->ReplyWord = htole32(tgt->reply_desc);
4511 		if (csio->ccb_h.target_lun > MPT_MAX_LUNS) {
4512 			ta->LUN[0] =
4513 			    0x40 | ((csio->ccb_h.target_lun >> 8) & 0x3f);
4514 			ta->LUN[1] = csio->ccb_h.target_lun & 0xff;
4515 		} else {
4516 			ta->LUN[1] = csio->ccb_h.target_lun;
4517 		}
4518 
4519 		ta->RelativeOffset = tgt->bytes_xfered;
4520 		ta->DataLength = ccb->csio.dxfer_len;
4521 		if (ta->DataLength > tgt->resid) {
4522 			ta->DataLength = tgt->resid;
4523 		}
4524 
4525 		/*
4526 		 * XXX Should be done after data transfer completes?
4527 		 */
4528 		tgt->resid -= csio->dxfer_len;
4529 		tgt->bytes_xfered += csio->dxfer_len;
4530 
4531 		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4532 			ta->TargetAssistFlags |=
4533 			    TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4534 		}
4535 
4536 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4537 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) &&
4538 		    csio->scsi_status == SCSI_STATUS_OK && tgt->resid == 0) {
4539 			ta->TargetAssistFlags |=
4540 			    TARGET_ASSIST_FLAGS_AUTO_STATUS;
4541 		}
4542 #endif
4543 		tgt->state = TGT_STATE_SETTING_UP_FOR_DATA;
4544 
4545 		mpt_lprt(mpt, MPT_PRT_DEBUG,
4546 		    "DATA_CCB %p tag %x %u bytes %u resid flg %x req %p:%u "
4547 		    "nxtstate=%d\n", csio, csio->tag_id, csio->dxfer_len,
4548 		    tgt->resid, ccb->ccb_h.flags, req, req->serno, tgt->state);
4549 
4550 		MPTLOCK_2_CAMLOCK(mpt);
4551 		if ((ccb->ccb_h.flags & CAM_SCATTER_VALID) == 0) {
4552 			if ((ccb->ccb_h.flags & CAM_DATA_PHYS) == 0) {
4553 				int error;
4554 				int s = splsoftvm();
4555 				error = bus_dmamap_load(mpt->buffer_dmat,
4556 				    req->dmap, csio->data_ptr, csio->dxfer_len,
4557 				    cb, req, 0);
4558 				splx(s);
4559 				if (error == EINPROGRESS) {
4560 					xpt_freeze_simq(mpt->sim, 1);
4561 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
4562 				}
4563 			} else {
4564 				/*
4565 				 * We have been given a pointer to single
4566 				 * physical buffer.
4567 				 */
4568 				struct bus_dma_segment seg;
4569 				seg.ds_addr = (bus_addr_t)
4570 				    (vm_offset_t)csio->data_ptr;
4571 				seg.ds_len = csio->dxfer_len;
4572 				(*cb)(req, &seg, 1, 0);
4573 			}
4574 		} else {
4575 			/*
4576 			 * We have been given a list of addresses.
4577 			 * This case could be easily supported but they are not
4578 			 * currently generated by the CAM subsystem so there
4579 			 * is no point in wasting the time right now.
4580 			 */
4581 			struct bus_dma_segment *sgs;
4582 			if ((ccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0) {
4583 				(*cb)(req, NULL, 0, EFAULT);
4584 			} else {
4585 				/* Just use the segments provided */
4586 				sgs = (struct bus_dma_segment *)csio->data_ptr;
4587 				(*cb)(req, sgs, csio->sglist_cnt, 0);
4588 			}
4589 		}
4590 		CAMLOCK_2_MPTLOCK(mpt);
4591 	} else {
4592 		uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
4593 
4594 		/*
4595 		 * XXX: I don't know why this seems to happen, but
4596 		 * XXX: completing the CCB seems to make things happy.
4597 		 * XXX: This seems to happen if the initiator requests
4598 		 * XXX: enough data that we have to do multiple CTIOs.
4599 		 */
4600 		if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
4601 			mpt_lprt(mpt, MPT_PRT_DEBUG,
4602 			    "Meaningless STATUS CCB (%p): flags %x status %x "
4603 			    "resid %d bytes_xfered %u\n", ccb, ccb->ccb_h.flags,
4604 			    ccb->ccb_h.status, tgt->resid, tgt->bytes_xfered);
4605 			mpt_set_ccb_status(ccb, CAM_REQ_CMP);
4606 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4607 			MPTLOCK_2_CAMLOCK(mpt);
4608 			xpt_done(ccb);
4609 			CAMLOCK_2_MPTLOCK(mpt);
4610 			return;
4611 		}
4612 		if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
4613 			sp = sense;
4614 			memcpy(sp, &csio->sense_data,
4615 			   min(csio->sense_len, MPT_SENSE_SIZE));
4616 		}
4617 		mpt_scsi_tgt_status(mpt, ccb, cmd_req, csio->scsi_status, sp);
4618 	}
4619 }
4620 
4621 static void
4622 mpt_scsi_tgt_local(struct mpt_softc *mpt, request_t *cmd_req,
4623     uint32_t lun, int send, uint8_t *data, size_t length)
4624 {
4625 	mpt_tgt_state_t *tgt;
4626 	PTR_MSG_TARGET_ASSIST_REQUEST ta;
4627 	SGE_SIMPLE32 *se;
4628 	uint32_t flags;
4629 	uint8_t *dptr;
4630 	bus_addr_t pptr;
4631 	request_t *req;
4632 
4633 	/*
4634 	 * We enter with resid set to the data load for the command.
4635 	 */
4636 	tgt = MPT_TGT_STATE(mpt, cmd_req);
4637 	if (length == 0 || tgt->resid == 0) {
4638 		tgt->resid = 0;
4639 		mpt_scsi_tgt_status(mpt, NULL, cmd_req, 0, NULL);
4640 		return;
4641 	}
4642 
4643 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4644 		mpt_prt(mpt, "out of resources- dropping local response\n");
4645 		return;
4646 	}
4647 	tgt->is_local = 1;
4648 
4649 
4650 	memset(req->req_vbuf, 0, MPT_RQSL(mpt));
4651 	ta = req->req_vbuf;
4652 
4653 	if (mpt->is_sas) {
4654 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp = cmd_req->req_vbuf;
4655 		ta->QueueTag = ssp->InitiatorTag;
4656 	} else if (mpt->is_spi) {
4657 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp = cmd_req->req_vbuf;
4658 		ta->QueueTag = sp->Tag;
4659 	}
4660 	ta->Function = MPI_FUNCTION_TARGET_ASSIST;
4661 	ta->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4662 	ta->ReplyWord = htole32(tgt->reply_desc);
4663 	if (lun > MPT_MAX_LUNS) {
4664 		ta->LUN[0] = 0x40 | ((lun >> 8) & 0x3f);
4665 		ta->LUN[1] = lun & 0xff;
4666 	} else {
4667 		ta->LUN[1] = lun;
4668 	}
4669 	ta->RelativeOffset = 0;
4670 	ta->DataLength = length;
4671 
4672 	dptr = req->req_vbuf;
4673 	dptr += MPT_RQSL(mpt);
4674 	pptr = req->req_pbuf;
4675 	pptr += MPT_RQSL(mpt);
4676 	memcpy(dptr, data, min(length, MPT_RQSL(mpt)));
4677 
4678 	se = (SGE_SIMPLE32 *) &ta->SGL[0];
4679 	memset(se, 0,sizeof (*se));
4680 
4681 	flags = MPI_SGE_FLAGS_SIMPLE_ELEMENT;
4682 	if (send) {
4683 		ta->TargetAssistFlags |= TARGET_ASSIST_FLAGS_DATA_DIRECTION;
4684 		flags |= MPI_SGE_FLAGS_HOST_TO_IOC;
4685 	}
4686 	se->Address = pptr;
4687 	MPI_pSGE_SET_LENGTH(se, length);
4688 	flags |= MPI_SGE_FLAGS_LAST_ELEMENT;
4689 	flags |= MPI_SGE_FLAGS_END_OF_LIST | MPI_SGE_FLAGS_END_OF_BUFFER;
4690 	MPI_pSGE_SET_FLAGS(se, flags);
4691 
4692 	tgt->ccb = NULL;
4693 	tgt->req = req;
4694 	tgt->resid -= length;
4695 	tgt->bytes_xfered = length;
4696 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4697 	tgt->state = TGT_STATE_MOVING_DATA_AND_STATUS;
4698 #else
4699 	tgt->state = TGT_STATE_MOVING_DATA;
4700 #endif
4701 	mpt_send_cmd(mpt, req);
4702 }
4703 
4704 /*
4705  * Abort queued up CCBs
4706  */
4707 static cam_status
4708 mpt_abort_target_ccb(struct mpt_softc *mpt, union ccb *ccb)
4709 {
4710 	struct mpt_hdr_stailq *lp;
4711 	struct ccb_hdr *srch;
4712 	int found = 0;
4713 	union ccb *accb = ccb->cab.abort_ccb;
4714 	tgt_resource_t *trtp;
4715 
4716 	mpt_lprt(mpt, MPT_PRT_DEBUG, "aborting ccb %p\n", accb);
4717 
4718 	if (ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
4719 		trtp = &mpt->trt_wildcard;
4720 	} else {
4721 		trtp = &mpt->trt[ccb->ccb_h.target_lun];
4722 	}
4723 
4724 	if (accb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
4725 		lp = &trtp->atios;
4726 	} else if (accb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
4727 		lp = &trtp->inots;
4728 	} else {
4729 		return (CAM_REQ_INVALID);
4730 	}
4731 
4732 	STAILQ_FOREACH(srch, lp, sim_links.stqe) {
4733 		if (srch == &accb->ccb_h) {
4734 			found = 1;
4735 			STAILQ_REMOVE(lp, srch, ccb_hdr, sim_links.stqe);
4736 			break;
4737 		}
4738 	}
4739 	if (found) {
4740 		accb->ccb_h.status = CAM_REQ_ABORTED;
4741 		xpt_done(accb);
4742 		return (CAM_REQ_CMP);
4743 	}
4744 	mpt_prt(mpt, "mpt_abort_tgt_ccb: CCB %p not found\n", ccb);
4745 	return (CAM_PATH_INVALID);
4746 }
4747 
4748 /*
4749  * Ask the MPT to abort the current target command
4750  */
4751 static int
4752 mpt_abort_target_cmd(struct mpt_softc *mpt, request_t *cmd_req)
4753 {
4754 	int error;
4755 	request_t *req;
4756 	PTR_MSG_TARGET_MODE_ABORT abtp;
4757 
4758 	req = mpt_get_request(mpt, FALSE);
4759 	if (req == NULL) {
4760 		return (-1);
4761 	}
4762 	abtp = req->req_vbuf;
4763 	memset(abtp, 0, sizeof (*abtp));
4764 
4765 	abtp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4766 	abtp->AbortType = TARGET_MODE_ABORT_TYPE_EXACT_IO;
4767 	abtp->Function = MPI_FUNCTION_TARGET_MODE_ABORT;
4768 	abtp->ReplyWord = htole32(MPT_TGT_STATE(mpt, cmd_req)->reply_desc);
4769 	error = 0;
4770 	if (mpt->is_fc || mpt->is_sas) {
4771 		mpt_send_cmd(mpt, req);
4772 	} else {
4773 		error = mpt_send_handshake_cmd(mpt, sizeof(*req), req);
4774 	}
4775 	return (error);
4776 }
4777 
4778 /*
4779  * WE_TRUST_AUTO_GOOD_STATUS- I've found that setting
4780  * TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS leads the
4781  * FC929 to set bogus FC_RSP fields (nonzero residuals
4782  * but w/o RESID fields set). This causes QLogic initiators
4783  * to think maybe that a frame was lost.
4784  *
4785  * WE_CAN_USE_AUTO_REPOST- we can't use AUTO_REPOST because
4786  * we use allocated requests to do TARGET_ASSIST and we
4787  * need to know when to release them.
4788  */
4789 
4790 static void
4791 mpt_scsi_tgt_status(struct mpt_softc *mpt, union ccb *ccb, request_t *cmd_req,
4792     uint8_t status, uint8_t const *sense_data)
4793 {
4794 	uint8_t *cmd_vbuf;
4795 	mpt_tgt_state_t *tgt;
4796 	PTR_MSG_TARGET_STATUS_SEND_REQUEST tp;
4797 	request_t *req;
4798 	bus_addr_t paddr;
4799 	int resplen = 0;
4800 	uint32_t fl;
4801 
4802 	cmd_vbuf = cmd_req->req_vbuf;
4803 	cmd_vbuf += MPT_RQSL(mpt);
4804 	tgt = MPT_TGT_STATE(mpt, cmd_req);
4805 
4806 	if ((req = mpt_get_request(mpt, FALSE)) == NULL) {
4807 		if (mpt->outofbeer == 0) {
4808 			mpt->outofbeer = 1;
4809 			xpt_freeze_simq(mpt->sim, 1);
4810 			mpt_lprt(mpt, MPT_PRT_DEBUG, "FREEZEQ\n");
4811 		}
4812 		if (ccb) {
4813 			ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4814 			mpt_set_ccb_status(ccb, CAM_REQUEUE_REQ);
4815 			MPTLOCK_2_CAMLOCK(mpt);
4816 			xpt_done(ccb);
4817 			CAMLOCK_2_MPTLOCK(mpt);
4818 		} else {
4819 			mpt_prt(mpt,
4820 			    "could not allocate status request- dropping\n");
4821 		}
4822 		return;
4823 	}
4824 	req->ccb = ccb;
4825 	if (ccb) {
4826 		ccb->ccb_h.ccb_mpt_ptr = mpt;
4827 		ccb->ccb_h.ccb_req_ptr = req;
4828 	}
4829 
4830 	/*
4831 	 * Record the currently active ccb, if any, and the
4832 	 * request for it in our target state area.
4833 	 */
4834 	tgt->ccb = ccb;
4835 	tgt->req = req;
4836 	tgt->state = TGT_STATE_SENDING_STATUS;
4837 
4838 	tp = req->req_vbuf;
4839 	paddr = req->req_pbuf;
4840 	paddr += MPT_RQSL(mpt);
4841 
4842 	memset(tp, 0, sizeof (*tp));
4843 	tp->Function = MPI_FUNCTION_TARGET_STATUS_SEND;
4844 	if (mpt->is_fc) {
4845 		PTR_MPI_TARGET_FCP_CMD_BUFFER fc =
4846 		    (PTR_MPI_TARGET_FCP_CMD_BUFFER) cmd_vbuf;
4847 		uint8_t *sts_vbuf;
4848 		uint32_t *rsp;
4849 
4850 		sts_vbuf = req->req_vbuf;
4851 		sts_vbuf += MPT_RQSL(mpt);
4852 		rsp = (uint32_t *) sts_vbuf;
4853 		memcpy(tp->LUN, fc->FcpLun, sizeof (tp->LUN));
4854 
4855 		/*
4856 		 * The MPI_TARGET_FCP_RSP_BUFFER define is unfortunate.
4857 		 * It has to be big-endian in memory and is organized
4858 		 * in 32 bit words, which are much easier to deal with
4859 		 * as words which are swizzled as needed.
4860 		 *
4861 		 * All we're filling here is the FC_RSP payload.
4862 		 * We may just have the chip synthesize it if
4863 		 * we have no residual and an OK status.
4864 		 *
4865 		 */
4866 		memset(rsp, 0, sizeof (MPI_TARGET_FCP_RSP_BUFFER));
4867 
4868 		rsp[2] = status;
4869 		if (tgt->resid) {
4870 			rsp[2] |= 0x800;	/* XXXX NEED MNEMONIC!!!! */
4871 			rsp[3] = htobe32(tgt->resid);
4872 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4873 			resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4874 #endif
4875 		}
4876 		if (status == SCSI_STATUS_CHECK_COND) {
4877 			int i;
4878 
4879 			rsp[2] |= 0x200;	/* XXXX NEED MNEMONIC!!!! */
4880 			rsp[4] = htobe32(MPT_SENSE_SIZE);
4881 			if (sense_data) {
4882 				memcpy(&rsp[8], sense_data, MPT_SENSE_SIZE);
4883 			} else {
4884 				mpt_prt(mpt, "mpt_scsi_tgt_status: CHECK CONDI"
4885 				    "TION but no sense data?\n");
4886 				memset(&rsp, 0, MPT_SENSE_SIZE);
4887 			}
4888 			for (i = 8; i < (8 + (MPT_SENSE_SIZE >> 2)); i++) {
4889 				rsp[i] = htobe32(rsp[i]);
4890 			}
4891 #ifdef	WE_TRUST_AUTO_GOOD_STATUS
4892 			resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4893 #endif
4894 		}
4895 #ifndef	WE_TRUST_AUTO_GOOD_STATUS
4896 		resplen = sizeof (MPI_TARGET_FCP_RSP_BUFFER);
4897 #endif
4898 		rsp[2] = htobe32(rsp[2]);
4899 	} else if (mpt->is_sas) {
4900 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp =
4901 		    (PTR_MPI_TARGET_SSP_CMD_BUFFER) cmd_vbuf;
4902 		memcpy(tp->LUN, ssp->LogicalUnitNumber, sizeof (tp->LUN));
4903 	} else {
4904 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp =
4905 		    (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) cmd_vbuf;
4906 		tp->StatusCode = status;
4907 		tp->QueueTag = htole16(sp->Tag);
4908 		memcpy(tp->LUN, sp->LogicalUnitNumber, sizeof (tp->LUN));
4909 	}
4910 
4911 	tp->ReplyWord = htole32(tgt->reply_desc);
4912 	tp->MsgContext = htole32(req->index | mpt->scsi_tgt_handler_id);
4913 
4914 #ifdef	WE_CAN_USE_AUTO_REPOST
4915 	tp->MsgFlags = TARGET_STATUS_SEND_FLAGS_REPOST_CMD_BUFFER;
4916 #endif
4917 	if (status == SCSI_STATUS_OK && resplen == 0) {
4918 		tp->MsgFlags |= TARGET_STATUS_SEND_FLAGS_AUTO_GOOD_STATUS;
4919 	} else {
4920 		tp->StatusDataSGE.u.Address32 = htole32((uint32_t) paddr);
4921 		fl =
4922 			MPI_SGE_FLAGS_HOST_TO_IOC	|
4923 			MPI_SGE_FLAGS_SIMPLE_ELEMENT	|
4924 			MPI_SGE_FLAGS_LAST_ELEMENT	|
4925 			MPI_SGE_FLAGS_END_OF_LIST	|
4926 			MPI_SGE_FLAGS_END_OF_BUFFER;
4927 		fl <<= MPI_SGE_FLAGS_SHIFT;
4928 		fl |= resplen;
4929 		tp->StatusDataSGE.FlagsLength = htole32(fl);
4930 	}
4931 
4932 	mpt_lprt(mpt, MPT_PRT_DEBUG,
4933 	    "STATUS_CCB %p (wit%s sense) tag %x req %p:%u resid %u\n",
4934 	    ccb, sense_data?"h" : "hout", ccb? ccb->csio.tag_id : -1, req,
4935 	    req->serno, tgt->resid);
4936 	if (ccb) {
4937 		ccb->ccb_h.status = CAM_SIM_QUEUED | CAM_REQ_INPROG;
4938 		mpt_req_timeout(req, 60 * hz, mpt_timeout, ccb);
4939 	}
4940 	mpt_send_cmd(mpt, req);
4941 }
4942 
4943 static void
4944 mpt_scsi_tgt_tsk_mgmt(struct mpt_softc *mpt, request_t *req, mpt_task_mgmt_t fc,
4945     tgt_resource_t *trtp, int init_id)
4946 {
4947 	struct ccb_immed_notify *inot;
4948 	mpt_tgt_state_t *tgt;
4949 
4950 	tgt = MPT_TGT_STATE(mpt, req);
4951 	inot = (struct ccb_immed_notify *) STAILQ_FIRST(&trtp->inots);
4952 	if (inot == NULL) {
4953 		mpt_lprt(mpt, MPT_PRT_WARN, "no INOTSs- sending back BSY\n");
4954 		mpt_scsi_tgt_status(mpt, NULL, req, SCSI_STATUS_BUSY, NULL);
4955 		return;
4956 	}
4957 	STAILQ_REMOVE_HEAD(&trtp->inots, sim_links.stqe);
4958 	mpt_lprt(mpt, MPT_PRT_DEBUG1,
4959 	    "Get FREE INOT %p lun %d\n", inot, inot->ccb_h.target_lun);
4960 
4961 	memset(&inot->sense_data, 0, sizeof (inot->sense_data));
4962 	inot->sense_len = 0;
4963 	memset(inot->message_args, 0, sizeof (inot->message_args));
4964 	inot->initiator_id = init_id;	/* XXX */
4965 
4966 	/*
4967 	 * This is a somewhat grotesque attempt to map from task management
4968 	 * to old style SCSI messages. God help us all.
4969 	 */
4970 	switch (fc) {
4971 	case MPT_ABORT_TASK_SET:
4972 		inot->message_args[0] = MSG_ABORT_TAG;
4973 		break;
4974 	case MPT_CLEAR_TASK_SET:
4975 		inot->message_args[0] = MSG_CLEAR_TASK_SET;
4976 		break;
4977 	case MPT_TARGET_RESET:
4978 		inot->message_args[0] = MSG_TARGET_RESET;
4979 		break;
4980 	case MPT_CLEAR_ACA:
4981 		inot->message_args[0] = MSG_CLEAR_ACA;
4982 		break;
4983 	case MPT_TERMINATE_TASK:
4984 		inot->message_args[0] = MSG_ABORT_TAG;
4985 		break;
4986 	default:
4987 		inot->message_args[0] = MSG_NOOP;
4988 		break;
4989 	}
4990 	tgt->ccb = (union ccb *) inot;
4991 	inot->ccb_h.status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
4992 	MPTLOCK_2_CAMLOCK(mpt);
4993 	xpt_done((union ccb *)inot);
4994 	CAMLOCK_2_MPTLOCK(mpt);
4995 }
4996 
4997 static void
4998 mpt_scsi_tgt_atio(struct mpt_softc *mpt, request_t *req, uint32_t reply_desc)
4999 {
5000 	static uint8_t null_iqd[SHORT_INQUIRY_LENGTH] = {
5001 	    0x7f, 0x00, 0x02, 0x02, 0x20, 0x00, 0x00, 0x32,
5002 	     'F',  'R',  'E',  'E',  'B',  'S',  'D',  ' ',
5003 	     'L',  'S',  'I',  '-',  'L',  'O',  'G',  'I',
5004 	     'C',  ' ',  'N',  'U',  'L',  'D',  'E',  'V',
5005 	     '0',  '0',  '0',  '1'
5006 	};
5007 	struct ccb_accept_tio *atiop;
5008 	lun_id_t lun;
5009 	int tag_action = 0;
5010 	mpt_tgt_state_t *tgt;
5011 	tgt_resource_t *trtp = NULL;
5012 	U8 *lunptr;
5013 	U8 *vbuf;
5014 	U16 itag;
5015 	U16 ioindex;
5016 	mpt_task_mgmt_t fct = MPT_NIL_TMT_VALUE;
5017 	uint8_t *cdbp;
5018 
5019 	/*
5020 	 * First, DMA sync the received command-
5021 	 * which is in the *request* * phys area.
5022 	 *
5023 	 * XXX: We could optimize this for a range
5024 	 */
5025 	bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
5026 	    BUS_DMASYNC_POSTREAD);
5027 
5028 	/*
5029 	 * Stash info for the current command where we can get at it later.
5030 	 */
5031 	vbuf = req->req_vbuf;
5032 	vbuf += MPT_RQSL(mpt);
5033 
5034 	/*
5035 	 * Get our state pointer set up.
5036 	 */
5037 	tgt = MPT_TGT_STATE(mpt, req);
5038 	if (tgt->state != TGT_STATE_LOADED) {
5039 		mpt_tgt_dump_req_state(mpt, req);
5040 		panic("bad target state in mpt_scsi_tgt_atio");
5041 	}
5042 	memset(tgt, 0, sizeof (mpt_tgt_state_t));
5043 	tgt->state = TGT_STATE_IN_CAM;
5044 	tgt->reply_desc = reply_desc;
5045 	ioindex = GET_IO_INDEX(reply_desc);
5046 	if (mpt->verbose >= MPT_PRT_DEBUG) {
5047 		mpt_dump_data(mpt, "mpt_scsi_tgt_atio response", vbuf,
5048 		    max(sizeof (MPI_TARGET_FCP_CMD_BUFFER),
5049 		    max(sizeof (MPI_TARGET_SSP_CMD_BUFFER),
5050 		    sizeof (MPI_TARGET_SCSI_SPI_CMD_BUFFER))));
5051 	}
5052 	if (mpt->is_fc) {
5053 		PTR_MPI_TARGET_FCP_CMD_BUFFER fc;
5054 		fc = (PTR_MPI_TARGET_FCP_CMD_BUFFER) vbuf;
5055 		if (fc->FcpCntl[2]) {
5056 			/*
5057 			 * Task Management Request
5058 			 */
5059 			switch (fc->FcpCntl[2]) {
5060 			case 0x2:
5061 				fct = MPT_ABORT_TASK_SET;
5062 				break;
5063 			case 0x4:
5064 				fct = MPT_CLEAR_TASK_SET;
5065 				break;
5066 			case 0x20:
5067 				fct = MPT_TARGET_RESET;
5068 				break;
5069 			case 0x40:
5070 				fct = MPT_CLEAR_ACA;
5071 				break;
5072 			case 0x80:
5073 				fct = MPT_TERMINATE_TASK;
5074 				break;
5075 			default:
5076 				mpt_prt(mpt, "CORRUPTED TASK MGMT BITS: 0x%x\n",
5077 				    fc->FcpCntl[2]);
5078 				mpt_scsi_tgt_status(mpt, 0, req,
5079 				    SCSI_STATUS_OK, 0);
5080 				return;
5081 			}
5082 		} else {
5083 			switch (fc->FcpCntl[1]) {
5084 			case 0:
5085 				tag_action = MSG_SIMPLE_Q_TAG;
5086 				break;
5087 			case 1:
5088 				tag_action = MSG_HEAD_OF_Q_TAG;
5089 				break;
5090 			case 2:
5091 				tag_action = MSG_ORDERED_Q_TAG;
5092 				break;
5093 			default:
5094 				/*
5095 				 * Bah. Ignore Untagged Queing and ACA
5096 				 */
5097 				tag_action = MSG_SIMPLE_Q_TAG;
5098 				break;
5099 			}
5100 		}
5101 		tgt->resid = be32toh(fc->FcpDl);
5102 		cdbp = fc->FcpCdb;
5103 		lunptr = fc->FcpLun;
5104 		itag = be16toh(fc->OptionalOxid);
5105 	} else if (mpt->is_sas) {
5106 		PTR_MPI_TARGET_SSP_CMD_BUFFER ssp;
5107 		ssp = (PTR_MPI_TARGET_SSP_CMD_BUFFER) vbuf;
5108 		cdbp = ssp->CDB;
5109 		lunptr = ssp->LogicalUnitNumber;
5110 		itag = ssp->InitiatorTag;
5111 	} else {
5112 		PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER sp;
5113 		sp = (PTR_MPI_TARGET_SCSI_SPI_CMD_BUFFER) vbuf;
5114 		cdbp = sp->CDB;
5115 		lunptr = sp->LogicalUnitNumber;
5116 		itag = sp->Tag;
5117 	}
5118 
5119 	/*
5120 	 * Generate a simple lun
5121 	 */
5122 	switch (lunptr[0] & 0xc0) {
5123 	case 0x40:
5124 		lun = ((lunptr[0] & 0x3f) << 8) | lunptr[1];
5125 		break;
5126 	case 0:
5127 		lun = lunptr[1];
5128 		break;
5129 	default:
5130 		mpt_lprt(mpt, MPT_PRT_ERROR, "cannot handle this type lun\n");
5131 		lun = 0xffff;
5132 		break;
5133 	}
5134 
5135 	/*
5136 	 * Deal with non-enabled or bad luns here.
5137 	 */
5138 	if (lun >= MPT_MAX_LUNS || mpt->tenabled == 0 ||
5139 	    mpt->trt[lun].enabled == 0) {
5140 		if (mpt->twildcard) {
5141 			trtp = &mpt->trt_wildcard;
5142 		} else if (fct == MPT_NIL_TMT_VALUE) {
5143 			/*
5144 			 * In this case, we haven't got an upstream listener
5145 			 * for either a specific lun or wildcard luns. We
5146 			 * have to make some sensible response. For regular
5147 			 * inquiry, just return some NOT HERE inquiry data.
5148 			 * For VPD inquiry, report illegal field in cdb.
5149 			 * For REQUEST SENSE, just return NO SENSE data.
5150 			 * REPORT LUNS gets illegal command.
5151 			 * All other commands get 'no such device'.
5152 			 */
5153 			uint8_t *sp, cond, buf[MPT_SENSE_SIZE];
5154 			size_t len;
5155 
5156 			memset(buf, 0, MPT_SENSE_SIZE);
5157 			cond = SCSI_STATUS_CHECK_COND;
5158 			buf[0] = 0xf0;
5159 			buf[2] = 0x5;
5160 			buf[7] = 0x8;
5161 			sp = buf;
5162 			tgt->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5163 
5164 			switch (cdbp[0]) {
5165 			case INQUIRY:
5166 			{
5167 				if (cdbp[1] != 0) {
5168 					buf[12] = 0x26;
5169 					buf[13] = 0x01;
5170 					break;
5171 				}
5172 				len = min(tgt->resid, cdbp[4]);
5173 				len = min(len, sizeof (null_iqd));
5174 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5175 				    "local inquiry %ld bytes\n", (long) len);
5176 				mpt_scsi_tgt_local(mpt, req, lun, 1,
5177 				    null_iqd, len);
5178 				return;
5179 			}
5180 			case REQUEST_SENSE:
5181 			{
5182 				buf[2] = 0x0;
5183 				len = min(tgt->resid, cdbp[4]);
5184 				len = min(len, sizeof (buf));
5185 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5186 				    "local reqsense %ld bytes\n", (long) len);
5187 				mpt_scsi_tgt_local(mpt, req, lun, 1,
5188 				    buf, len);
5189 				return;
5190 			}
5191 			case REPORT_LUNS:
5192 				mpt_lprt(mpt, MPT_PRT_DEBUG, "REPORT LUNS\n");
5193 				buf[12] = 0x26;
5194 				return;
5195 			default:
5196 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5197 				    "CMD 0x%x to unmanaged lun %u\n",
5198 				    cdbp[0], lun);
5199 				buf[12] = 0x25;
5200 				break;
5201 			}
5202 			mpt_scsi_tgt_status(mpt, NULL, req, cond, sp);
5203 			return;
5204 		}
5205 		/* otherwise, leave trtp NULL */
5206 	} else {
5207 		trtp = &mpt->trt[lun];
5208 	}
5209 
5210 	/*
5211 	 * Deal with any task management
5212 	 */
5213 	if (fct != MPT_NIL_TMT_VALUE) {
5214 		if (trtp == NULL) {
5215 			mpt_prt(mpt, "task mgmt function %x but no listener\n",
5216 			    fct);
5217 			mpt_scsi_tgt_status(mpt, 0, req,
5218 			    SCSI_STATUS_OK, 0);
5219 		} else {
5220 			mpt_scsi_tgt_tsk_mgmt(mpt, req, fct, trtp,
5221 			    GET_INITIATOR_INDEX(reply_desc));
5222 		}
5223 		return;
5224 	}
5225 
5226 
5227 	atiop = (struct ccb_accept_tio *) STAILQ_FIRST(&trtp->atios);
5228 	if (atiop == NULL) {
5229 		mpt_lprt(mpt, MPT_PRT_WARN,
5230 		    "no ATIOs for lun %u- sending back %s\n", lun,
5231 		    mpt->tenabled? "QUEUE FULL" : "BUSY");
5232 		mpt_scsi_tgt_status(mpt, NULL, req,
5233 		    mpt->tenabled? SCSI_STATUS_QUEUE_FULL : SCSI_STATUS_BUSY,
5234 		    NULL);
5235 		return;
5236 	}
5237 	STAILQ_REMOVE_HEAD(&trtp->atios, sim_links.stqe);
5238 	mpt_lprt(mpt, MPT_PRT_DEBUG1,
5239 	    "Get FREE ATIO %p lun %d\n", atiop, atiop->ccb_h.target_lun);
5240 	atiop->ccb_h.ccb_mpt_ptr = mpt;
5241 	atiop->ccb_h.status = CAM_CDB_RECVD;
5242 	atiop->ccb_h.target_lun = lun;
5243 	atiop->sense_len = 0;
5244 	atiop->init_id = GET_INITIATOR_INDEX(reply_desc);
5245 	atiop->cdb_len = mpt_cdblen(cdbp[0], 16);
5246 	memcpy(atiop->cdb_io.cdb_bytes, cdbp, atiop->cdb_len);
5247 
5248 	/*
5249 	 * The tag we construct here allows us to find the
5250 	 * original request that the command came in with.
5251 	 *
5252 	 * This way we don't have to depend on anything but the
5253 	 * tag to find things when CCBs show back up from CAM.
5254 	 */
5255 	atiop->tag_id = MPT_MAKE_TAGID(mpt, req, ioindex);
5256 	tgt->tag_id = atiop->tag_id;
5257 	if (tag_action) {
5258 		atiop->tag_action = tag_action;
5259 		atiop->ccb_h.flags = CAM_TAG_ACTION_VALID;
5260 	}
5261 	if (mpt->verbose >= MPT_PRT_DEBUG) {
5262 		int i;
5263 		mpt_prt(mpt, "START_CCB %p for lun %u CDB=<", atiop,
5264 		    atiop->ccb_h.target_lun);
5265 		for (i = 0; i < atiop->cdb_len; i++) {
5266 			mpt_prtc(mpt, "%02x%c", cdbp[i] & 0xff,
5267 			    (i == (atiop->cdb_len - 1))? '>' : ' ');
5268 		}
5269 		mpt_prtc(mpt, " itag %x tag %x rdesc %x dl=%u\n",
5270 	    	    itag, atiop->tag_id, tgt->reply_desc, tgt->resid);
5271 	}
5272 
5273 	MPTLOCK_2_CAMLOCK(mpt);
5274 	xpt_done((union ccb *)atiop);
5275 	CAMLOCK_2_MPTLOCK(mpt);
5276 }
5277 
5278 static void
5279 mpt_tgt_dump_tgt_state(struct mpt_softc *mpt, request_t *req)
5280 {
5281 	mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5282 
5283 	mpt_prt(mpt, "req %p:%u tgt:rdesc 0x%x resid %u xfrd %u ccb %p treq %p "
5284 	    "nx %d tag 0x%08x state=%d\n", req, req->serno, tgt->reply_desc,
5285 	    tgt->resid, tgt->bytes_xfered, tgt->ccb, tgt->req, tgt->nxfers,
5286 	    tgt->tag_id, tgt->state);
5287 }
5288 
5289 static void
5290 mpt_tgt_dump_req_state(struct mpt_softc *mpt, request_t *req)
5291 {
5292 	mpt_prt(mpt, "req %p:%u index %u (%x) state %x\n", req, req->serno,
5293 	    req->index, req->index, req->state);
5294 	mpt_tgt_dump_tgt_state(mpt, req);
5295 }
5296 
5297 static int
5298 mpt_scsi_tgt_reply_handler(struct mpt_softc *mpt, request_t *req,
5299     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
5300 {
5301 	int dbg;
5302 	union ccb *ccb;
5303 	U16 status;
5304 
5305 	if (reply_frame == NULL) {
5306 		/*
5307 		 * Figure out what the state of the command is.
5308 		 */
5309 		mpt_tgt_state_t *tgt = MPT_TGT_STATE(mpt, req);
5310 
5311 #ifdef	INVARIANTS
5312 		mpt_req_spcl(mpt, req, "turbo scsi_tgt_reply", __LINE__);
5313 		if (tgt->req) {
5314 			mpt_req_not_spcl(mpt, tgt->req,
5315 			    "turbo scsi_tgt_reply associated req", __LINE__);
5316 		}
5317 #endif
5318 		switch(tgt->state) {
5319 		case TGT_STATE_LOADED:
5320 			/*
5321 			 * This is a new command starting.
5322 			 */
5323 			mpt_scsi_tgt_atio(mpt, req, reply_desc);
5324 			break;
5325 		case TGT_STATE_MOVING_DATA:
5326 		{
5327 			uint8_t *sp = NULL, sense[MPT_SENSE_SIZE];
5328 
5329 			ccb = tgt->ccb;
5330 			if (tgt->req == NULL) {
5331 				panic("mpt: turbo target reply with null "
5332 				    "associated request moving data");
5333 				/* NOTREACHED */
5334 			}
5335 			if (ccb == NULL) {
5336 				if (tgt->is_local == 0) {
5337 					panic("mpt: turbo target reply with "
5338 					    "null associated ccb moving data");
5339 					/* NOTREACHED */
5340 				}
5341 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5342 				    "TARGET_ASSIST local done\n");
5343 				TAILQ_REMOVE(&mpt->request_pending_list,
5344 				    tgt->req, links);
5345 				mpt_free_request(mpt, tgt->req);
5346 				tgt->req = NULL;
5347 				mpt_scsi_tgt_status(mpt, NULL, req,
5348 				    0, NULL);
5349 				return (TRUE);
5350 			}
5351 			tgt->ccb = NULL;
5352 			tgt->nxfers++;
5353 			mpt_req_untimeout(req, mpt_timeout, ccb);
5354 			mpt_lprt(mpt, MPT_PRT_DEBUG,
5355 			    "TARGET_ASSIST %p (req %p:%u) done tag 0x%x\n",
5356 			    ccb, tgt->req, tgt->req->serno, ccb->csio.tag_id);
5357 			/*
5358 			 * Free the Target Assist Request
5359 			 */
5360 			KASSERT(tgt->req->ccb == ccb,
5361 			    ("tgt->req %p:%u tgt->req->ccb %p", tgt->req,
5362 			    tgt->req->serno, tgt->req->ccb));
5363 			TAILQ_REMOVE(&mpt->request_pending_list,
5364 			    tgt->req, links);
5365 			mpt_free_request(mpt, tgt->req);
5366 			tgt->req = NULL;
5367 
5368 			/*
5369 			 * Do we need to send status now? That is, are
5370 			 * we done with all our data transfers?
5371 			 */
5372 			if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
5373 				mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5374 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5375 				KASSERT(ccb->ccb_h.status,
5376 				    ("zero ccb sts at %d\n", __LINE__));
5377 				tgt->state = TGT_STATE_IN_CAM;
5378 				if (mpt->outofbeer) {
5379 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5380 					mpt->outofbeer = 0;
5381 					mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5382 				}
5383 				MPTLOCK_2_CAMLOCK(mpt);
5384 				xpt_done(ccb);
5385 				CAMLOCK_2_MPTLOCK(mpt);
5386 				break;
5387 			}
5388 			/*
5389 			 * Otherwise, send status (and sense)
5390 			 */
5391 			if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5392 				sp = sense;
5393 				memcpy(sp, &ccb->csio.sense_data,
5394 				   min(ccb->csio.sense_len, MPT_SENSE_SIZE));
5395 			}
5396 			mpt_scsi_tgt_status(mpt, ccb, req,
5397 			    ccb->csio.scsi_status, sp);
5398 			break;
5399 		}
5400 		case TGT_STATE_SENDING_STATUS:
5401 		case TGT_STATE_MOVING_DATA_AND_STATUS:
5402 		{
5403 			int ioindex;
5404 			ccb = tgt->ccb;
5405 
5406 			if (tgt->req == NULL) {
5407 				panic("mpt: turbo target reply with null "
5408 				    "associated request sending status");
5409 				/* NOTREACHED */
5410 			}
5411 
5412 			if (ccb) {
5413 				tgt->ccb = NULL;
5414 				if (tgt->state ==
5415 				    TGT_STATE_MOVING_DATA_AND_STATUS) {
5416 					tgt->nxfers++;
5417 				}
5418 				mpt_req_untimeout(req, mpt_timeout, ccb);
5419 				if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
5420 					ccb->ccb_h.status |= CAM_SENT_SENSE;
5421 				}
5422 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5423 				    "TARGET_STATUS tag %x sts %x flgs %x req "
5424 				    "%p\n", ccb->csio.tag_id, ccb->ccb_h.status,
5425 				    ccb->ccb_h.flags, tgt->req);
5426 				/*
5427 				 * Free the Target Send Status Request
5428 				 */
5429 				KASSERT(tgt->req->ccb == ccb,
5430 				    ("tgt->req %p:%u tgt->req->ccb %p",
5431 				    tgt->req, tgt->req->serno, tgt->req->ccb));
5432 				/*
5433 				 * Notify CAM that we're done
5434 				 */
5435 				mpt_set_ccb_status(ccb, CAM_REQ_CMP);
5436 				ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5437 				KASSERT(ccb->ccb_h.status,
5438 				    ("ZERO ccb sts at %d\n", __LINE__));
5439 				tgt->ccb = NULL;
5440 			} else {
5441 				mpt_lprt(mpt, MPT_PRT_DEBUG,
5442 				    "TARGET_STATUS non-CAM for  req %p:%u\n",
5443 				    tgt->req, tgt->req->serno);
5444 			}
5445 			TAILQ_REMOVE(&mpt->request_pending_list,
5446 			    tgt->req, links);
5447 			mpt_free_request(mpt, tgt->req);
5448 			tgt->req = NULL;
5449 
5450 			/*
5451 			 * And re-post the Command Buffer.
5452 			 * This will reset the state.
5453 			 */
5454 			ioindex = GET_IO_INDEX(reply_desc);
5455 			TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5456 			tgt->is_local = 0;
5457 			mpt_post_target_command(mpt, req, ioindex);
5458 
5459 			/*
5460 			 * And post a done for anyone who cares
5461 			 */
5462 			if (ccb) {
5463 				if (mpt->outofbeer) {
5464 					ccb->ccb_h.status |= CAM_RELEASE_SIMQ;
5465 					mpt->outofbeer = 0;
5466 					mpt_lprt(mpt, MPT_PRT_DEBUG, "THAWQ\n");
5467 				}
5468 				MPTLOCK_2_CAMLOCK(mpt);
5469 				xpt_done(ccb);
5470 				CAMLOCK_2_MPTLOCK(mpt);
5471 			}
5472 			break;
5473 		}
5474 		case TGT_STATE_NIL:	/* XXX This Never Happens XXX */
5475 			tgt->state = TGT_STATE_LOADED;
5476 			break;
5477 		default:
5478 			mpt_prt(mpt, "Unknown Target State 0x%x in Context "
5479 			    "Reply Function\n", tgt->state);
5480 		}
5481 		return (TRUE);
5482 	}
5483 
5484 	status = le16toh(reply_frame->IOCStatus);
5485 	if (status != MPI_IOCSTATUS_SUCCESS) {
5486 		dbg = MPT_PRT_ERROR;
5487 	} else {
5488 		dbg = MPT_PRT_DEBUG1;
5489 	}
5490 
5491 	mpt_lprt(mpt, dbg,
5492 	    "SCSI_TGT REPLY: req=%p:%u reply=%p func=%x IOCstatus 0x%x\n",
5493 	     req, req->serno, reply_frame, reply_frame->Function, status);
5494 
5495 	switch (reply_frame->Function) {
5496 	case MPI_FUNCTION_TARGET_CMD_BUFFER_POST:
5497 	{
5498 		mpt_tgt_state_t *tgt;
5499 #ifdef	INVARIANTS
5500 		mpt_req_spcl(mpt, req, "tgt reply BUFFER POST", __LINE__);
5501 #endif
5502 		if (status != MPI_IOCSTATUS_SUCCESS) {
5503 			/*
5504 			 * XXX What to do?
5505 			 */
5506 			break;
5507 		}
5508 		tgt = MPT_TGT_STATE(mpt, req);
5509 		KASSERT(tgt->state == TGT_STATE_LOADING,
5510 		    ("bad state 0x%x on reply to buffer post\n", tgt->state));
5511 		mpt_assign_serno(mpt, req);
5512 		tgt->state = TGT_STATE_LOADED;
5513 		break;
5514 	}
5515 	case MPI_FUNCTION_TARGET_ASSIST:
5516 #ifdef	INVARIANTS
5517 		mpt_req_not_spcl(mpt, req, "tgt reply TARGET ASSIST", __LINE__);
5518 #endif
5519 		mpt_prt(mpt, "target assist completion\n");
5520 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5521 		mpt_free_request(mpt, req);
5522 		break;
5523 	case MPI_FUNCTION_TARGET_STATUS_SEND:
5524 #ifdef	INVARIANTS
5525 		mpt_req_not_spcl(mpt, req, "tgt reply STATUS SEND", __LINE__);
5526 #endif
5527 		mpt_prt(mpt, "status send completion\n");
5528 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5529 		mpt_free_request(mpt, req);
5530 		break;
5531 	case MPI_FUNCTION_TARGET_MODE_ABORT:
5532 	{
5533 		PTR_MSG_TARGET_MODE_ABORT_REPLY abtrp =
5534 		    (PTR_MSG_TARGET_MODE_ABORT_REPLY) reply_frame;
5535 		PTR_MSG_TARGET_MODE_ABORT abtp =
5536 		    (PTR_MSG_TARGET_MODE_ABORT) req->req_vbuf;
5537 		uint32_t cc = GET_IO_INDEX(le32toh(abtp->ReplyWord));
5538 #ifdef	INVARIANTS
5539 		mpt_req_not_spcl(mpt, req, "tgt reply TMODE ABORT", __LINE__);
5540 #endif
5541 		mpt_prt(mpt, "ABORT RX_ID 0x%x Complete; status 0x%x cnt %u\n",
5542 		    cc, le16toh(abtrp->IOCStatus), le32toh(abtrp->AbortCount));
5543 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
5544 		mpt_free_request(mpt, req);
5545 		break;
5546 	}
5547 	default:
5548 		mpt_prt(mpt, "Unknown Target Address Reply Function code: "
5549 		    "0x%x\n", reply_frame->Function);
5550 		break;
5551 	}
5552 	return (TRUE);
5553 }
5554