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