xref: /freebsd/sys/dev/mpt/mpt.c (revision aa0a1e58)
1 /*-
2  * Generic routines for LSI Fusion 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  *
62  * Support from LSI-Logic has also gone a great deal toward making this a
63  * workable subsystem and is gratefully acknowledged.
64  */
65 /*-
66  * Copyright (c) 2004, Avid Technology, Inc. and its contributors.
67  * Copyright (c) 2005, WHEEL Sp. z o.o.
68  * Copyright (c) 2004, 2005 Justin T. Gibbs
69  * All rights reserved.
70  *
71  * Redistribution and use in source and binary forms, with or without
72  * modification, are permitted provided that the following conditions are
73  * met:
74  * 1. Redistributions of source code must retain the above copyright
75  *    notice, this list of conditions and the following disclaimer.
76  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
77  *    substantially similar to the "NO WARRANTY" disclaimer below
78  *    ("Disclaimer") and any redistribution must be conditioned upon including
79  *    a substantially similar Disclaimer requirement for further binary
80  *    redistribution.
81  * 3. Neither the names of the above listed copyright holders nor the names
82  *    of any contributors may be used to endorse or promote products derived
83  *    from this software without specific prior written permission.
84  *
85  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
86  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
88  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
89  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
90  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
91  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
92  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
93  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
94  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE COPYRIGHT
95  * OWNER OR CONTRIBUTOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
96  */
97 
98 #include <sys/cdefs.h>
99 __FBSDID("$FreeBSD$");
100 
101 #include <dev/mpt/mpt.h>
102 #include <dev/mpt/mpt_cam.h> /* XXX For static handler registration */
103 #include <dev/mpt/mpt_raid.h> /* XXX For static handler registration */
104 
105 #include <dev/mpt/mpilib/mpi.h>
106 #include <dev/mpt/mpilib/mpi_ioc.h>
107 #include <dev/mpt/mpilib/mpi_fc.h>
108 #include <dev/mpt/mpilib/mpi_targ.h>
109 
110 #include <sys/sysctl.h>
111 
112 #define MPT_MAX_TRYS 3
113 #define MPT_MAX_WAIT 300000
114 
115 static int maxwait_ack = 0;
116 static int maxwait_int = 0;
117 static int maxwait_state = 0;
118 
119 static TAILQ_HEAD(, mpt_softc)	mpt_tailq = TAILQ_HEAD_INITIALIZER(mpt_tailq);
120 mpt_reply_handler_t *mpt_reply_handlers[MPT_NUM_REPLY_HANDLERS];
121 
122 static mpt_reply_handler_t mpt_default_reply_handler;
123 static mpt_reply_handler_t mpt_config_reply_handler;
124 static mpt_reply_handler_t mpt_handshake_reply_handler;
125 static mpt_reply_handler_t mpt_event_reply_handler;
126 static void mpt_send_event_ack(struct mpt_softc *mpt, request_t *ack_req,
127 			       MSG_EVENT_NOTIFY_REPLY *msg, uint32_t context);
128 static int mpt_send_event_request(struct mpt_softc *mpt, int onoff);
129 static int mpt_soft_reset(struct mpt_softc *mpt);
130 static void mpt_hard_reset(struct mpt_softc *mpt);
131 static int mpt_dma_buf_alloc(struct mpt_softc *mpt);
132 static void mpt_dma_buf_free(struct mpt_softc *mpt);
133 static int mpt_configure_ioc(struct mpt_softc *mpt, int, int);
134 static int mpt_enable_ioc(struct mpt_softc *mpt, int);
135 
136 /************************* Personality Module Support *************************/
137 /*
138  * We include one extra entry that is guaranteed to be NULL
139  * to simplify our itterator.
140  */
141 static struct mpt_personality *mpt_personalities[MPT_MAX_PERSONALITIES + 1];
142 static __inline struct mpt_personality*
143 	mpt_pers_find(struct mpt_softc *, u_int);
144 static __inline struct mpt_personality*
145 	mpt_pers_find_reverse(struct mpt_softc *, u_int);
146 
147 static __inline struct mpt_personality *
148 mpt_pers_find(struct mpt_softc *mpt, u_int start_at)
149 {
150 	KASSERT(start_at <= MPT_MAX_PERSONALITIES,
151 		("mpt_pers_find: starting position out of range\n"));
152 
153 	while (start_at < MPT_MAX_PERSONALITIES
154 	    && (mpt->mpt_pers_mask & (0x1 << start_at)) == 0) {
155 		start_at++;
156 	}
157 	return (mpt_personalities[start_at]);
158 }
159 
160 /*
161  * Used infrequently, so no need to optimize like a forward
162  * traversal where we use the MAX+1 is guaranteed to be NULL
163  * trick.
164  */
165 static __inline struct mpt_personality *
166 mpt_pers_find_reverse(struct mpt_softc *mpt, u_int start_at)
167 {
168 	while (start_at < MPT_MAX_PERSONALITIES
169 	    && (mpt->mpt_pers_mask & (0x1 << start_at)) == 0) {
170 		start_at--;
171 	}
172 	if (start_at < MPT_MAX_PERSONALITIES)
173 		return (mpt_personalities[start_at]);
174 	return (NULL);
175 }
176 
177 #define MPT_PERS_FOREACH(mpt, pers)				\
178 	for (pers = mpt_pers_find(mpt, /*start_at*/0);		\
179 	     pers != NULL;					\
180 	     pers = mpt_pers_find(mpt, /*start_at*/pers->id+1))
181 
182 #define MPT_PERS_FOREACH_REVERSE(mpt, pers)				\
183 	for (pers = mpt_pers_find_reverse(mpt, MPT_MAX_PERSONALITIES-1);\
184 	     pers != NULL;						\
185 	     pers = mpt_pers_find_reverse(mpt, /*start_at*/pers->id-1))
186 
187 static mpt_load_handler_t      mpt_stdload;
188 static mpt_probe_handler_t     mpt_stdprobe;
189 static mpt_attach_handler_t    mpt_stdattach;
190 static mpt_enable_handler_t    mpt_stdenable;
191 static mpt_ready_handler_t     mpt_stdready;
192 static mpt_event_handler_t     mpt_stdevent;
193 static mpt_reset_handler_t     mpt_stdreset;
194 static mpt_shutdown_handler_t  mpt_stdshutdown;
195 static mpt_detach_handler_t    mpt_stddetach;
196 static mpt_unload_handler_t    mpt_stdunload;
197 static struct mpt_personality mpt_default_personality =
198 {
199 	.load		= mpt_stdload,
200 	.probe		= mpt_stdprobe,
201 	.attach		= mpt_stdattach,
202 	.enable		= mpt_stdenable,
203 	.ready		= mpt_stdready,
204 	.event		= mpt_stdevent,
205 	.reset		= mpt_stdreset,
206 	.shutdown	= mpt_stdshutdown,
207 	.detach		= mpt_stddetach,
208 	.unload		= mpt_stdunload
209 };
210 
211 static mpt_load_handler_t      mpt_core_load;
212 static mpt_attach_handler_t    mpt_core_attach;
213 static mpt_enable_handler_t    mpt_core_enable;
214 static mpt_reset_handler_t     mpt_core_ioc_reset;
215 static mpt_event_handler_t     mpt_core_event;
216 static mpt_shutdown_handler_t  mpt_core_shutdown;
217 static mpt_shutdown_handler_t  mpt_core_detach;
218 static mpt_unload_handler_t    mpt_core_unload;
219 static struct mpt_personality mpt_core_personality =
220 {
221 	.name		= "mpt_core",
222 	.load		= mpt_core_load,
223 //	.attach		= mpt_core_attach,
224 //	.enable		= mpt_core_enable,
225 	.event		= mpt_core_event,
226 	.reset		= mpt_core_ioc_reset,
227 	.shutdown	= mpt_core_shutdown,
228 	.detach		= mpt_core_detach,
229 	.unload		= mpt_core_unload,
230 };
231 
232 /*
233  * Manual declaration so that DECLARE_MPT_PERSONALITY doesn't need
234  * ordering information.  We want the core to always register FIRST.
235  * other modules are set to SI_ORDER_SECOND.
236  */
237 static moduledata_t mpt_core_mod = {
238 	"mpt_core", mpt_modevent, &mpt_core_personality
239 };
240 DECLARE_MODULE(mpt_core, mpt_core_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
241 MODULE_VERSION(mpt_core, 1);
242 
243 #define MPT_PERS_ATTACHED(pers, mpt) ((mpt)->mpt_pers_mask & (0x1 << pers->id))
244 
245 int
246 mpt_modevent(module_t mod, int type, void *data)
247 {
248 	struct mpt_personality *pers;
249 	int error;
250 
251 	pers = (struct mpt_personality *)data;
252 
253 	error = 0;
254 	switch (type) {
255 	case MOD_LOAD:
256 	{
257 		mpt_load_handler_t **def_handler;
258 		mpt_load_handler_t **pers_handler;
259 		int i;
260 
261 		for (i = 0; i < MPT_MAX_PERSONALITIES; i++) {
262 			if (mpt_personalities[i] == NULL)
263 				break;
264 		}
265 		if (i >= MPT_MAX_PERSONALITIES) {
266 			error = ENOMEM;
267 			break;
268 		}
269 		pers->id = i;
270 		mpt_personalities[i] = pers;
271 
272 		/* Install standard/noop handlers for any NULL entries. */
273 		def_handler = MPT_PERS_FIRST_HANDLER(&mpt_default_personality);
274 		pers_handler = MPT_PERS_FIRST_HANDLER(pers);
275 		while (pers_handler <= MPT_PERS_LAST_HANDLER(pers)) {
276 			if (*pers_handler == NULL)
277 				*pers_handler = *def_handler;
278 			pers_handler++;
279 			def_handler++;
280 		}
281 
282 		error = (pers->load(pers));
283 		if (error != 0)
284 			mpt_personalities[i] = NULL;
285 		break;
286 	}
287 	case MOD_SHUTDOWN:
288 		break;
289 #if __FreeBSD_version >= 500000
290 	case MOD_QUIESCE:
291 		break;
292 #endif
293 	case MOD_UNLOAD:
294 		error = pers->unload(pers);
295 		mpt_personalities[pers->id] = NULL;
296 		break;
297 	default:
298 		error = EINVAL;
299 		break;
300 	}
301 	return (error);
302 }
303 
304 int
305 mpt_stdload(struct mpt_personality *pers)
306 {
307 	/* Load is always successfull. */
308 	return (0);
309 }
310 
311 int
312 mpt_stdprobe(struct mpt_softc *mpt)
313 {
314 	/* Probe is always successfull. */
315 	return (0);
316 }
317 
318 int
319 mpt_stdattach(struct mpt_softc *mpt)
320 {
321 	/* Attach is always successfull. */
322 	return (0);
323 }
324 
325 int
326 mpt_stdenable(struct mpt_softc *mpt)
327 {
328 	/* Enable is always successfull. */
329 	return (0);
330 }
331 
332 void
333 mpt_stdready(struct mpt_softc *mpt)
334 {
335 }
336 
337 
338 int
339 mpt_stdevent(struct mpt_softc *mpt, request_t *req, MSG_EVENT_NOTIFY_REPLY *msg)
340 {
341 	mpt_lprt(mpt, MPT_PRT_DEBUG, "mpt_stdevent: 0x%x\n", msg->Event & 0xFF);
342 	/* Event was not for us. */
343 	return (0);
344 }
345 
346 void
347 mpt_stdreset(struct mpt_softc *mpt, int type)
348 {
349 }
350 
351 void
352 mpt_stdshutdown(struct mpt_softc *mpt)
353 {
354 }
355 
356 void
357 mpt_stddetach(struct mpt_softc *mpt)
358 {
359 }
360 
361 int
362 mpt_stdunload(struct mpt_personality *pers)
363 {
364 	/* Unload is always successfull. */
365 	return (0);
366 }
367 
368 /*
369  * Post driver attachment, we may want to perform some global actions.
370  * Here is the hook to do so.
371  */
372 
373 static void
374 mpt_postattach(void *unused)
375 {
376 	struct mpt_softc *mpt;
377 	struct mpt_personality *pers;
378 
379 	TAILQ_FOREACH(mpt, &mpt_tailq, links) {
380 		MPT_PERS_FOREACH(mpt, pers)
381 			pers->ready(mpt);
382 	}
383 }
384 SYSINIT(mptdev, SI_SUB_CONFIGURE, SI_ORDER_MIDDLE, mpt_postattach, NULL);
385 
386 
387 /******************************* Bus DMA Support ******************************/
388 void
389 mpt_map_rquest(void *arg, bus_dma_segment_t *segs, int nseg, int error)
390 {
391 	struct mpt_map_info *map_info;
392 
393 	map_info = (struct mpt_map_info *)arg;
394 	map_info->error = error;
395 	map_info->phys = segs->ds_addr;
396 }
397 
398 /**************************** Reply/Event Handling ****************************/
399 int
400 mpt_register_handler(struct mpt_softc *mpt, mpt_handler_type type,
401 		     mpt_handler_t handler, uint32_t *phandler_id)
402 {
403 
404 	switch (type) {
405 	case MPT_HANDLER_REPLY:
406 	{
407 		u_int cbi;
408 		u_int free_cbi;
409 
410 		if (phandler_id == NULL)
411 			return (EINVAL);
412 
413 		free_cbi = MPT_HANDLER_ID_NONE;
414 		for (cbi = 0; cbi < MPT_NUM_REPLY_HANDLERS; cbi++) {
415 			/*
416 			 * If the same handler is registered multiple
417 			 * times, don't error out.  Just return the
418 			 * index of the original registration.
419 			 */
420 			if (mpt_reply_handlers[cbi] == handler.reply_handler) {
421 				*phandler_id = MPT_CBI_TO_HID(cbi);
422 				return (0);
423 			}
424 
425 			/*
426 			 * Fill from the front in the hope that
427 			 * all registered handlers consume only a
428 			 * single cache line.
429 			 *
430 			 * We don't break on the first empty slot so
431 			 * that the full table is checked to see if
432 			 * this handler was previously registered.
433 			 */
434 			if (free_cbi == MPT_HANDLER_ID_NONE &&
435 			    (mpt_reply_handlers[cbi]
436 			  == mpt_default_reply_handler))
437 				free_cbi = cbi;
438 		}
439 		if (free_cbi == MPT_HANDLER_ID_NONE) {
440 			return (ENOMEM);
441 		}
442 		mpt_reply_handlers[free_cbi] = handler.reply_handler;
443 		*phandler_id = MPT_CBI_TO_HID(free_cbi);
444 		break;
445 	}
446 	default:
447 		mpt_prt(mpt, "mpt_register_handler unknown type %d\n", type);
448 		return (EINVAL);
449 	}
450 	return (0);
451 }
452 
453 int
454 mpt_deregister_handler(struct mpt_softc *mpt, mpt_handler_type type,
455 		       mpt_handler_t handler, uint32_t handler_id)
456 {
457 
458 	switch (type) {
459 	case MPT_HANDLER_REPLY:
460 	{
461 		u_int cbi;
462 
463 		cbi = MPT_CBI(handler_id);
464 		if (cbi >= MPT_NUM_REPLY_HANDLERS
465 		 || mpt_reply_handlers[cbi] != handler.reply_handler)
466 			return (ENOENT);
467 		mpt_reply_handlers[cbi] = mpt_default_reply_handler;
468 		break;
469 	}
470 	default:
471 		mpt_prt(mpt, "mpt_deregister_handler unknown type %d\n", type);
472 		return (EINVAL);
473 	}
474 	return (0);
475 }
476 
477 static int
478 mpt_default_reply_handler(struct mpt_softc *mpt, request_t *req,
479 	uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
480 {
481 	mpt_prt(mpt,
482 	    "Default Handler Called: req=%p:%u reply_descriptor=%x frame=%p\n",
483 	    req, req->serno, reply_desc, reply_frame);
484 
485 	if (reply_frame != NULL)
486 		mpt_dump_reply_frame(mpt, reply_frame);
487 
488 	mpt_prt(mpt, "Reply Frame Ignored\n");
489 
490 	return (/*free_reply*/TRUE);
491 }
492 
493 static int
494 mpt_config_reply_handler(struct mpt_softc *mpt, request_t *req,
495  uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
496 {
497 	if (req != NULL) {
498 
499 		if (reply_frame != NULL) {
500 			MSG_CONFIG *cfgp;
501 			MSG_CONFIG_REPLY *reply;
502 
503 			cfgp = (MSG_CONFIG *)req->req_vbuf;
504 			reply = (MSG_CONFIG_REPLY *)reply_frame;
505 			req->IOCStatus = le16toh(reply_frame->IOCStatus);
506 			bcopy(&reply->Header, &cfgp->Header,
507 			      sizeof(cfgp->Header));
508 			cfgp->ExtPageLength = reply->ExtPageLength;
509 			cfgp->ExtPageType = reply->ExtPageType;
510 		}
511 		req->state &= ~REQ_STATE_QUEUED;
512 		req->state |= REQ_STATE_DONE;
513 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
514 		if ((req->state & REQ_STATE_NEED_WAKEUP) != 0) {
515 			wakeup(req);
516 		} else if ((req->state & REQ_STATE_TIMEDOUT) != 0) {
517 			/*
518 			 * Whew- we can free this request (late completion)
519 			 */
520 			mpt_free_request(mpt, req);
521 		}
522 	}
523 
524 	return (TRUE);
525 }
526 
527 static int
528 mpt_handshake_reply_handler(struct mpt_softc *mpt, request_t *req,
529  uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
530 {
531 	/* Nothing to be done. */
532 	return (TRUE);
533 }
534 
535 static int
536 mpt_event_reply_handler(struct mpt_softc *mpt, request_t *req,
537     uint32_t reply_desc, MSG_DEFAULT_REPLY *reply_frame)
538 {
539 	int free_reply;
540 
541 	KASSERT(reply_frame != NULL, ("null reply in mpt_event_reply_handler"));
542 	KASSERT(req != NULL, ("null request in mpt_event_reply_handler"));
543 
544 	free_reply = TRUE;
545 	switch (reply_frame->Function) {
546 	case MPI_FUNCTION_EVENT_NOTIFICATION:
547 	{
548 		MSG_EVENT_NOTIFY_REPLY *msg;
549 		struct mpt_personality *pers;
550 		u_int handled;
551 
552 		handled = 0;
553 		msg = (MSG_EVENT_NOTIFY_REPLY *)reply_frame;
554 		msg->EventDataLength = le16toh(msg->EventDataLength);
555 		msg->IOCStatus = le16toh(msg->IOCStatus);
556 		msg->IOCLogInfo = le32toh(msg->IOCLogInfo);
557 		msg->Event = le32toh(msg->Event);
558 		MPT_PERS_FOREACH(mpt, pers)
559 			handled += pers->event(mpt, req, msg);
560 
561 		if (handled == 0 && mpt->mpt_pers_mask == 0) {
562 			mpt_lprt(mpt, MPT_PRT_INFO,
563 				"No Handlers For Any Event Notify Frames. "
564 				"Event %#x (ACK %sequired).\n",
565 				msg->Event, msg->AckRequired? "r" : "not r");
566 		} else if (handled == 0) {
567 			mpt_lprt(mpt,
568 				msg->AckRequired? MPT_PRT_WARN : MPT_PRT_INFO,
569 				"Unhandled Event Notify Frame. Event %#x "
570 				"(ACK %sequired).\n",
571 				msg->Event, msg->AckRequired? "r" : "not r");
572 		}
573 
574 		if (msg->AckRequired) {
575 			request_t *ack_req;
576 			uint32_t context;
577 
578 			context = req->index | MPT_REPLY_HANDLER_EVENTS;
579 			ack_req = mpt_get_request(mpt, FALSE);
580 			if (ack_req == NULL) {
581 				struct mpt_evtf_record *evtf;
582 
583 				evtf = (struct mpt_evtf_record *)reply_frame;
584 				evtf->context = context;
585 				LIST_INSERT_HEAD(&mpt->ack_frames, evtf, links);
586 				free_reply = FALSE;
587 				break;
588 			}
589 			mpt_send_event_ack(mpt, ack_req, msg, context);
590 			/*
591 			 * Don't check for CONTINUATION_REPLY here
592 			 */
593 			return (free_reply);
594 		}
595 		break;
596 	}
597 	case MPI_FUNCTION_PORT_ENABLE:
598 		mpt_lprt(mpt, MPT_PRT_DEBUG , "enable port reply\n");
599 		break;
600 	case MPI_FUNCTION_EVENT_ACK:
601 		break;
602 	default:
603 		mpt_prt(mpt, "unknown event function: %x\n",
604 			reply_frame->Function);
605 		break;
606 	}
607 
608 	/*
609 	 * I'm not sure that this continuation stuff works as it should.
610 	 *
611 	 * I've had FC async events occur that free the frame up because
612 	 * the continuation bit isn't set, and then additional async events
613 	 * then occur using the same context. As you might imagine, this
614 	 * leads to Very Bad Thing.
615 	 *
616 	 *  Let's just be safe for now and not free them up until we figure
617 	 * out what's actually happening here.
618 	 */
619 #if	0
620 	if ((reply_frame->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY) == 0) {
621 		TAILQ_REMOVE(&mpt->request_pending_list, req, links);
622 		mpt_free_request(mpt, req);
623 		mpt_prt(mpt, "event_reply %x for req %p:%u NOT a continuation",
624 		    reply_frame->Function, req, req->serno);
625 		if (reply_frame->Function == MPI_FUNCTION_EVENT_NOTIFICATION) {
626 			MSG_EVENT_NOTIFY_REPLY *msg =
627 			    (MSG_EVENT_NOTIFY_REPLY *)reply_frame;
628 			mpt_prtc(mpt, " Event=0x%x AckReq=%d",
629 			    msg->Event, msg->AckRequired);
630 		}
631 	} else {
632 		mpt_prt(mpt, "event_reply %x for %p:%u IS a continuation",
633 		    reply_frame->Function, req, req->serno);
634 		if (reply_frame->Function == MPI_FUNCTION_EVENT_NOTIFICATION) {
635 			MSG_EVENT_NOTIFY_REPLY *msg =
636 			    (MSG_EVENT_NOTIFY_REPLY *)reply_frame;
637 			mpt_prtc(mpt, " Event=0x%x AckReq=%d",
638 			    msg->Event, msg->AckRequired);
639 		}
640 		mpt_prtc(mpt, "\n");
641 	}
642 #endif
643 	return (free_reply);
644 }
645 
646 /*
647  * Process an asynchronous event from the IOC.
648  */
649 static int
650 mpt_core_event(struct mpt_softc *mpt, request_t *req,
651 	       MSG_EVENT_NOTIFY_REPLY *msg)
652 {
653 	mpt_lprt(mpt, MPT_PRT_DEBUG, "mpt_core_event: 0x%x\n",
654                  msg->Event & 0xFF);
655 	switch(msg->Event & 0xFF) {
656 	case MPI_EVENT_NONE:
657 		break;
658 	case MPI_EVENT_LOG_DATA:
659 	{
660 		int i;
661 
662 		/* Some error occured that LSI wants logged */
663 		mpt_prt(mpt, "EvtLogData: IOCLogInfo: 0x%08x\n",
664 			msg->IOCLogInfo);
665 		mpt_prt(mpt, "\tEvtLogData: Event Data:");
666 		for (i = 0; i < msg->EventDataLength; i++)
667 			mpt_prtc(mpt, "  %08x", msg->Data[i]);
668 		mpt_prtc(mpt, "\n");
669 		break;
670 	}
671 	case MPI_EVENT_EVENT_CHANGE:
672 		/*
673 		 * This is just an acknowledgement
674 		 * of our mpt_send_event_request.
675 		 */
676 		break;
677 	case MPI_EVENT_SAS_DEVICE_STATUS_CHANGE:
678 		break;
679 	default:
680 		return (0);
681 		break;
682 	}
683 	return (1);
684 }
685 
686 static void
687 mpt_send_event_ack(struct mpt_softc *mpt, request_t *ack_req,
688 		   MSG_EVENT_NOTIFY_REPLY *msg, uint32_t context)
689 {
690 	MSG_EVENT_ACK *ackp;
691 
692 	ackp = (MSG_EVENT_ACK *)ack_req->req_vbuf;
693 	memset(ackp, 0, sizeof (*ackp));
694 	ackp->Function = MPI_FUNCTION_EVENT_ACK;
695 	ackp->Event = htole32(msg->Event);
696 	ackp->EventContext = htole32(msg->EventContext);
697 	ackp->MsgContext = htole32(context);
698 	mpt_check_doorbell(mpt);
699 	mpt_send_cmd(mpt, ack_req);
700 }
701 
702 /***************************** Interrupt Handling *****************************/
703 void
704 mpt_intr(void *arg)
705 {
706 	struct mpt_softc *mpt;
707 	uint32_t reply_desc;
708 	int ntrips = 0;
709 
710 	mpt = (struct mpt_softc *)arg;
711 	mpt_lprt(mpt, MPT_PRT_DEBUG2, "enter mpt_intr\n");
712 	MPT_LOCK_ASSERT(mpt);
713 
714 	while ((reply_desc = mpt_pop_reply_queue(mpt)) != MPT_REPLY_EMPTY) {
715 		request_t	  *req;
716 		MSG_DEFAULT_REPLY *reply_frame;
717 		uint32_t	   reply_baddr;
718 		uint32_t           ctxt_idx;
719 		u_int		   cb_index;
720 		u_int		   req_index;
721 		u_int		   offset;
722 		int		   free_rf;
723 
724 		req = NULL;
725 		reply_frame = NULL;
726 		reply_baddr = 0;
727 		offset = 0;
728 		if ((reply_desc & MPI_ADDRESS_REPLY_A_BIT) != 0) {
729 			/*
730 			 * Ensure that the reply frame is coherent.
731 			 */
732 			reply_baddr = MPT_REPLY_BADDR(reply_desc);
733 			offset = reply_baddr - (mpt->reply_phys & 0xFFFFFFFF);
734 			bus_dmamap_sync_range(mpt->reply_dmat,
735 			    mpt->reply_dmap, offset, MPT_REPLY_SIZE,
736 			    BUS_DMASYNC_POSTREAD);
737 			reply_frame = MPT_REPLY_OTOV(mpt, offset);
738 			ctxt_idx = le32toh(reply_frame->MsgContext);
739 		} else {
740 			uint32_t type;
741 
742 			type = MPI_GET_CONTEXT_REPLY_TYPE(reply_desc);
743 			ctxt_idx = reply_desc;
744 			mpt_lprt(mpt, MPT_PRT_DEBUG1, "Context Reply: 0x%08x\n",
745 				    reply_desc);
746 
747 			switch (type) {
748 			case MPI_CONTEXT_REPLY_TYPE_SCSI_INIT:
749 				ctxt_idx &= MPI_CONTEXT_REPLY_CONTEXT_MASK;
750 				break;
751 			case MPI_CONTEXT_REPLY_TYPE_SCSI_TARGET:
752 				ctxt_idx = GET_IO_INDEX(reply_desc);
753 				if (mpt->tgt_cmd_ptrs == NULL) {
754 					mpt_prt(mpt,
755 					    "mpt_intr: no target cmd ptrs\n");
756 					reply_desc = MPT_REPLY_EMPTY;
757 					break;
758 				}
759 				if (ctxt_idx >= mpt->tgt_cmds_allocated) {
760 					mpt_prt(mpt,
761 					    "mpt_intr: bad tgt cmd ctxt %u\n",
762 					    ctxt_idx);
763 					reply_desc = MPT_REPLY_EMPTY;
764 					ntrips = 1000;
765 					break;
766 				}
767 				req = mpt->tgt_cmd_ptrs[ctxt_idx];
768 				if (req == NULL) {
769 					mpt_prt(mpt, "no request backpointer "
770 					    "at index %u", ctxt_idx);
771 					reply_desc = MPT_REPLY_EMPTY;
772 					ntrips = 1000;
773 					break;
774 				}
775 				/*
776 				 * Reformulate ctxt_idx to be just as if
777 				 * it were another type of context reply
778 				 * so the code below will find the request
779 				 * via indexing into the pool.
780 				 */
781 				ctxt_idx =
782 				    req->index | mpt->scsi_tgt_handler_id;
783 				req = NULL;
784 				break;
785 			case MPI_CONTEXT_REPLY_TYPE_LAN:
786 				mpt_prt(mpt, "LAN CONTEXT REPLY: 0x%08x\n",
787 				    reply_desc);
788 				reply_desc = MPT_REPLY_EMPTY;
789 				break;
790 			default:
791 				mpt_prt(mpt, "Context Reply 0x%08x?\n", type);
792 				reply_desc = MPT_REPLY_EMPTY;
793 				break;
794 			}
795 			if (reply_desc == MPT_REPLY_EMPTY) {
796 				if (ntrips++ > 1000) {
797 					break;
798 				}
799 				continue;
800 			}
801 		}
802 
803 		cb_index = MPT_CONTEXT_TO_CBI(ctxt_idx);
804 		req_index = MPT_CONTEXT_TO_REQI(ctxt_idx);
805 		if (req_index < MPT_MAX_REQUESTS(mpt)) {
806 			req = &mpt->request_pool[req_index];
807 		} else {
808 			mpt_prt(mpt, "WARN: mpt_intr index == %d (reply_desc =="
809 			    " 0x%x)\n", req_index, reply_desc);
810 		}
811 
812 		bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
813 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
814 		free_rf = mpt_reply_handlers[cb_index](mpt, req,
815 		    reply_desc, reply_frame);
816 
817 		if (reply_frame != NULL && free_rf) {
818 			bus_dmamap_sync_range(mpt->reply_dmat,
819 			    mpt->reply_dmap, offset, MPT_REPLY_SIZE,
820 			    BUS_DMASYNC_PREREAD);
821 			mpt_free_reply(mpt, reply_baddr);
822 		}
823 
824 		/*
825 		 * If we got ourselves disabled, don't get stuck in a loop
826 		 */
827 		if (mpt->disabled) {
828 			mpt_disable_ints(mpt);
829 			break;
830 		}
831 		if (ntrips++ > 1000) {
832 			break;
833 		}
834 	}
835 	mpt_lprt(mpt, MPT_PRT_DEBUG2, "exit mpt_intr\n");
836 }
837 
838 /******************************* Error Recovery *******************************/
839 void
840 mpt_complete_request_chain(struct mpt_softc *mpt, struct req_queue *chain,
841 			    u_int iocstatus)
842 {
843 	MSG_DEFAULT_REPLY  ioc_status_frame;
844 	request_t	  *req;
845 
846 	memset(&ioc_status_frame, 0, sizeof(ioc_status_frame));
847 	ioc_status_frame.MsgLength = roundup2(sizeof(ioc_status_frame), 4);
848 	ioc_status_frame.IOCStatus = iocstatus;
849 	while((req = TAILQ_FIRST(chain)) != NULL) {
850 		MSG_REQUEST_HEADER *msg_hdr;
851 		u_int		    cb_index;
852 
853 		bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
854 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
855 		msg_hdr = (MSG_REQUEST_HEADER *)req->req_vbuf;
856 		ioc_status_frame.Function = msg_hdr->Function;
857 		ioc_status_frame.MsgContext = msg_hdr->MsgContext;
858 		cb_index = MPT_CONTEXT_TO_CBI(le32toh(msg_hdr->MsgContext));
859 		mpt_reply_handlers[cb_index](mpt, req, msg_hdr->MsgContext,
860 		    &ioc_status_frame);
861 		if (mpt_req_on_pending_list(mpt, req) != 0)
862 			TAILQ_REMOVE(chain, req, links);
863 	}
864 }
865 
866 /********************************* Diagnostics ********************************/
867 /*
868  * Perform a diagnostic dump of a reply frame.
869  */
870 void
871 mpt_dump_reply_frame(struct mpt_softc *mpt, MSG_DEFAULT_REPLY *reply_frame)
872 {
873 	mpt_prt(mpt, "Address Reply:\n");
874 	mpt_print_reply(reply_frame);
875 }
876 
877 /******************************* Doorbell Access ******************************/
878 static __inline uint32_t mpt_rd_db(struct mpt_softc *mpt);
879 static __inline  uint32_t mpt_rd_intr(struct mpt_softc *mpt);
880 
881 static __inline uint32_t
882 mpt_rd_db(struct mpt_softc *mpt)
883 {
884 	return mpt_read(mpt, MPT_OFFSET_DOORBELL);
885 }
886 
887 static __inline uint32_t
888 mpt_rd_intr(struct mpt_softc *mpt)
889 {
890 	return mpt_read(mpt, MPT_OFFSET_INTR_STATUS);
891 }
892 
893 /* Busy wait for a door bell to be read by IOC */
894 static int
895 mpt_wait_db_ack(struct mpt_softc *mpt)
896 {
897 	int i;
898 	for (i=0; i < MPT_MAX_WAIT; i++) {
899 		if (!MPT_DB_IS_BUSY(mpt_rd_intr(mpt))) {
900 			maxwait_ack = i > maxwait_ack ? i : maxwait_ack;
901 			return (MPT_OK);
902 		}
903 		DELAY(200);
904 	}
905 	return (MPT_FAIL);
906 }
907 
908 /* Busy wait for a door bell interrupt */
909 static int
910 mpt_wait_db_int(struct mpt_softc *mpt)
911 {
912 	int i;
913 	for (i = 0; i < MPT_MAX_WAIT; i++) {
914 		if (MPT_DB_INTR(mpt_rd_intr(mpt))) {
915 			maxwait_int = i > maxwait_int ? i : maxwait_int;
916 			return MPT_OK;
917 		}
918 		DELAY(100);
919 	}
920 	return (MPT_FAIL);
921 }
922 
923 /* Wait for IOC to transition to a give state */
924 void
925 mpt_check_doorbell(struct mpt_softc *mpt)
926 {
927 	uint32_t db = mpt_rd_db(mpt);
928 	if (MPT_STATE(db) != MPT_DB_STATE_RUNNING) {
929 		mpt_prt(mpt, "Device not running\n");
930 		mpt_print_db(db);
931 	}
932 }
933 
934 /* Wait for IOC to transition to a give state */
935 static int
936 mpt_wait_state(struct mpt_softc *mpt, enum DB_STATE_BITS state)
937 {
938 	int i;
939 
940 	for (i = 0; i < MPT_MAX_WAIT; i++) {
941 		uint32_t db = mpt_rd_db(mpt);
942 		if (MPT_STATE(db) == state) {
943 			maxwait_state = i > maxwait_state ? i : maxwait_state;
944 			return (MPT_OK);
945 		}
946 		DELAY(100);
947 	}
948 	return (MPT_FAIL);
949 }
950 
951 
952 /************************* Intialization/Configuration ************************/
953 static int mpt_download_fw(struct mpt_softc *mpt);
954 
955 /* Issue the reset COMMAND to the IOC */
956 static int
957 mpt_soft_reset(struct mpt_softc *mpt)
958 {
959 	mpt_lprt(mpt, MPT_PRT_DEBUG, "soft reset\n");
960 
961 	/* Have to use hard reset if we are not in Running state */
962 	if (MPT_STATE(mpt_rd_db(mpt)) != MPT_DB_STATE_RUNNING) {
963 		mpt_prt(mpt, "soft reset failed: device not running\n");
964 		return (MPT_FAIL);
965 	}
966 
967 	/* If door bell is in use we don't have a chance of getting
968 	 * a word in since the IOC probably crashed in message
969 	 * processing. So don't waste our time.
970 	 */
971 	if (MPT_DB_IS_IN_USE(mpt_rd_db(mpt))) {
972 		mpt_prt(mpt, "soft reset failed: doorbell wedged\n");
973 		return (MPT_FAIL);
974 	}
975 
976 	/* Send the reset request to the IOC */
977 	mpt_write(mpt, MPT_OFFSET_DOORBELL,
978 	    MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET << MPI_DOORBELL_FUNCTION_SHIFT);
979 	if (mpt_wait_db_ack(mpt) != MPT_OK) {
980 		mpt_prt(mpt, "soft reset failed: ack timeout\n");
981 		return (MPT_FAIL);
982 	}
983 
984 	/* Wait for the IOC to reload and come out of reset state */
985 	if (mpt_wait_state(mpt, MPT_DB_STATE_READY) != MPT_OK) {
986 		mpt_prt(mpt, "soft reset failed: device did not restart\n");
987 		return (MPT_FAIL);
988 	}
989 
990 	return MPT_OK;
991 }
992 
993 static int
994 mpt_enable_diag_mode(struct mpt_softc *mpt)
995 {
996 	int try;
997 
998 	try = 20;
999 	while (--try) {
1000 
1001 		if ((mpt_read(mpt, MPT_OFFSET_DIAGNOSTIC) & MPI_DIAG_DRWE) != 0)
1002 			break;
1003 
1004 		/* Enable diagnostic registers */
1005 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, 0xFF);
1006 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, MPI_WRSEQ_1ST_KEY_VALUE);
1007 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, MPI_WRSEQ_2ND_KEY_VALUE);
1008 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, MPI_WRSEQ_3RD_KEY_VALUE);
1009 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, MPI_WRSEQ_4TH_KEY_VALUE);
1010 		mpt_write(mpt, MPT_OFFSET_SEQUENCE, MPI_WRSEQ_5TH_KEY_VALUE);
1011 
1012 		DELAY(100000);
1013 	}
1014 	if (try == 0)
1015 		return (EIO);
1016 	return (0);
1017 }
1018 
1019 static void
1020 mpt_disable_diag_mode(struct mpt_softc *mpt)
1021 {
1022 	mpt_write(mpt, MPT_OFFSET_SEQUENCE, 0xFFFFFFFF);
1023 }
1024 
1025 /* This is a magic diagnostic reset that resets all the ARM
1026  * processors in the chip.
1027  */
1028 static void
1029 mpt_hard_reset(struct mpt_softc *mpt)
1030 {
1031 	int error;
1032 	int wait;
1033 	uint32_t diagreg;
1034 
1035 	mpt_lprt(mpt, MPT_PRT_DEBUG, "hard reset\n");
1036 
1037 	error = mpt_enable_diag_mode(mpt);
1038 	if (error) {
1039 		mpt_prt(mpt, "WARNING - Could not enter diagnostic mode !\n");
1040 		mpt_prt(mpt, "Trying to reset anyway.\n");
1041 	}
1042 
1043 	diagreg = mpt_read(mpt, MPT_OFFSET_DIAGNOSTIC);
1044 
1045 	/*
1046 	 * This appears to be a workaround required for some
1047 	 * firmware or hardware revs.
1048 	 */
1049 	mpt_write(mpt, MPT_OFFSET_DIAGNOSTIC, diagreg | MPI_DIAG_DISABLE_ARM);
1050 	DELAY(1000);
1051 
1052 	/* Diag. port is now active so we can now hit the reset bit */
1053 	mpt_write(mpt, MPT_OFFSET_DIAGNOSTIC, diagreg | MPI_DIAG_RESET_ADAPTER);
1054 
1055         /*
1056          * Ensure that the reset has finished.  We delay 1ms
1057          * prior to reading the register to make sure the chip
1058          * has sufficiently completed its reset to handle register
1059          * accesses.
1060          */
1061 	wait = 5000;
1062 	do {
1063 		DELAY(1000);
1064 		diagreg = mpt_read(mpt, MPT_OFFSET_DIAGNOSTIC);
1065 	} while (--wait && (diagreg & MPI_DIAG_RESET_ADAPTER) == 0);
1066 
1067 	if (wait == 0) {
1068 		mpt_prt(mpt, "WARNING - Failed hard reset! "
1069 			"Trying to initialize anyway.\n");
1070 	}
1071 
1072 	/*
1073 	 * If we have firmware to download, it must be loaded before
1074 	 * the controller will become operational.  Do so now.
1075 	 */
1076 	if (mpt->fw_image != NULL) {
1077 
1078 		error = mpt_download_fw(mpt);
1079 
1080 		if (error) {
1081 			mpt_prt(mpt, "WARNING - Firmware Download Failed!\n");
1082 			mpt_prt(mpt, "Trying to initialize anyway.\n");
1083 		}
1084 	}
1085 
1086 	/*
1087 	 * Reseting the controller should have disabled write
1088 	 * access to the diagnostic registers, but disable
1089 	 * manually to be sure.
1090 	 */
1091 	mpt_disable_diag_mode(mpt);
1092 }
1093 
1094 static void
1095 mpt_core_ioc_reset(struct mpt_softc *mpt, int type)
1096 {
1097 	/*
1098 	 * Complete all pending requests with a status
1099 	 * appropriate for an IOC reset.
1100 	 */
1101 	mpt_complete_request_chain(mpt, &mpt->request_pending_list,
1102 				   MPI_IOCSTATUS_INVALID_STATE);
1103 }
1104 
1105 
1106 /*
1107  * Reset the IOC when needed. Try software command first then if needed
1108  * poke at the magic diagnostic reset. Note that a hard reset resets
1109  * *both* IOCs on dual function chips (FC929 && LSI1030) as well as
1110  * fouls up the PCI configuration registers.
1111  */
1112 int
1113 mpt_reset(struct mpt_softc *mpt, int reinit)
1114 {
1115 	struct	mpt_personality *pers;
1116 	int	ret;
1117 	int	retry_cnt = 0;
1118 
1119 	/*
1120 	 * Try a soft reset. If that fails, get out the big hammer.
1121 	 */
1122  again:
1123 	if ((ret = mpt_soft_reset(mpt)) != MPT_OK) {
1124 		int	cnt;
1125 		for (cnt = 0; cnt < 5; cnt++) {
1126 			/* Failed; do a hard reset */
1127 			mpt_hard_reset(mpt);
1128 
1129 			/*
1130 			 * Wait for the IOC to reload
1131 			 * and come out of reset state
1132 			 */
1133 			ret = mpt_wait_state(mpt, MPT_DB_STATE_READY);
1134 			if (ret == MPT_OK) {
1135 				break;
1136 			}
1137 			/*
1138 			 * Okay- try to check again...
1139 			 */
1140 			ret = mpt_wait_state(mpt, MPT_DB_STATE_READY);
1141 			if (ret == MPT_OK) {
1142 				break;
1143 			}
1144 			mpt_prt(mpt, "mpt_reset: failed hard reset (%d:%d)\n",
1145 			    retry_cnt, cnt);
1146 		}
1147 	}
1148 
1149 	if (retry_cnt == 0) {
1150 		/*
1151 		 * Invoke reset handlers.  We bump the reset count so
1152 		 * that mpt_wait_req() understands that regardless of
1153 		 * the specified wait condition, it should stop its wait.
1154 		 */
1155 		mpt->reset_cnt++;
1156 		MPT_PERS_FOREACH(mpt, pers)
1157 			pers->reset(mpt, ret);
1158 	}
1159 
1160 	if (reinit) {
1161 		ret = mpt_enable_ioc(mpt, 1);
1162 		if (ret == MPT_OK) {
1163 			mpt_enable_ints(mpt);
1164 		}
1165 	}
1166 	if (ret != MPT_OK && retry_cnt++ < 2) {
1167 		goto again;
1168 	}
1169 	return ret;
1170 }
1171 
1172 /* Return a command buffer to the free queue */
1173 void
1174 mpt_free_request(struct mpt_softc *mpt, request_t *req)
1175 {
1176 	request_t *nxt;
1177 	struct mpt_evtf_record *record;
1178 	uint32_t offset, reply_baddr;
1179 
1180 	if (req == NULL || req != &mpt->request_pool[req->index]) {
1181 		panic("mpt_free_request bad req ptr\n");
1182 		return;
1183 	}
1184 	if ((nxt = req->chain) != NULL) {
1185 		req->chain = NULL;
1186 		mpt_free_request(mpt, nxt);	/* NB: recursion */
1187 	}
1188 	KASSERT(req->state != REQ_STATE_FREE, ("freeing free request"));
1189 	KASSERT(!(req->state & REQ_STATE_LOCKED), ("freeing locked request"));
1190 	MPT_LOCK_ASSERT(mpt);
1191 	KASSERT(mpt_req_on_free_list(mpt, req) == 0,
1192 	    ("mpt_free_request: req %p:%u func %x already on freelist",
1193 	    req, req->serno, ((MSG_REQUEST_HEADER *)req->req_vbuf)->Function));
1194 	KASSERT(mpt_req_on_pending_list(mpt, req) == 0,
1195 	    ("mpt_free_request: req %p:%u func %x on pending list",
1196 	    req, req->serno, ((MSG_REQUEST_HEADER *)req->req_vbuf)->Function));
1197 #ifdef	INVARIANTS
1198 	mpt_req_not_spcl(mpt, req, "mpt_free_request", __LINE__);
1199 #endif
1200 
1201 	req->ccb = NULL;
1202 	if (LIST_EMPTY(&mpt->ack_frames)) {
1203 		/*
1204 		 * Insert free ones at the tail
1205 		 */
1206 		req->serno = 0;
1207 		req->state = REQ_STATE_FREE;
1208 #ifdef	INVARIANTS
1209 		memset(req->req_vbuf, 0xff, sizeof (MSG_REQUEST_HEADER));
1210 #endif
1211 		TAILQ_INSERT_TAIL(&mpt->request_free_list, req, links);
1212 		if (mpt->getreqwaiter != 0) {
1213 			mpt->getreqwaiter = 0;
1214 			wakeup(&mpt->request_free_list);
1215 		}
1216 		return;
1217 	}
1218 
1219 	/*
1220 	 * Process an ack frame deferred due to resource shortage.
1221 	 */
1222 	record = LIST_FIRST(&mpt->ack_frames);
1223 	LIST_REMOVE(record, links);
1224 	req->state = REQ_STATE_ALLOCATED;
1225 	mpt_assign_serno(mpt, req);
1226 	mpt_send_event_ack(mpt, req, &record->reply, record->context);
1227 	offset = (uint32_t)((uint8_t *)record - mpt->reply);
1228 	reply_baddr = offset + (mpt->reply_phys & 0xFFFFFFFF);
1229 	bus_dmamap_sync_range(mpt->reply_dmat, mpt->reply_dmap, offset,
1230 	    MPT_REPLY_SIZE, BUS_DMASYNC_PREREAD);
1231 	mpt_free_reply(mpt, reply_baddr);
1232 }
1233 
1234 /* Get a command buffer from the free queue */
1235 request_t *
1236 mpt_get_request(struct mpt_softc *mpt, int sleep_ok)
1237 {
1238 	request_t *req;
1239 
1240 retry:
1241 	MPT_LOCK_ASSERT(mpt);
1242 	req = TAILQ_FIRST(&mpt->request_free_list);
1243 	if (req != NULL) {
1244 		KASSERT(req == &mpt->request_pool[req->index],
1245 		    ("mpt_get_request: corrupted request free list\n"));
1246 		KASSERT(req->state == REQ_STATE_FREE,
1247 		    ("req %p:%u not free on free list %x index %d function %x",
1248 		    req, req->serno, req->state, req->index,
1249 		    ((MSG_REQUEST_HEADER *)req->req_vbuf)->Function));
1250 		TAILQ_REMOVE(&mpt->request_free_list, req, links);
1251 		req->state = REQ_STATE_ALLOCATED;
1252 		req->chain = NULL;
1253 		mpt_assign_serno(mpt, req);
1254 	} else if (sleep_ok != 0) {
1255 		mpt->getreqwaiter = 1;
1256 		mpt_sleep(mpt, &mpt->request_free_list, PUSER, "mptgreq", 0);
1257 		goto retry;
1258 	}
1259 	return (req);
1260 }
1261 
1262 /* Pass the command to the IOC */
1263 void
1264 mpt_send_cmd(struct mpt_softc *mpt, request_t *req)
1265 {
1266 	if (mpt->verbose > MPT_PRT_DEBUG2) {
1267 		mpt_dump_request(mpt, req);
1268 	}
1269 	bus_dmamap_sync(mpt->request_dmat, mpt->request_dmap,
1270 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1271 	req->state |= REQ_STATE_QUEUED;
1272 	KASSERT(mpt_req_on_free_list(mpt, req) == 0,
1273 	    ("req %p:%u func %x on freelist list in mpt_send_cmd",
1274 	    req, req->serno, ((MSG_REQUEST_HEADER *)req->req_vbuf)->Function));
1275 	KASSERT(mpt_req_on_pending_list(mpt, req) == 0,
1276 	    ("req %p:%u func %x already on pending list in mpt_send_cmd",
1277 	    req, req->serno, ((MSG_REQUEST_HEADER *)req->req_vbuf)->Function));
1278 	TAILQ_INSERT_HEAD(&mpt->request_pending_list, req, links);
1279 	mpt_write(mpt, MPT_OFFSET_REQUEST_Q, (uint32_t) req->req_pbuf);
1280 }
1281 
1282 /*
1283  * Wait for a request to complete.
1284  *
1285  * Inputs:
1286  *	mpt		softc of controller executing request
1287  *	req		request to wait for
1288  *	sleep_ok	nonzero implies may sleep in this context
1289  *	time_ms		timeout in ms.  0 implies no timeout.
1290  *
1291  * Return Values:
1292  *	0		Request completed
1293  *	non-0		Timeout fired before request completion.
1294  */
1295 int
1296 mpt_wait_req(struct mpt_softc *mpt, request_t *req,
1297 	     mpt_req_state_t state, mpt_req_state_t mask,
1298 	     int sleep_ok, int time_ms)
1299 {
1300 	int   error;
1301 	int   timeout;
1302 	u_int saved_cnt;
1303 
1304 	/*
1305 	 * timeout is in ms.  0 indicates infinite wait.
1306 	 * Convert to ticks or 500us units depending on
1307 	 * our sleep mode.
1308 	 */
1309 	if (sleep_ok != 0) {
1310 		timeout = (time_ms * hz) / 1000;
1311 	} else {
1312 		timeout = time_ms * 2;
1313 	}
1314 	req->state |= REQ_STATE_NEED_WAKEUP;
1315 	mask &= ~REQ_STATE_NEED_WAKEUP;
1316 	saved_cnt = mpt->reset_cnt;
1317 	while ((req->state & mask) != state && mpt->reset_cnt == saved_cnt) {
1318 		if (sleep_ok != 0) {
1319 			error = mpt_sleep(mpt, req, PUSER, "mptreq", timeout);
1320 			if (error == EWOULDBLOCK) {
1321 				timeout = 0;
1322 				break;
1323 			}
1324 		} else {
1325 			if (time_ms != 0 && --timeout == 0) {
1326 				break;
1327 			}
1328 			DELAY(500);
1329 			mpt_intr(mpt);
1330 		}
1331 	}
1332 	req->state &= ~REQ_STATE_NEED_WAKEUP;
1333 	if (mpt->reset_cnt != saved_cnt) {
1334 		return (EIO);
1335 	}
1336 	if (time_ms && timeout <= 0) {
1337 		MSG_REQUEST_HEADER *msg_hdr = req->req_vbuf;
1338 		req->state |= REQ_STATE_TIMEDOUT;
1339 		mpt_prt(mpt, "mpt_wait_req(%x) timed out\n", msg_hdr->Function);
1340 		return (ETIMEDOUT);
1341 	}
1342 	return (0);
1343 }
1344 
1345 /*
1346  * Send a command to the IOC via the handshake register.
1347  *
1348  * Only done at initialization time and for certain unusual
1349  * commands such as device/bus reset as specified by LSI.
1350  */
1351 int
1352 mpt_send_handshake_cmd(struct mpt_softc *mpt, size_t len, void *cmd)
1353 {
1354 	int i;
1355 	uint32_t data, *data32;
1356 
1357 	/* Check condition of the IOC */
1358 	data = mpt_rd_db(mpt);
1359 	if ((MPT_STATE(data) != MPT_DB_STATE_READY
1360 	  && MPT_STATE(data) != MPT_DB_STATE_RUNNING
1361 	  && MPT_STATE(data) != MPT_DB_STATE_FAULT)
1362 	 || MPT_DB_IS_IN_USE(data)) {
1363 		mpt_prt(mpt, "handshake aborted - invalid doorbell state\n");
1364 		mpt_print_db(data);
1365 		return (EBUSY);
1366 	}
1367 
1368 	/* We move things in 32 bit chunks */
1369 	len = (len + 3) >> 2;
1370 	data32 = cmd;
1371 
1372 	/* Clear any left over pending doorbell interrupts */
1373 	if (MPT_DB_INTR(mpt_rd_intr(mpt)))
1374 		mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1375 
1376 	/*
1377 	 * Tell the handshake reg. we are going to send a command
1378          * and how long it is going to be.
1379 	 */
1380 	data = (MPI_FUNCTION_HANDSHAKE << MPI_DOORBELL_FUNCTION_SHIFT) |
1381 	    (len << MPI_DOORBELL_ADD_DWORDS_SHIFT);
1382 	mpt_write(mpt, MPT_OFFSET_DOORBELL, data);
1383 
1384 	/* Wait for the chip to notice */
1385 	if (mpt_wait_db_int(mpt) != MPT_OK) {
1386 		mpt_prt(mpt, "mpt_send_handshake_cmd: db ignored\n");
1387 		return (ETIMEDOUT);
1388 	}
1389 
1390 	/* Clear the interrupt */
1391 	mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1392 
1393 	if (mpt_wait_db_ack(mpt) != MPT_OK) {
1394 		mpt_prt(mpt, "mpt_send_handshake_cmd: db ack timed out\n");
1395 		return (ETIMEDOUT);
1396 	}
1397 
1398 	/* Send the command */
1399 	for (i = 0; i < len; i++) {
1400 		mpt_write(mpt, MPT_OFFSET_DOORBELL, htole32(*data32++));
1401 		if (mpt_wait_db_ack(mpt) != MPT_OK) {
1402 			mpt_prt(mpt,
1403 			    "mpt_send_handshake_cmd: timeout @ index %d\n", i);
1404 			return (ETIMEDOUT);
1405 		}
1406 	}
1407 	return MPT_OK;
1408 }
1409 
1410 /* Get the response from the handshake register */
1411 int
1412 mpt_recv_handshake_reply(struct mpt_softc *mpt, size_t reply_len, void *reply)
1413 {
1414 	int left, reply_left;
1415 	u_int16_t *data16;
1416 	uint32_t data;
1417 	MSG_DEFAULT_REPLY *hdr;
1418 
1419 	/* We move things out in 16 bit chunks */
1420 	reply_len >>= 1;
1421 	data16 = (u_int16_t *)reply;
1422 
1423 	hdr = (MSG_DEFAULT_REPLY *)reply;
1424 
1425 	/* Get first word */
1426 	if (mpt_wait_db_int(mpt) != MPT_OK) {
1427 		mpt_prt(mpt, "mpt_recv_handshake_cmd timeout1\n");
1428 		return ETIMEDOUT;
1429 	}
1430 	data = mpt_read(mpt, MPT_OFFSET_DOORBELL);
1431 	*data16++ = le16toh(data & MPT_DB_DATA_MASK);
1432 	mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1433 
1434 	/* Get Second Word */
1435 	if (mpt_wait_db_int(mpt) != MPT_OK) {
1436 		mpt_prt(mpt, "mpt_recv_handshake_cmd timeout2\n");
1437 		return ETIMEDOUT;
1438 	}
1439 	data = mpt_read(mpt, MPT_OFFSET_DOORBELL);
1440 	*data16++ = le16toh(data & MPT_DB_DATA_MASK);
1441 	mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1442 
1443 	/*
1444 	 * With the second word, we can now look at the length.
1445 	 * Warn about a reply that's too short (except for IOC FACTS REPLY)
1446 	 */
1447 	if ((reply_len >> 1) != hdr->MsgLength &&
1448 	    (hdr->Function != MPI_FUNCTION_IOC_FACTS)){
1449 #if __FreeBSD_version >= 500000
1450 		mpt_prt(mpt, "reply length does not match message length: "
1451 			"got %x; expected %zx for function %x\n",
1452 			hdr->MsgLength << 2, reply_len << 1, hdr->Function);
1453 #else
1454 		mpt_prt(mpt, "reply length does not match message length: "
1455 			"got %x; expected %x for function %x\n",
1456 			hdr->MsgLength << 2, reply_len << 1, hdr->Function);
1457 #endif
1458 	}
1459 
1460 	/* Get rest of the reply; but don't overflow the provided buffer */
1461 	left = (hdr->MsgLength << 1) - 2;
1462 	reply_left =  reply_len - 2;
1463 	while (left--) {
1464 		u_int16_t datum;
1465 
1466 		if (mpt_wait_db_int(mpt) != MPT_OK) {
1467 			mpt_prt(mpt, "mpt_recv_handshake_cmd timeout3\n");
1468 			return ETIMEDOUT;
1469 		}
1470 		data = mpt_read(mpt, MPT_OFFSET_DOORBELL);
1471 		datum = le16toh(data & MPT_DB_DATA_MASK);
1472 
1473 		if (reply_left-- > 0)
1474 			*data16++ = datum;
1475 
1476 		mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1477 	}
1478 
1479 	/* One more wait & clear at the end */
1480 	if (mpt_wait_db_int(mpt) != MPT_OK) {
1481 		mpt_prt(mpt, "mpt_recv_handshake_cmd timeout4\n");
1482 		return ETIMEDOUT;
1483 	}
1484 	mpt_write(mpt, MPT_OFFSET_INTR_STATUS, 0);
1485 
1486 	if ((hdr->IOCStatus & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
1487 		if (mpt->verbose >= MPT_PRT_TRACE)
1488 			mpt_print_reply(hdr);
1489 		return (MPT_FAIL | hdr->IOCStatus);
1490 	}
1491 
1492 	return (0);
1493 }
1494 
1495 static int
1496 mpt_get_iocfacts(struct mpt_softc *mpt, MSG_IOC_FACTS_REPLY *freplp)
1497 {
1498 	MSG_IOC_FACTS f_req;
1499 	int error;
1500 
1501 	memset(&f_req, 0, sizeof f_req);
1502 	f_req.Function = MPI_FUNCTION_IOC_FACTS;
1503 	f_req.MsgContext = htole32(MPT_REPLY_HANDLER_HANDSHAKE);
1504 	error = mpt_send_handshake_cmd(mpt, sizeof f_req, &f_req);
1505 	if (error) {
1506 		return(error);
1507 	}
1508 	error = mpt_recv_handshake_reply(mpt, sizeof (*freplp), freplp);
1509 	return (error);
1510 }
1511 
1512 static int
1513 mpt_get_portfacts(struct mpt_softc *mpt, U8 port, MSG_PORT_FACTS_REPLY *freplp)
1514 {
1515 	MSG_PORT_FACTS f_req;
1516 	int error;
1517 
1518 	memset(&f_req, 0, sizeof f_req);
1519 	f_req.Function = MPI_FUNCTION_PORT_FACTS;
1520 	f_req.PortNumber = port;
1521 	f_req.MsgContext = htole32(MPT_REPLY_HANDLER_HANDSHAKE);
1522 	error = mpt_send_handshake_cmd(mpt, sizeof f_req, &f_req);
1523 	if (error) {
1524 		return(error);
1525 	}
1526 	error = mpt_recv_handshake_reply(mpt, sizeof (*freplp), freplp);
1527 	return (error);
1528 }
1529 
1530 /*
1531  * Send the initialization request. This is where we specify how many
1532  * SCSI busses and how many devices per bus we wish to emulate.
1533  * This is also the command that specifies the max size of the reply
1534  * frames from the IOC that we will be allocating.
1535  */
1536 static int
1537 mpt_send_ioc_init(struct mpt_softc *mpt, uint32_t who)
1538 {
1539 	int error = 0;
1540 	MSG_IOC_INIT init;
1541 	MSG_IOC_INIT_REPLY reply;
1542 
1543 	memset(&init, 0, sizeof init);
1544 	init.WhoInit = who;
1545 	init.Function = MPI_FUNCTION_IOC_INIT;
1546 	init.MaxDevices = 0;	/* at least 256 devices per bus */
1547 	init.MaxBuses = 16;	/* at least 16 busses */
1548 
1549 	init.MsgVersion = htole16(MPI_VERSION);
1550 	init.HeaderVersion = htole16(MPI_HEADER_VERSION);
1551 	init.ReplyFrameSize = htole16(MPT_REPLY_SIZE);
1552 	init.MsgContext = htole32(MPT_REPLY_HANDLER_HANDSHAKE);
1553 
1554 	if ((error = mpt_send_handshake_cmd(mpt, sizeof init, &init)) != 0) {
1555 		return(error);
1556 	}
1557 
1558 	error = mpt_recv_handshake_reply(mpt, sizeof reply, &reply);
1559 	return (error);
1560 }
1561 
1562 
1563 /*
1564  * Utiltity routine to read configuration headers and pages
1565  */
1566 int
1567 mpt_issue_cfg_req(struct mpt_softc *mpt, request_t *req, cfgparms_t *params,
1568 		  bus_addr_t addr, bus_size_t len, int sleep_ok, int timeout_ms)
1569 {
1570 	MSG_CONFIG *cfgp;
1571 	SGE_SIMPLE32 *se;
1572 
1573 	cfgp = req->req_vbuf;
1574 	memset(cfgp, 0, sizeof *cfgp);
1575 	cfgp->Action = params->Action;
1576 	cfgp->Function = MPI_FUNCTION_CONFIG;
1577 	cfgp->Header.PageVersion = params->PageVersion;
1578 	cfgp->Header.PageNumber = params->PageNumber;
1579 	cfgp->PageAddress = htole32(params->PageAddress);
1580 	if ((params->PageType & MPI_CONFIG_PAGETYPE_MASK) ==
1581 	    MPI_CONFIG_PAGETYPE_EXTENDED) {
1582 		cfgp->Header.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
1583 		cfgp->Header.PageLength = 0;
1584 		cfgp->ExtPageLength = htole16(params->ExtPageLength);
1585 		cfgp->ExtPageType = params->ExtPageType;
1586 	} else {
1587 		cfgp->Header.PageType = params->PageType;
1588 		cfgp->Header.PageLength = params->PageLength;
1589 	}
1590 	se = (SGE_SIMPLE32 *)&cfgp->PageBufferSGE;
1591 	se->Address = htole32(addr);
1592 	MPI_pSGE_SET_LENGTH(se, len);
1593 	MPI_pSGE_SET_FLAGS(se, (MPI_SGE_FLAGS_SIMPLE_ELEMENT |
1594 	    MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER |
1595 	    MPI_SGE_FLAGS_END_OF_LIST |
1596 	    ((params->Action == MPI_CONFIG_ACTION_PAGE_WRITE_CURRENT
1597 	  || params->Action == MPI_CONFIG_ACTION_PAGE_WRITE_NVRAM)
1598 	   ? MPI_SGE_FLAGS_HOST_TO_IOC : MPI_SGE_FLAGS_IOC_TO_HOST)));
1599 	se->FlagsLength = htole32(se->FlagsLength);
1600 	cfgp->MsgContext = htole32(req->index | MPT_REPLY_HANDLER_CONFIG);
1601 
1602 	mpt_check_doorbell(mpt);
1603 	mpt_send_cmd(mpt, req);
1604 	return (mpt_wait_req(mpt, req, REQ_STATE_DONE, REQ_STATE_DONE,
1605 			     sleep_ok, timeout_ms));
1606 }
1607 
1608 int
1609 mpt_read_extcfg_header(struct mpt_softc *mpt, int PageVersion, int PageNumber,
1610 		       uint32_t PageAddress, int ExtPageType,
1611 		       CONFIG_EXTENDED_PAGE_HEADER *rslt,
1612 		       int sleep_ok, int timeout_ms)
1613 {
1614 	request_t  *req;
1615 	cfgparms_t params;
1616 	MSG_CONFIG_REPLY *cfgp;
1617 	int	    error;
1618 
1619 	req = mpt_get_request(mpt, sleep_ok);
1620 	if (req == NULL) {
1621 		mpt_prt(mpt, "mpt_extread_cfg_header: Get request failed!\n");
1622 		return (ENOMEM);
1623 	}
1624 
1625 	params.Action = MPI_CONFIG_ACTION_PAGE_HEADER;
1626 	params.PageVersion = PageVersion;
1627 	params.PageLength = 0;
1628 	params.PageNumber = PageNumber;
1629 	params.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
1630 	params.PageAddress = PageAddress;
1631 	params.ExtPageType = ExtPageType;
1632 	params.ExtPageLength = 0;
1633 	error = mpt_issue_cfg_req(mpt, req, &params, /*addr*/0, /*len*/0,
1634 				  sleep_ok, timeout_ms);
1635 	if (error != 0) {
1636 		/*
1637 		 * Leave the request. Without resetting the chip, it's
1638 		 * still owned by it and we'll just get into trouble
1639 		 * freeing it now. Mark it as abandoned so that if it
1640 		 * shows up later it can be freed.
1641 		 */
1642 		mpt_prt(mpt, "read_extcfg_header timed out\n");
1643 		return (ETIMEDOUT);
1644 	}
1645 
1646         switch (req->IOCStatus & MPI_IOCSTATUS_MASK) {
1647 	case MPI_IOCSTATUS_SUCCESS:
1648 		cfgp = req->req_vbuf;
1649 		rslt->PageVersion = cfgp->Header.PageVersion;
1650 		rslt->PageNumber = cfgp->Header.PageNumber;
1651 		rslt->PageType = cfgp->Header.PageType;
1652 		rslt->ExtPageLength = le16toh(cfgp->ExtPageLength);
1653 		rslt->ExtPageType = cfgp->ExtPageType;
1654 		error = 0;
1655 		break;
1656 	case MPI_IOCSTATUS_CONFIG_INVALID_PAGE:
1657 		mpt_lprt(mpt, MPT_PRT_DEBUG,
1658 		    "Invalid Page Type %d Number %d Addr 0x%0x\n",
1659 		    MPI_CONFIG_PAGETYPE_EXTENDED, PageNumber, PageAddress);
1660 		error = EINVAL;
1661 		break;
1662 	default:
1663 		mpt_prt(mpt, "mpt_read_extcfg_header: Config Info Status %x\n",
1664 			req->IOCStatus);
1665 		error = EIO;
1666 		break;
1667 	}
1668 	mpt_free_request(mpt, req);
1669 	return (error);
1670 }
1671 
1672 int
1673 mpt_read_extcfg_page(struct mpt_softc *mpt, int Action, uint32_t PageAddress,
1674 		     CONFIG_EXTENDED_PAGE_HEADER *hdr, void *buf, size_t len,
1675 		     int sleep_ok, int timeout_ms)
1676 {
1677 	request_t    *req;
1678 	cfgparms_t    params;
1679 	int	      error;
1680 
1681 	req = mpt_get_request(mpt, sleep_ok);
1682 	if (req == NULL) {
1683 		mpt_prt(mpt, "mpt_read_extcfg_page: Get request failed!\n");
1684 		return (-1);
1685 	}
1686 
1687 	params.Action = Action;
1688 	params.PageVersion = hdr->PageVersion;
1689 	params.PageLength = 0;
1690 	params.PageNumber = hdr->PageNumber;
1691 	params.PageType = MPI_CONFIG_PAGETYPE_EXTENDED;
1692 	params.PageAddress = PageAddress;
1693 	params.ExtPageType = hdr->ExtPageType;
1694 	params.ExtPageLength = hdr->ExtPageLength;
1695 	error = mpt_issue_cfg_req(mpt, req, &params,
1696 				  req->req_pbuf + MPT_RQSL(mpt),
1697 				  len, sleep_ok, timeout_ms);
1698 	if (error != 0) {
1699 		mpt_prt(mpt, "read_extcfg_page(%d) timed out\n", Action);
1700 		return (-1);
1701 	}
1702 
1703 	if ((req->IOCStatus & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
1704 		mpt_prt(mpt, "mpt_read_extcfg_page: Config Info Status %x\n",
1705 			req->IOCStatus);
1706 		mpt_free_request(mpt, req);
1707 		return (-1);
1708 	}
1709 	memcpy(buf, ((uint8_t *)req->req_vbuf)+MPT_RQSL(mpt), len);
1710 	mpt_free_request(mpt, req);
1711 	return (0);
1712 }
1713 
1714 int
1715 mpt_read_cfg_header(struct mpt_softc *mpt, int PageType, int PageNumber,
1716 		    uint32_t PageAddress, CONFIG_PAGE_HEADER *rslt,
1717 		    int sleep_ok, int timeout_ms)
1718 {
1719 	request_t  *req;
1720 	cfgparms_t params;
1721 	MSG_CONFIG *cfgp;
1722 	int	    error;
1723 
1724 	req = mpt_get_request(mpt, sleep_ok);
1725 	if (req == NULL) {
1726 		mpt_prt(mpt, "mpt_read_cfg_header: Get request failed!\n");
1727 		return (ENOMEM);
1728 	}
1729 
1730 	params.Action = MPI_CONFIG_ACTION_PAGE_HEADER;
1731 	params.PageVersion = 0;
1732 	params.PageLength = 0;
1733 	params.PageNumber = PageNumber;
1734 	params.PageType = PageType;
1735 	params.PageAddress = PageAddress;
1736 	error = mpt_issue_cfg_req(mpt, req, &params, /*addr*/0, /*len*/0,
1737 				  sleep_ok, timeout_ms);
1738 	if (error != 0) {
1739 		/*
1740 		 * Leave the request. Without resetting the chip, it's
1741 		 * still owned by it and we'll just get into trouble
1742 		 * freeing it now. Mark it as abandoned so that if it
1743 		 * shows up later it can be freed.
1744 		 */
1745 		mpt_prt(mpt, "read_cfg_header timed out\n");
1746 		return (ETIMEDOUT);
1747 	}
1748 
1749         switch (req->IOCStatus & MPI_IOCSTATUS_MASK) {
1750 	case MPI_IOCSTATUS_SUCCESS:
1751 		cfgp = req->req_vbuf;
1752 		bcopy(&cfgp->Header, rslt, sizeof(*rslt));
1753 		error = 0;
1754 		break;
1755 	case MPI_IOCSTATUS_CONFIG_INVALID_PAGE:
1756 		mpt_lprt(mpt, MPT_PRT_DEBUG,
1757 		    "Invalid Page Type %d Number %d Addr 0x%0x\n",
1758 		    PageType, PageNumber, PageAddress);
1759 		error = EINVAL;
1760 		break;
1761 	default:
1762 		mpt_prt(mpt, "mpt_read_cfg_header: Config Info Status %x\n",
1763 			req->IOCStatus);
1764 		error = EIO;
1765 		break;
1766 	}
1767 	mpt_free_request(mpt, req);
1768 	return (error);
1769 }
1770 
1771 int
1772 mpt_read_cfg_page(struct mpt_softc *mpt, int Action, uint32_t PageAddress,
1773 		  CONFIG_PAGE_HEADER *hdr, size_t len, int sleep_ok,
1774 		  int timeout_ms)
1775 {
1776 	request_t    *req;
1777 	cfgparms_t    params;
1778 	int	      error;
1779 
1780 	req = mpt_get_request(mpt, sleep_ok);
1781 	if (req == NULL) {
1782 		mpt_prt(mpt, "mpt_read_cfg_page: Get request failed!\n");
1783 		return (-1);
1784 	}
1785 
1786 	params.Action = Action;
1787 	params.PageVersion = hdr->PageVersion;
1788 	params.PageLength = hdr->PageLength;
1789 	params.PageNumber = hdr->PageNumber;
1790 	params.PageType = hdr->PageType & MPI_CONFIG_PAGETYPE_MASK;
1791 	params.PageAddress = PageAddress;
1792 	error = mpt_issue_cfg_req(mpt, req, &params,
1793 				  req->req_pbuf + MPT_RQSL(mpt),
1794 				  len, sleep_ok, timeout_ms);
1795 	if (error != 0) {
1796 		mpt_prt(mpt, "read_cfg_page(%d) timed out\n", Action);
1797 		return (-1);
1798 	}
1799 
1800 	if ((req->IOCStatus & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
1801 		mpt_prt(mpt, "mpt_read_cfg_page: Config Info Status %x\n",
1802 			req->IOCStatus);
1803 		mpt_free_request(mpt, req);
1804 		return (-1);
1805 	}
1806 	memcpy(hdr, ((uint8_t *)req->req_vbuf)+MPT_RQSL(mpt), len);
1807 	mpt_free_request(mpt, req);
1808 	return (0);
1809 }
1810 
1811 int
1812 mpt_write_cfg_page(struct mpt_softc *mpt, int Action, uint32_t PageAddress,
1813 		   CONFIG_PAGE_HEADER *hdr, size_t len, int sleep_ok,
1814 		   int timeout_ms)
1815 {
1816 	request_t    *req;
1817 	cfgparms_t    params;
1818 	u_int	      hdr_attr;
1819 	int	      error;
1820 
1821 	hdr_attr = hdr->PageType & MPI_CONFIG_PAGEATTR_MASK;
1822 	if (hdr_attr != MPI_CONFIG_PAGEATTR_CHANGEABLE &&
1823 	    hdr_attr != MPI_CONFIG_PAGEATTR_PERSISTENT) {
1824 		mpt_prt(mpt, "page type 0x%x not changeable\n",
1825 			hdr->PageType & MPI_CONFIG_PAGETYPE_MASK);
1826 		return (-1);
1827 	}
1828 
1829 #if	0
1830 	/*
1831 	 * We shouldn't mask off other bits here.
1832 	 */
1833 	hdr->PageType &= MPI_CONFIG_PAGETYPE_MASK;
1834 #endif
1835 
1836 	req = mpt_get_request(mpt, sleep_ok);
1837 	if (req == NULL)
1838 		return (-1);
1839 
1840 	memcpy(((caddr_t)req->req_vbuf) + MPT_RQSL(mpt), hdr, len);
1841 
1842 	/*
1843 	 * There isn't any point in restoring stripped out attributes
1844 	 * if you then mask them going down to issue the request.
1845 	 */
1846 
1847 	params.Action = Action;
1848 	params.PageVersion = hdr->PageVersion;
1849 	params.PageLength = hdr->PageLength;
1850 	params.PageNumber = hdr->PageNumber;
1851 	params.PageAddress = PageAddress;
1852 #if	0
1853 	/* Restore stripped out attributes */
1854 	hdr->PageType |= hdr_attr;
1855 	params.PageType = hdr->PageType & MPI_CONFIG_PAGETYPE_MASK;
1856 #else
1857 	params.PageType = hdr->PageType;
1858 #endif
1859 	error = mpt_issue_cfg_req(mpt, req, &params,
1860 				  req->req_pbuf + MPT_RQSL(mpt),
1861 				  len, sleep_ok, timeout_ms);
1862 	if (error != 0) {
1863 		mpt_prt(mpt, "mpt_write_cfg_page timed out\n");
1864 		return (-1);
1865 	}
1866 
1867         if ((req->IOCStatus & MPI_IOCSTATUS_MASK) != MPI_IOCSTATUS_SUCCESS) {
1868 		mpt_prt(mpt, "mpt_write_cfg_page: Config Info Status %x\n",
1869 			req->IOCStatus);
1870 		mpt_free_request(mpt, req);
1871 		return (-1);
1872 	}
1873 	mpt_free_request(mpt, req);
1874 	return (0);
1875 }
1876 
1877 /*
1878  * Read IOC configuration information
1879  */
1880 static int
1881 mpt_read_config_info_ioc(struct mpt_softc *mpt)
1882 {
1883 	CONFIG_PAGE_HEADER hdr;
1884 	struct mpt_raid_volume *mpt_raid;
1885 	int rv;
1886 	int i;
1887 	size_t len;
1888 
1889 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_IOC,
1890 		2, 0, &hdr, FALSE, 5000);
1891 	/*
1892 	 * If it's an invalid page, so what? Not a supported function....
1893 	 */
1894 	if (rv == EINVAL) {
1895 		return (0);
1896 	}
1897 	if (rv) {
1898 		return (rv);
1899 	}
1900 
1901 	mpt_lprt(mpt, MPT_PRT_DEBUG,
1902 	    "IOC Page 2 Header: Version %x len %x PageNumber %x PageType %x\n",
1903 	    hdr.PageVersion, hdr.PageLength << 2,
1904 	    hdr.PageNumber, hdr.PageType);
1905 
1906 	len = hdr.PageLength * sizeof(uint32_t);
1907 	mpt->ioc_page2 = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
1908 	if (mpt->ioc_page2 == NULL) {
1909 		mpt_prt(mpt, "unable to allocate memory for IOC page 2\n");
1910 		mpt_raid_free_mem(mpt);
1911 		return (ENOMEM);
1912 	}
1913 	memcpy(&mpt->ioc_page2->Header, &hdr, sizeof(hdr));
1914 	rv = mpt_read_cur_cfg_page(mpt, 0,
1915 	    &mpt->ioc_page2->Header, len, FALSE, 5000);
1916 	if (rv) {
1917 		mpt_prt(mpt, "failed to read IOC Page 2\n");
1918 		mpt_raid_free_mem(mpt);
1919 		return (EIO);
1920 	}
1921 	mpt2host_config_page_ioc2(mpt->ioc_page2);
1922 
1923 	if (mpt->ioc_page2->CapabilitiesFlags != 0) {
1924 		uint32_t mask;
1925 
1926 		mpt_prt(mpt, "Capabilities: (");
1927 		for (mask = 1; mask != 0; mask <<= 1) {
1928 			if ((mpt->ioc_page2->CapabilitiesFlags & mask) == 0) {
1929 				continue;
1930 			}
1931 			switch (mask) {
1932 			case MPI_IOCPAGE2_CAP_FLAGS_IS_SUPPORT:
1933 				mpt_prtc(mpt, " RAID-0");
1934 				break;
1935 			case MPI_IOCPAGE2_CAP_FLAGS_IME_SUPPORT:
1936 				mpt_prtc(mpt, " RAID-1E");
1937 				break;
1938 			case MPI_IOCPAGE2_CAP_FLAGS_IM_SUPPORT:
1939 				mpt_prtc(mpt, " RAID-1");
1940 				break;
1941 			case MPI_IOCPAGE2_CAP_FLAGS_SES_SUPPORT:
1942 				mpt_prtc(mpt, " SES");
1943 				break;
1944 			case MPI_IOCPAGE2_CAP_FLAGS_SAFTE_SUPPORT:
1945 				mpt_prtc(mpt, " SAFTE");
1946 				break;
1947 			case MPI_IOCPAGE2_CAP_FLAGS_CROSS_CHANNEL_SUPPORT:
1948 				mpt_prtc(mpt, " Multi-Channel-Arrays");
1949 			default:
1950 				break;
1951 			}
1952 		}
1953 		mpt_prtc(mpt, " )\n");
1954 		if ((mpt->ioc_page2->CapabilitiesFlags
1955 		   & (MPI_IOCPAGE2_CAP_FLAGS_IS_SUPPORT
1956 		    | MPI_IOCPAGE2_CAP_FLAGS_IME_SUPPORT
1957 		    | MPI_IOCPAGE2_CAP_FLAGS_IM_SUPPORT)) != 0) {
1958 			mpt_prt(mpt, "%d Active Volume%s(%d Max)\n",
1959 				mpt->ioc_page2->NumActiveVolumes,
1960 				mpt->ioc_page2->NumActiveVolumes != 1
1961 			      ? "s " : " ",
1962 				mpt->ioc_page2->MaxVolumes);
1963 			mpt_prt(mpt, "%d Hidden Drive Member%s(%d Max)\n",
1964 				mpt->ioc_page2->NumActivePhysDisks,
1965 				mpt->ioc_page2->NumActivePhysDisks != 1
1966 			      ? "s " : " ",
1967 				mpt->ioc_page2->MaxPhysDisks);
1968 		}
1969 	}
1970 
1971 	len = mpt->ioc_page2->MaxVolumes * sizeof(struct mpt_raid_volume);
1972 	mpt->raid_volumes = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
1973 	if (mpt->raid_volumes == NULL) {
1974 		mpt_prt(mpt, "Could not allocate RAID volume data\n");
1975 		mpt_raid_free_mem(mpt);
1976 		return (ENOMEM);
1977 	}
1978 
1979 	/*
1980 	 * Copy critical data out of ioc_page2 so that we can
1981 	 * safely refresh the page without windows of unreliable
1982 	 * data.
1983 	 */
1984 	mpt->raid_max_volumes =  mpt->ioc_page2->MaxVolumes;
1985 
1986 	len = sizeof(*mpt->raid_volumes->config_page) +
1987 	    (sizeof (RAID_VOL0_PHYS_DISK) * (mpt->ioc_page2->MaxPhysDisks - 1));
1988 	for (i = 0; i < mpt->ioc_page2->MaxVolumes; i++) {
1989 		mpt_raid = &mpt->raid_volumes[i];
1990 		mpt_raid->config_page =
1991 		    malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
1992 		if (mpt_raid->config_page == NULL) {
1993 			mpt_prt(mpt, "Could not allocate RAID page data\n");
1994 			mpt_raid_free_mem(mpt);
1995 			return (ENOMEM);
1996 		}
1997 	}
1998 	mpt->raid_page0_len = len;
1999 
2000 	len = mpt->ioc_page2->MaxPhysDisks * sizeof(struct mpt_raid_disk);
2001 	mpt->raid_disks = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
2002 	if (mpt->raid_disks == NULL) {
2003 		mpt_prt(mpt, "Could not allocate RAID disk data\n");
2004 		mpt_raid_free_mem(mpt);
2005 		return (ENOMEM);
2006 	}
2007 	mpt->raid_max_disks =  mpt->ioc_page2->MaxPhysDisks;
2008 
2009 	/*
2010 	 * Load page 3.
2011 	 */
2012 	rv = mpt_read_cfg_header(mpt, MPI_CONFIG_PAGETYPE_IOC,
2013 	    3, 0, &hdr, FALSE, 5000);
2014 	if (rv) {
2015 		mpt_raid_free_mem(mpt);
2016 		return (EIO);
2017 	}
2018 
2019 	mpt_lprt(mpt, MPT_PRT_DEBUG, "IOC Page 3 Header: %x %x %x %x\n",
2020 	    hdr.PageVersion, hdr.PageLength, hdr.PageNumber, hdr.PageType);
2021 
2022 	len = hdr.PageLength * sizeof(uint32_t);
2023 	mpt->ioc_page3 = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
2024 	if (mpt->ioc_page3 == NULL) {
2025 		mpt_prt(mpt, "unable to allocate memory for IOC page 3\n");
2026 		mpt_raid_free_mem(mpt);
2027 		return (ENOMEM);
2028 	}
2029 	memcpy(&mpt->ioc_page3->Header, &hdr, sizeof(hdr));
2030 	rv = mpt_read_cur_cfg_page(mpt, 0,
2031 	    &mpt->ioc_page3->Header, len, FALSE, 5000);
2032 	if (rv) {
2033 		mpt_raid_free_mem(mpt);
2034 		return (EIO);
2035 	}
2036 	mpt2host_config_page_ioc3(mpt->ioc_page3);
2037 	mpt_raid_wakeup(mpt);
2038 	return (0);
2039 }
2040 
2041 /*
2042  * Enable IOC port
2043  */
2044 static int
2045 mpt_send_port_enable(struct mpt_softc *mpt, int port)
2046 {
2047 	request_t	*req;
2048 	MSG_PORT_ENABLE *enable_req;
2049 	int		 error;
2050 
2051 	req = mpt_get_request(mpt, /*sleep_ok*/FALSE);
2052 	if (req == NULL)
2053 		return (-1);
2054 
2055 	enable_req = req->req_vbuf;
2056 	memset(enable_req, 0,  MPT_RQSL(mpt));
2057 
2058 	enable_req->Function   = MPI_FUNCTION_PORT_ENABLE;
2059 	enable_req->MsgContext = htole32(req->index | MPT_REPLY_HANDLER_CONFIG);
2060 	enable_req->PortNumber = port;
2061 
2062 	mpt_check_doorbell(mpt);
2063 	mpt_lprt(mpt, MPT_PRT_DEBUG, "enabling port %d\n", port);
2064 
2065 	mpt_send_cmd(mpt, req);
2066 	error = mpt_wait_req(mpt, req, REQ_STATE_DONE, REQ_STATE_DONE,
2067 	    FALSE, (mpt->is_sas || mpt->is_fc)? 30000 : 3000);
2068 	if (error != 0) {
2069 		mpt_prt(mpt, "port %d enable timed out\n", port);
2070 		return (-1);
2071 	}
2072 	mpt_free_request(mpt, req);
2073 	mpt_lprt(mpt, MPT_PRT_DEBUG, "enabled port %d\n", port);
2074 	return (0);
2075 }
2076 
2077 /*
2078  * Enable/Disable asynchronous event reporting.
2079  */
2080 static int
2081 mpt_send_event_request(struct mpt_softc *mpt, int onoff)
2082 {
2083 	request_t *req;
2084 	MSG_EVENT_NOTIFY *enable_req;
2085 
2086 	req = mpt_get_request(mpt, FALSE);
2087 	if (req == NULL) {
2088 		return (ENOMEM);
2089 	}
2090 	enable_req = req->req_vbuf;
2091 	memset(enable_req, 0, sizeof *enable_req);
2092 
2093 	enable_req->Function   = MPI_FUNCTION_EVENT_NOTIFICATION;
2094 	enable_req->MsgContext = htole32(req->index | MPT_REPLY_HANDLER_EVENTS);
2095 	enable_req->Switch     = onoff;
2096 
2097 	mpt_check_doorbell(mpt);
2098 	mpt_lprt(mpt, MPT_PRT_DEBUG, "%sabling async events\n",
2099 	    onoff ? "en" : "dis");
2100 	/*
2101 	 * Send the command off, but don't wait for it.
2102 	 */
2103 	mpt_send_cmd(mpt, req);
2104 	return (0);
2105 }
2106 
2107 /*
2108  * Un-mask the interrupts on the chip.
2109  */
2110 void
2111 mpt_enable_ints(struct mpt_softc *mpt)
2112 {
2113 	/* Unmask every thing except door bell int */
2114 	mpt_write(mpt, MPT_OFFSET_INTR_MASK, MPT_INTR_DB_MASK);
2115 }
2116 
2117 /*
2118  * Mask the interrupts on the chip.
2119  */
2120 void
2121 mpt_disable_ints(struct mpt_softc *mpt)
2122 {
2123 	/* Mask all interrupts */
2124 	mpt_write(mpt, MPT_OFFSET_INTR_MASK,
2125 	    MPT_INTR_REPLY_MASK | MPT_INTR_DB_MASK);
2126 }
2127 
2128 static void
2129 mpt_sysctl_attach(struct mpt_softc *mpt)
2130 {
2131 #if __FreeBSD_version >= 500000
2132 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(mpt->dev);
2133 	struct sysctl_oid *tree = device_get_sysctl_tree(mpt->dev);
2134 
2135 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
2136 		       "debug", CTLFLAG_RW, &mpt->verbose, 0,
2137 		       "Debugging/Verbose level");
2138 	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
2139 		       "role", CTLFLAG_RD, &mpt->role, 0,
2140 		       "HBA role");
2141 #ifdef	MPT_TEST_MULTIPATH
2142 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
2143 		       "failure_id", CTLFLAG_RW, &mpt->failure_id, -1,
2144 		       "Next Target to Fail");
2145 #endif
2146 #endif
2147 }
2148 
2149 int
2150 mpt_attach(struct mpt_softc *mpt)
2151 {
2152 	struct mpt_personality *pers;
2153 	int i;
2154 	int error;
2155 
2156 	mpt_core_attach(mpt);
2157 	mpt_core_enable(mpt);
2158 
2159 	TAILQ_INSERT_TAIL(&mpt_tailq, mpt, links);
2160 	for (i = 0; i < MPT_MAX_PERSONALITIES; i++) {
2161 		pers = mpt_personalities[i];
2162 		if (pers == NULL) {
2163 			continue;
2164 		}
2165 		if (pers->probe(mpt) == 0) {
2166 			error = pers->attach(mpt);
2167 			if (error != 0) {
2168 				mpt_detach(mpt);
2169 				return (error);
2170 			}
2171 			mpt->mpt_pers_mask |= (0x1 << pers->id);
2172 			pers->use_count++;
2173 		}
2174 	}
2175 
2176 	/*
2177 	 * Now that we've attached everything, do the enable function
2178 	 * for all of the personalities. This allows the personalities
2179 	 * to do setups that are appropriate for them prior to enabling
2180 	 * any ports.
2181 	 */
2182 	for (i = 0; i < MPT_MAX_PERSONALITIES; i++) {
2183 		pers = mpt_personalities[i];
2184 		if (pers != NULL  && MPT_PERS_ATTACHED(pers, mpt) != 0) {
2185 			error = pers->enable(mpt);
2186 			if (error != 0) {
2187 				mpt_prt(mpt, "personality %s attached but would"
2188 				    " not enable (%d)\n", pers->name, error);
2189 				mpt_detach(mpt);
2190 				return (error);
2191 			}
2192 		}
2193 	}
2194 	return (0);
2195 }
2196 
2197 int
2198 mpt_shutdown(struct mpt_softc *mpt)
2199 {
2200 	struct mpt_personality *pers;
2201 
2202 	MPT_PERS_FOREACH_REVERSE(mpt, pers) {
2203 		pers->shutdown(mpt);
2204 	}
2205 	return (0);
2206 }
2207 
2208 int
2209 mpt_detach(struct mpt_softc *mpt)
2210 {
2211 	struct mpt_personality *pers;
2212 
2213 	MPT_PERS_FOREACH_REVERSE(mpt, pers) {
2214 		pers->detach(mpt);
2215 		mpt->mpt_pers_mask &= ~(0x1 << pers->id);
2216 		pers->use_count--;
2217 	}
2218 	TAILQ_REMOVE(&mpt_tailq, mpt, links);
2219 	return (0);
2220 }
2221 
2222 int
2223 mpt_core_load(struct mpt_personality *pers)
2224 {
2225 	int i;
2226 
2227 	/*
2228 	 * Setup core handlers and insert the default handler
2229 	 * into all "empty slots".
2230 	 */
2231 	for (i = 0; i < MPT_NUM_REPLY_HANDLERS; i++) {
2232 		mpt_reply_handlers[i] = mpt_default_reply_handler;
2233 	}
2234 
2235 	mpt_reply_handlers[MPT_CBI(MPT_REPLY_HANDLER_EVENTS)] =
2236 	    mpt_event_reply_handler;
2237 	mpt_reply_handlers[MPT_CBI(MPT_REPLY_HANDLER_CONFIG)] =
2238 	    mpt_config_reply_handler;
2239 	mpt_reply_handlers[MPT_CBI(MPT_REPLY_HANDLER_HANDSHAKE)] =
2240 	    mpt_handshake_reply_handler;
2241 	return (0);
2242 }
2243 
2244 /*
2245  * Initialize per-instance driver data and perform
2246  * initial controller configuration.
2247  */
2248 int
2249 mpt_core_attach(struct mpt_softc *mpt)
2250 {
2251         int val, error;
2252 
2253 	LIST_INIT(&mpt->ack_frames);
2254 	/* Put all request buffers on the free list */
2255 	TAILQ_INIT(&mpt->request_pending_list);
2256 	TAILQ_INIT(&mpt->request_free_list);
2257 	TAILQ_INIT(&mpt->request_timeout_list);
2258 	for (val = 0; val < MPT_MAX_LUNS; val++) {
2259 		STAILQ_INIT(&mpt->trt[val].atios);
2260 		STAILQ_INIT(&mpt->trt[val].inots);
2261 	}
2262 	STAILQ_INIT(&mpt->trt_wildcard.atios);
2263 	STAILQ_INIT(&mpt->trt_wildcard.inots);
2264 #ifdef	MPT_TEST_MULTIPATH
2265 	mpt->failure_id = -1;
2266 #endif
2267 	mpt->scsi_tgt_handler_id = MPT_HANDLER_ID_NONE;
2268 	mpt_sysctl_attach(mpt);
2269 	mpt_lprt(mpt, MPT_PRT_DEBUG, "doorbell req = %s\n",
2270 	    mpt_ioc_diag(mpt_read(mpt, MPT_OFFSET_DOORBELL)));
2271 
2272 	MPT_LOCK(mpt);
2273 	error = mpt_configure_ioc(mpt, 0, 0);
2274 	MPT_UNLOCK(mpt);
2275 
2276 	return (error);
2277 }
2278 
2279 int
2280 mpt_core_enable(struct mpt_softc *mpt)
2281 {
2282 	/*
2283 	 * We enter with the IOC enabled, but async events
2284 	 * not enabled, ports not enabled and interrupts
2285 	 * not enabled.
2286 	 */
2287 	MPT_LOCK(mpt);
2288 
2289 	/*
2290 	 * Enable asynchronous event reporting- all personalities
2291 	 * have attached so that they should be able to now field
2292 	 * async events.
2293 	 */
2294 	mpt_send_event_request(mpt, 1);
2295 
2296 	/*
2297 	 * Catch any pending interrupts
2298 	 *
2299 	 * This seems to be crucial- otherwise
2300 	 * the portenable below times out.
2301 	 */
2302 	mpt_intr(mpt);
2303 
2304 	/*
2305 	 * Enable Interrupts
2306 	 */
2307 	mpt_enable_ints(mpt);
2308 
2309 	/*
2310 	 * Catch any pending interrupts
2311 	 *
2312 	 * This seems to be crucial- otherwise
2313 	 * the portenable below times out.
2314 	 */
2315 	mpt_intr(mpt);
2316 
2317 	/*
2318 	 * Enable the port.
2319 	 */
2320 	if (mpt_send_port_enable(mpt, 0) != MPT_OK) {
2321 		mpt_prt(mpt, "failed to enable port 0\n");
2322 		MPT_UNLOCK(mpt);
2323 		return (ENXIO);
2324 	}
2325 	MPT_UNLOCK(mpt);
2326 	return (0);
2327 }
2328 
2329 void
2330 mpt_core_shutdown(struct mpt_softc *mpt)
2331 {
2332 	mpt_disable_ints(mpt);
2333 }
2334 
2335 void
2336 mpt_core_detach(struct mpt_softc *mpt)
2337 {
2338 	int val;
2339 
2340 	/*
2341 	 * XXX: FREE MEMORY
2342 	 */
2343 	mpt_disable_ints(mpt);
2344 
2345 	/* Make sure no request has pending timeouts. */
2346 	for (val = 0; val < MPT_MAX_REQUESTS(mpt); val++) {
2347 		request_t *req = &mpt->request_pool[val];
2348 		mpt_callout_drain(mpt, &req->callout);
2349 	}
2350 
2351 	mpt_dma_buf_free(mpt);
2352 }
2353 
2354 int
2355 mpt_core_unload(struct mpt_personality *pers)
2356 {
2357 	/* Unload is always successfull. */
2358 	return (0);
2359 }
2360 
2361 #define FW_UPLOAD_REQ_SIZE				\
2362 	(sizeof(MSG_FW_UPLOAD) - sizeof(SGE_MPI_UNION)	\
2363        + sizeof(FW_UPLOAD_TCSGE) + sizeof(SGE_SIMPLE32))
2364 
2365 static int
2366 mpt_upload_fw(struct mpt_softc *mpt)
2367 {
2368 	uint8_t fw_req_buf[FW_UPLOAD_REQ_SIZE];
2369 	MSG_FW_UPLOAD_REPLY fw_reply;
2370 	MSG_FW_UPLOAD *fw_req;
2371 	FW_UPLOAD_TCSGE *tsge;
2372 	SGE_SIMPLE32 *sge;
2373 	uint32_t flags;
2374 	int error;
2375 
2376 	memset(&fw_req_buf, 0, sizeof(fw_req_buf));
2377 	fw_req = (MSG_FW_UPLOAD *)fw_req_buf;
2378 	fw_req->ImageType = MPI_FW_UPLOAD_ITYPE_FW_IOC_MEM;
2379 	fw_req->Function = MPI_FUNCTION_FW_UPLOAD;
2380 	fw_req->MsgContext = htole32(MPT_REPLY_HANDLER_HANDSHAKE);
2381 	tsge = (FW_UPLOAD_TCSGE *)&fw_req->SGL;
2382 	tsge->DetailsLength = 12;
2383 	tsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
2384 	tsge->ImageSize = htole32(mpt->fw_image_size);
2385 	sge = (SGE_SIMPLE32 *)(tsge + 1);
2386 	flags = (MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER
2387 	      | MPI_SGE_FLAGS_END_OF_LIST | MPI_SGE_FLAGS_SIMPLE_ELEMENT
2388 	      | MPI_SGE_FLAGS_32_BIT_ADDRESSING | MPI_SGE_FLAGS_IOC_TO_HOST);
2389 	flags <<= MPI_SGE_FLAGS_SHIFT;
2390 	sge->FlagsLength = htole32(flags | mpt->fw_image_size);
2391 	sge->Address = htole32(mpt->fw_phys);
2392 	bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap, BUS_DMASYNC_PREREAD);
2393 	error = mpt_send_handshake_cmd(mpt, sizeof(fw_req_buf), &fw_req_buf);
2394 	if (error)
2395 		return(error);
2396 	error = mpt_recv_handshake_reply(mpt, sizeof(fw_reply), &fw_reply);
2397 	bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap, BUS_DMASYNC_POSTREAD);
2398 	return (error);
2399 }
2400 
2401 static void
2402 mpt_diag_outsl(struct mpt_softc *mpt, uint32_t addr,
2403 	       uint32_t *data, bus_size_t len)
2404 {
2405 	uint32_t *data_end;
2406 
2407 	data_end = data + (roundup2(len, sizeof(uint32_t)) / 4);
2408 	if (mpt->is_sas) {
2409 		pci_enable_io(mpt->dev, SYS_RES_IOPORT);
2410 	}
2411 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_ADDR, addr);
2412 	while (data != data_end) {
2413 		mpt_pio_write(mpt, MPT_OFFSET_DIAG_DATA, *data);
2414 		data++;
2415 	}
2416 	if (mpt->is_sas) {
2417 		pci_disable_io(mpt->dev, SYS_RES_IOPORT);
2418 	}
2419 }
2420 
2421 static int
2422 mpt_download_fw(struct mpt_softc *mpt)
2423 {
2424 	MpiFwHeader_t *fw_hdr;
2425 	int error;
2426 	uint32_t ext_offset;
2427 	uint32_t data;
2428 
2429 	mpt_prt(mpt, "Downloading Firmware - Image Size %d\n",
2430 		mpt->fw_image_size);
2431 
2432 	error = mpt_enable_diag_mode(mpt);
2433 	if (error != 0) {
2434 		mpt_prt(mpt, "Could not enter diagnostic mode!\n");
2435 		return (EIO);
2436 	}
2437 
2438 	mpt_write(mpt, MPT_OFFSET_DIAGNOSTIC,
2439 		  MPI_DIAG_RW_ENABLE|MPI_DIAG_DISABLE_ARM);
2440 
2441 	fw_hdr = (MpiFwHeader_t *)mpt->fw_image;
2442 	bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap, BUS_DMASYNC_PREWRITE);
2443 	mpt_diag_outsl(mpt, fw_hdr->LoadStartAddress, (uint32_t*)fw_hdr,
2444 		       fw_hdr->ImageSize);
2445 	bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap, BUS_DMASYNC_POSTWRITE);
2446 
2447 	ext_offset = fw_hdr->NextImageHeaderOffset;
2448 	while (ext_offset != 0) {
2449 		MpiExtImageHeader_t *ext;
2450 
2451 		ext = (MpiExtImageHeader_t *)((uintptr_t)fw_hdr + ext_offset);
2452 		ext_offset = ext->NextImageHeaderOffset;
2453 		bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap,
2454 		    BUS_DMASYNC_PREWRITE);
2455 		mpt_diag_outsl(mpt, ext->LoadStartAddress, (uint32_t*)ext,
2456 			       ext->ImageSize);
2457 		bus_dmamap_sync(mpt->fw_dmat, mpt->fw_dmap,
2458 		    BUS_DMASYNC_POSTWRITE);
2459 	}
2460 
2461 	if (mpt->is_sas) {
2462 		pci_enable_io(mpt->dev, SYS_RES_IOPORT);
2463 	}
2464 	/* Setup the address to jump to on reset. */
2465 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_ADDR, fw_hdr->IopResetRegAddr);
2466 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_DATA, fw_hdr->IopResetVectorValue);
2467 
2468 	/*
2469 	 * The controller sets the "flash bad" status after attempting
2470 	 * to auto-boot from flash.  Clear the status so that the controller
2471 	 * will continue the boot process with our newly installed firmware.
2472 	 */
2473 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_ADDR, MPT_DIAG_MEM_CFG_BASE);
2474 	data = mpt_pio_read(mpt, MPT_OFFSET_DIAG_DATA) | MPT_DIAG_MEM_CFG_BADFL;
2475 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_ADDR, MPT_DIAG_MEM_CFG_BASE);
2476 	mpt_pio_write(mpt, MPT_OFFSET_DIAG_DATA, data);
2477 
2478 	if (mpt->is_sas) {
2479 		pci_disable_io(mpt->dev, SYS_RES_IOPORT);
2480 	}
2481 
2482 	/*
2483 	 * Re-enable the processor and clear the boot halt flag.
2484 	 */
2485 	data = mpt_read(mpt, MPT_OFFSET_DIAGNOSTIC);
2486 	data &= ~(MPI_DIAG_PREVENT_IOC_BOOT|MPI_DIAG_DISABLE_ARM);
2487 	mpt_write(mpt, MPT_OFFSET_DIAGNOSTIC, data);
2488 
2489 	mpt_disable_diag_mode(mpt);
2490 	return (0);
2491 }
2492 
2493 static int
2494 mpt_dma_buf_alloc(struct mpt_softc *mpt)
2495 {
2496 	struct mpt_map_info mi;
2497 	uint8_t *vptr;
2498 	uint32_t pptr, end;
2499 	int i, error;
2500 
2501 	/* Create a child tag for data buffers */
2502 	if (mpt_dma_tag_create(mpt, mpt->parent_dmat, 1,
2503 	    0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR,
2504 	    NULL, NULL, (mpt->max_cam_seg_cnt - 1) * PAGE_SIZE,
2505 	    mpt->max_cam_seg_cnt, BUS_SPACE_MAXSIZE_32BIT, 0,
2506 	    &mpt->buffer_dmat) != 0) {
2507 		mpt_prt(mpt, "cannot create a dma tag for data buffers\n");
2508 		return (1);
2509 	}
2510 
2511 	/* Create a child tag for request buffers */
2512 	if (mpt_dma_tag_create(mpt, mpt->parent_dmat, PAGE_SIZE, 0,
2513 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
2514 	    NULL, NULL, MPT_REQ_MEM_SIZE(mpt), 1, BUS_SPACE_MAXSIZE_32BIT, 0,
2515 	    &mpt->request_dmat) != 0) {
2516 		mpt_prt(mpt, "cannot create a dma tag for requests\n");
2517 		return (1);
2518 	}
2519 
2520 	/* Allocate some DMA accessable memory for requests */
2521 	if (bus_dmamem_alloc(mpt->request_dmat, (void **)&mpt->request,
2522 	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &mpt->request_dmap) != 0) {
2523 		mpt_prt(mpt, "cannot allocate %d bytes of request memory\n",
2524 		    MPT_REQ_MEM_SIZE(mpt));
2525 		return (1);
2526 	}
2527 
2528 	mi.mpt = mpt;
2529 	mi.error = 0;
2530 
2531 	/* Load and lock it into "bus space" */
2532 	bus_dmamap_load(mpt->request_dmat, mpt->request_dmap, mpt->request,
2533 	    MPT_REQ_MEM_SIZE(mpt), mpt_map_rquest, &mi, 0);
2534 
2535 	if (mi.error) {
2536 		mpt_prt(mpt, "error %d loading dma map for DMA request queue\n",
2537 		    mi.error);
2538 		return (1);
2539 	}
2540 	mpt->request_phys = mi.phys;
2541 
2542 	/*
2543 	 * Now create per-request dma maps
2544 	 */
2545 	i = 0;
2546 	pptr =  mpt->request_phys;
2547 	vptr =  mpt->request;
2548 	end = pptr + MPT_REQ_MEM_SIZE(mpt);
2549 	while(pptr < end) {
2550 		request_t *req = &mpt->request_pool[i];
2551 		req->index = i++;
2552 
2553 		/* Store location of Request Data */
2554 		req->req_pbuf = pptr;
2555 		req->req_vbuf = vptr;
2556 
2557 		pptr += MPT_REQUEST_AREA;
2558 		vptr += MPT_REQUEST_AREA;
2559 
2560 		req->sense_pbuf = (pptr - MPT_SENSE_SIZE);
2561 		req->sense_vbuf = (vptr - MPT_SENSE_SIZE);
2562 
2563 		error = bus_dmamap_create(mpt->buffer_dmat, 0, &req->dmap);
2564 		if (error) {
2565 			mpt_prt(mpt, "error %d creating per-cmd DMA maps\n",
2566 			    error);
2567 			return (1);
2568 		}
2569 	}
2570 
2571 	return (0);
2572 }
2573 
2574 static void
2575 mpt_dma_buf_free(struct mpt_softc *mpt)
2576 {
2577 	int i;
2578 	if (mpt->request_dmat == 0) {
2579 		mpt_lprt(mpt, MPT_PRT_DEBUG, "already released dma memory\n");
2580 		return;
2581 	}
2582 	for (i = 0; i < MPT_MAX_REQUESTS(mpt); i++) {
2583 		bus_dmamap_destroy(mpt->buffer_dmat, mpt->request_pool[i].dmap);
2584 	}
2585 	bus_dmamap_unload(mpt->request_dmat, mpt->request_dmap);
2586 	bus_dmamem_free(mpt->request_dmat, mpt->request, mpt->request_dmap);
2587 	bus_dma_tag_destroy(mpt->request_dmat);
2588 	mpt->request_dmat = 0;
2589 	bus_dma_tag_destroy(mpt->buffer_dmat);
2590 }
2591 
2592 /*
2593  * Allocate/Initialize data structures for the controller.  Called
2594  * once at instance startup.
2595  */
2596 static int
2597 mpt_configure_ioc(struct mpt_softc *mpt, int tn, int needreset)
2598 {
2599 	PTR_MSG_PORT_FACTS_REPLY pfp;
2600 	int error, port, val;
2601 	size_t len;
2602 
2603 	if (tn == MPT_MAX_TRYS) {
2604 		return (-1);
2605 	}
2606 
2607 	/*
2608 	 * No need to reset if the IOC is already in the READY state.
2609 	 *
2610 	 * Force reset if initialization failed previously.
2611 	 * Note that a hard_reset of the second channel of a '929
2612 	 * will stop operation of the first channel.  Hopefully, if the
2613 	 * first channel is ok, the second will not require a hard
2614 	 * reset.
2615 	 */
2616 	if (needreset || MPT_STATE(mpt_rd_db(mpt)) != MPT_DB_STATE_READY) {
2617 		if (mpt_reset(mpt, FALSE) != MPT_OK) {
2618 			return (mpt_configure_ioc(mpt, tn++, 1));
2619 		}
2620 		needreset = 0;
2621 	}
2622 
2623 	if (mpt_get_iocfacts(mpt, &mpt->ioc_facts) != MPT_OK) {
2624 		mpt_prt(mpt, "mpt_get_iocfacts failed\n");
2625 		return (mpt_configure_ioc(mpt, tn++, 1));
2626 	}
2627 	mpt2host_iocfacts_reply(&mpt->ioc_facts);
2628 
2629 	mpt_prt(mpt, "MPI Version=%d.%d.%d.%d\n",
2630 	    mpt->ioc_facts.MsgVersion >> 8,
2631 	    mpt->ioc_facts.MsgVersion & 0xFF,
2632 	    mpt->ioc_facts.HeaderVersion >> 8,
2633 	    mpt->ioc_facts.HeaderVersion & 0xFF);
2634 
2635 	/*
2636 	 * Now that we know request frame size, we can calculate
2637 	 * the actual (reasonable) segment limit for read/write I/O.
2638 	 *
2639 	 * This limit is constrained by:
2640 	 *
2641 	 *  + The size of each area we allocate per command (and how
2642 	 *    many chain segments we can fit into it).
2643 	 *  + The total number of areas we've set up.
2644 	 *  + The actual chain depth the card will allow.
2645 	 *
2646 	 * The first area's segment count is limited by the I/O request
2647 	 * at the head of it. We cannot allocate realistically more
2648 	 * than MPT_MAX_REQUESTS areas. Therefore, to account for both
2649 	 * conditions, we'll just start out with MPT_MAX_REQUESTS-2.
2650 	 *
2651 	 */
2652 	/* total number of request areas we (can) allocate */
2653 	mpt->max_seg_cnt = MPT_MAX_REQUESTS(mpt) - 2;
2654 
2655 	/* converted to the number of chain areas possible */
2656 	mpt->max_seg_cnt *= MPT_NRFM(mpt);
2657 
2658 	/* limited by the number of chain areas the card will support */
2659 	if (mpt->max_seg_cnt > mpt->ioc_facts.MaxChainDepth) {
2660 		mpt_lprt(mpt, MPT_PRT_INFO,
2661 		    "chain depth limited to %u (from %u)\n",
2662 		    mpt->ioc_facts.MaxChainDepth, mpt->max_seg_cnt);
2663 		mpt->max_seg_cnt = mpt->ioc_facts.MaxChainDepth;
2664 	}
2665 
2666 	/* converted to the number of simple sges in chain segments. */
2667 	mpt->max_seg_cnt *= (MPT_NSGL(mpt) - 1);
2668 
2669 	/*
2670 	 * Use this as the basis for reporting the maximum I/O size to CAM.
2671 	 */
2672 	mpt->max_cam_seg_cnt = min(mpt->max_seg_cnt, (MAXPHYS / PAGE_SIZE) + 1);
2673 
2674 	error = mpt_dma_buf_alloc(mpt);
2675 	if (error != 0) {
2676 		mpt_prt(mpt, "mpt_dma_buf_alloc() failed!\n");
2677 		return (EIO);
2678 	}
2679 
2680 	for (val = 0; val < MPT_MAX_REQUESTS(mpt); val++) {
2681 		request_t *req = &mpt->request_pool[val];
2682 		req->state = REQ_STATE_ALLOCATED;
2683 		mpt_callout_init(mpt, &req->callout);
2684 		mpt_free_request(mpt, req);
2685 	}
2686 
2687 	mpt_lprt(mpt, MPT_PRT_INFO, "Maximum Segment Count: %u, Maximum "
2688 		 "CAM Segment Count: %u\n", mpt->max_seg_cnt,
2689 		 mpt->max_cam_seg_cnt);
2690 
2691 	mpt_lprt(mpt, MPT_PRT_INFO, "MsgLength=%u IOCNumber = %d\n",
2692 	    mpt->ioc_facts.MsgLength, mpt->ioc_facts.IOCNumber);
2693 	mpt_lprt(mpt, MPT_PRT_INFO,
2694 	    "IOCFACTS: GlobalCredits=%d BlockSize=%u bytes "
2695 	    "Request Frame Size %u bytes Max Chain Depth %u\n",
2696 	    mpt->ioc_facts.GlobalCredits, mpt->ioc_facts.BlockSize,
2697 	    mpt->ioc_facts.RequestFrameSize << 2,
2698 	    mpt->ioc_facts.MaxChainDepth);
2699 	mpt_lprt(mpt, MPT_PRT_INFO, "IOCFACTS: Num Ports %d, FWImageSize %d, "
2700 	    "Flags=%#x\n", mpt->ioc_facts.NumberOfPorts,
2701 	    mpt->ioc_facts.FWImageSize, mpt->ioc_facts.Flags);
2702 
2703 	len = mpt->ioc_facts.NumberOfPorts * sizeof (MSG_PORT_FACTS_REPLY);
2704 	mpt->port_facts = malloc(len, M_DEVBUF, M_NOWAIT | M_ZERO);
2705 	if (mpt->port_facts == NULL) {
2706 		mpt_prt(mpt, "unable to allocate memory for port facts\n");
2707 		return (ENOMEM);
2708 	}
2709 
2710 
2711 	if ((mpt->ioc_facts.Flags & MPI_IOCFACTS_FLAGS_FW_DOWNLOAD_BOOT) &&
2712 	    (mpt->fw_uploaded == 0)) {
2713 		struct mpt_map_info mi;
2714 
2715 		/*
2716 		 * In some configurations, the IOC's firmware is
2717 		 * stored in a shared piece of system NVRAM that
2718 		 * is only accessable via the BIOS.  In this
2719 		 * case, the firmware keeps a copy of firmware in
2720 		 * RAM until the OS driver retrieves it.  Once
2721 		 * retrieved, we are responsible for re-downloading
2722 		 * the firmware after any hard-reset.
2723 		 */
2724 		mpt->fw_image_size = mpt->ioc_facts.FWImageSize;
2725 		error = mpt_dma_tag_create(mpt, mpt->parent_dmat, 1, 0,
2726 		    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
2727 		    mpt->fw_image_size, 1, mpt->fw_image_size, 0,
2728 		    &mpt->fw_dmat);
2729 		if (error != 0) {
2730 			mpt_prt(mpt, "cannot create firmware dma tag\n");
2731 			return (ENOMEM);
2732 		}
2733 		error = bus_dmamem_alloc(mpt->fw_dmat,
2734 		    (void **)&mpt->fw_image, BUS_DMA_NOWAIT |
2735 		    BUS_DMA_COHERENT, &mpt->fw_dmap);
2736 		if (error != 0) {
2737 			mpt_prt(mpt, "cannot allocate firmware memory\n");
2738 			bus_dma_tag_destroy(mpt->fw_dmat);
2739 			return (ENOMEM);
2740 		}
2741 		mi.mpt = mpt;
2742 		mi.error = 0;
2743 		bus_dmamap_load(mpt->fw_dmat, mpt->fw_dmap,
2744 		    mpt->fw_image, mpt->fw_image_size, mpt_map_rquest, &mi, 0);
2745 		mpt->fw_phys = mi.phys;
2746 
2747 		error = mpt_upload_fw(mpt);
2748 		if (error != 0) {
2749 			mpt_prt(mpt, "firmware upload failed.\n");
2750 			bus_dmamap_unload(mpt->fw_dmat, mpt->fw_dmap);
2751 			bus_dmamem_free(mpt->fw_dmat, mpt->fw_image,
2752 			    mpt->fw_dmap);
2753 			bus_dma_tag_destroy(mpt->fw_dmat);
2754 			mpt->fw_image = NULL;
2755 			return (EIO);
2756 		}
2757 		mpt->fw_uploaded = 1;
2758 	}
2759 
2760 	for (port = 0; port < mpt->ioc_facts.NumberOfPorts; port++) {
2761 		pfp = &mpt->port_facts[port];
2762 		error = mpt_get_portfacts(mpt, 0, pfp);
2763 		if (error != MPT_OK) {
2764 			mpt_prt(mpt,
2765 			    "mpt_get_portfacts on port %d failed\n", port);
2766 			free(mpt->port_facts, M_DEVBUF);
2767 			mpt->port_facts = NULL;
2768 			return (mpt_configure_ioc(mpt, tn++, 1));
2769 		}
2770 		mpt2host_portfacts_reply(pfp);
2771 
2772 		if (port > 0) {
2773 			error = MPT_PRT_INFO;
2774 		} else {
2775 			error = MPT_PRT_DEBUG;
2776 		}
2777 		mpt_lprt(mpt, error,
2778 		    "PORTFACTS[%d]: Type %x PFlags %x IID %d MaxDev %d\n",
2779 		    port, pfp->PortType, pfp->ProtocolFlags, pfp->PortSCSIID,
2780 		    pfp->MaxDevices);
2781 
2782 	}
2783 
2784 	/*
2785 	 * XXX: Not yet supporting more than port 0
2786 	 */
2787 	pfp = &mpt->port_facts[0];
2788 	if (pfp->PortType == MPI_PORTFACTS_PORTTYPE_FC) {
2789 		mpt->is_fc = 1;
2790 		mpt->is_sas = 0;
2791 		mpt->is_spi = 0;
2792 	} else if (pfp->PortType == MPI_PORTFACTS_PORTTYPE_SAS) {
2793 		mpt->is_fc = 0;
2794 		mpt->is_sas = 1;
2795 		mpt->is_spi = 0;
2796 	} else if (pfp->PortType == MPI_PORTFACTS_PORTTYPE_SCSI) {
2797 		mpt->is_fc = 0;
2798 		mpt->is_sas = 0;
2799 		mpt->is_spi = 1;
2800 		if (mpt->mpt_ini_id == MPT_INI_ID_NONE)
2801 			mpt->mpt_ini_id = pfp->PortSCSIID;
2802 	} else if (pfp->PortType == MPI_PORTFACTS_PORTTYPE_ISCSI) {
2803 		mpt_prt(mpt, "iSCSI not supported yet\n");
2804 		return (ENXIO);
2805 	} else if (pfp->PortType == MPI_PORTFACTS_PORTTYPE_INACTIVE) {
2806 		mpt_prt(mpt, "Inactive Port\n");
2807 		return (ENXIO);
2808 	} else {
2809 		mpt_prt(mpt, "unknown Port Type %#x\n", pfp->PortType);
2810 		return (ENXIO);
2811 	}
2812 
2813 	/*
2814 	 * Set our role with what this port supports.
2815 	 *
2816 	 * Note this might be changed later in different modules
2817 	 * if this is different from what is wanted.
2818 	 */
2819 	mpt->role = MPT_ROLE_NONE;
2820 	if (pfp->ProtocolFlags & MPI_PORTFACTS_PROTOCOL_INITIATOR) {
2821 		mpt->role |= MPT_ROLE_INITIATOR;
2822 	}
2823 	if (pfp->ProtocolFlags & MPI_PORTFACTS_PROTOCOL_TARGET) {
2824 		mpt->role |= MPT_ROLE_TARGET;
2825 	}
2826 
2827 	/*
2828 	 * Enable the IOC
2829 	 */
2830 	if (mpt_enable_ioc(mpt, 1) != MPT_OK) {
2831 		mpt_prt(mpt, "unable to initialize IOC\n");
2832 		return (ENXIO);
2833 	}
2834 
2835 	/*
2836 	 * Read IOC configuration information.
2837 	 *
2838 	 * We need this to determine whether or not we have certain
2839 	 * settings for Integrated Mirroring (e.g.).
2840 	 */
2841 	mpt_read_config_info_ioc(mpt);
2842 
2843 	return (0);
2844 }
2845 
2846 static int
2847 mpt_enable_ioc(struct mpt_softc *mpt, int portenable)
2848 {
2849 	uint32_t pptr;
2850 	int val;
2851 
2852 	if (mpt_send_ioc_init(mpt, MPI_WHOINIT_HOST_DRIVER) != MPT_OK) {
2853 		mpt_prt(mpt, "mpt_send_ioc_init failed\n");
2854 		return (EIO);
2855 	}
2856 
2857 	mpt_lprt(mpt, MPT_PRT_DEBUG, "mpt_send_ioc_init ok\n");
2858 
2859 	if (mpt_wait_state(mpt, MPT_DB_STATE_RUNNING) != MPT_OK) {
2860 		mpt_prt(mpt, "IOC failed to go to run state\n");
2861 		return (ENXIO);
2862 	}
2863 	mpt_lprt(mpt, MPT_PRT_DEBUG, "IOC now at RUNSTATE\n");
2864 
2865 	/*
2866 	 * Give it reply buffers
2867 	 *
2868 	 * Do *not* exceed global credits.
2869 	 */
2870 	for (val = 0, pptr = mpt->reply_phys;
2871 	    (pptr + MPT_REPLY_SIZE) < (mpt->reply_phys + PAGE_SIZE);
2872 	     pptr += MPT_REPLY_SIZE) {
2873 		mpt_free_reply(mpt, pptr);
2874 		if (++val == mpt->ioc_facts.GlobalCredits - 1)
2875 			break;
2876 	}
2877 
2878 
2879 	/*
2880 	 * Enable the port if asked. This is only done if we're resetting
2881 	 * the IOC after initial startup.
2882 	 */
2883 	if (portenable) {
2884 		/*
2885 		 * Enable asynchronous event reporting
2886 		 */
2887 		mpt_send_event_request(mpt, 1);
2888 
2889 		if (mpt_send_port_enable(mpt, 0) != MPT_OK) {
2890 			mpt_prt(mpt, "%s: failed to enable port 0\n", __func__);
2891 			return (ENXIO);
2892 		}
2893 	}
2894 	return (MPT_OK);
2895 }
2896 
2897 /*
2898  * Endian Conversion Functions- only used on Big Endian machines
2899  */
2900 #if	_BYTE_ORDER == _BIG_ENDIAN
2901 void
2902 mpt2host_sge_simple_union(SGE_SIMPLE_UNION *sge)
2903 {
2904 
2905 	MPT_2_HOST32(sge, FlagsLength);
2906 	MPT_2_HOST32(sge, u.Address64.Low);
2907 	MPT_2_HOST32(sge, u.Address64.High);
2908 }
2909 
2910 void
2911 mpt2host_iocfacts_reply(MSG_IOC_FACTS_REPLY *rp)
2912 {
2913 
2914 	MPT_2_HOST16(rp, MsgVersion);
2915 	MPT_2_HOST16(rp, HeaderVersion);
2916 	MPT_2_HOST32(rp, MsgContext);
2917 	MPT_2_HOST16(rp, IOCExceptions);
2918 	MPT_2_HOST16(rp, IOCStatus);
2919 	MPT_2_HOST32(rp, IOCLogInfo);
2920 	MPT_2_HOST16(rp, ReplyQueueDepth);
2921 	MPT_2_HOST16(rp, RequestFrameSize);
2922 	MPT_2_HOST16(rp, Reserved_0101_FWVersion);
2923 	MPT_2_HOST16(rp, ProductID);
2924 	MPT_2_HOST32(rp, CurrentHostMfaHighAddr);
2925 	MPT_2_HOST16(rp, GlobalCredits);
2926 	MPT_2_HOST32(rp, CurrentSenseBufferHighAddr);
2927 	MPT_2_HOST16(rp, CurReplyFrameSize);
2928 	MPT_2_HOST32(rp, FWImageSize);
2929 	MPT_2_HOST32(rp, IOCCapabilities);
2930 	MPT_2_HOST32(rp, FWVersion.Word);
2931 	MPT_2_HOST16(rp, HighPriorityQueueDepth);
2932 	MPT_2_HOST16(rp, Reserved2);
2933 	mpt2host_sge_simple_union(&rp->HostPageBufferSGE);
2934 	MPT_2_HOST32(rp, ReplyFifoHostSignalingAddr);
2935 }
2936 
2937 void
2938 mpt2host_portfacts_reply(MSG_PORT_FACTS_REPLY *pfp)
2939 {
2940 
2941 	MPT_2_HOST16(pfp, Reserved);
2942 	MPT_2_HOST16(pfp, Reserved1);
2943 	MPT_2_HOST32(pfp, MsgContext);
2944 	MPT_2_HOST16(pfp, Reserved2);
2945 	MPT_2_HOST16(pfp, IOCStatus);
2946 	MPT_2_HOST32(pfp, IOCLogInfo);
2947 	MPT_2_HOST16(pfp, MaxDevices);
2948 	MPT_2_HOST16(pfp, PortSCSIID);
2949 	MPT_2_HOST16(pfp, ProtocolFlags);
2950 	MPT_2_HOST16(pfp, MaxPostedCmdBuffers);
2951 	MPT_2_HOST16(pfp, MaxPersistentIDs);
2952 	MPT_2_HOST16(pfp, MaxLanBuckets);
2953 	MPT_2_HOST16(pfp, Reserved4);
2954 	MPT_2_HOST32(pfp, Reserved5);
2955 }
2956 
2957 void
2958 mpt2host_config_page_ioc2(CONFIG_PAGE_IOC_2 *ioc2)
2959 {
2960 	int i;
2961 
2962 	MPT_2_HOST32(ioc2, CapabilitiesFlags);
2963 	for (i = 0; i < MPI_IOC_PAGE_2_RAID_VOLUME_MAX; i++) {
2964 		MPT_2_HOST16(ioc2, RaidVolume[i].Reserved3);
2965 	}
2966 }
2967 
2968 void
2969 mpt2host_config_page_ioc3(CONFIG_PAGE_IOC_3 *ioc3)
2970 {
2971 
2972 	MPT_2_HOST16(ioc3, Reserved2);
2973 }
2974 
2975 void
2976 mpt2host_config_page_scsi_port_0(CONFIG_PAGE_SCSI_PORT_0 *sp0)
2977 {
2978 
2979 	MPT_2_HOST32(sp0, Capabilities);
2980 	MPT_2_HOST32(sp0, PhysicalInterface);
2981 }
2982 
2983 void
2984 mpt2host_config_page_scsi_port_1(CONFIG_PAGE_SCSI_PORT_1 *sp1)
2985 {
2986 
2987 	MPT_2_HOST32(sp1, Configuration);
2988 	MPT_2_HOST32(sp1, OnBusTimerValue);
2989 	MPT_2_HOST16(sp1, IDConfig);
2990 }
2991 
2992 void
2993 host2mpt_config_page_scsi_port_1(CONFIG_PAGE_SCSI_PORT_1 *sp1)
2994 {
2995 
2996 	HOST_2_MPT32(sp1, Configuration);
2997 	HOST_2_MPT32(sp1, OnBusTimerValue);
2998 	HOST_2_MPT16(sp1, IDConfig);
2999 }
3000 
3001 void
3002 mpt2host_config_page_scsi_port_2(CONFIG_PAGE_SCSI_PORT_2 *sp2)
3003 {
3004 	int i;
3005 
3006 	MPT_2_HOST32(sp2, PortFlags);
3007 	MPT_2_HOST32(sp2, PortSettings);
3008 	for (i = 0; i < sizeof(sp2->DeviceSettings) /
3009 	    sizeof(*sp2->DeviceSettings); i++) {
3010 		MPT_2_HOST16(sp2, DeviceSettings[i].DeviceFlags);
3011 	}
3012 }
3013 
3014 void
3015 mpt2host_config_page_scsi_device_0(CONFIG_PAGE_SCSI_DEVICE_0 *sd0)
3016 {
3017 
3018 	MPT_2_HOST32(sd0, NegotiatedParameters);
3019 	MPT_2_HOST32(sd0, Information);
3020 }
3021 
3022 void
3023 mpt2host_config_page_scsi_device_1(CONFIG_PAGE_SCSI_DEVICE_1 *sd1)
3024 {
3025 
3026 	MPT_2_HOST32(sd1, RequestedParameters);
3027 	MPT_2_HOST32(sd1, Reserved);
3028 	MPT_2_HOST32(sd1, Configuration);
3029 }
3030 
3031 void
3032 host2mpt_config_page_scsi_device_1(CONFIG_PAGE_SCSI_DEVICE_1 *sd1)
3033 {
3034 
3035 	HOST_2_MPT32(sd1, RequestedParameters);
3036 	HOST_2_MPT32(sd1, Reserved);
3037 	HOST_2_MPT32(sd1, Configuration);
3038 }
3039 
3040 void
3041 mpt2host_config_page_fc_port_0(CONFIG_PAGE_FC_PORT_0 *fp0)
3042 {
3043 
3044 	MPT_2_HOST32(fp0, Flags);
3045 	MPT_2_HOST32(fp0, PortIdentifier);
3046 	MPT_2_HOST32(fp0, WWNN.Low);
3047 	MPT_2_HOST32(fp0, WWNN.High);
3048 	MPT_2_HOST32(fp0, WWPN.Low);
3049 	MPT_2_HOST32(fp0, WWPN.High);
3050 	MPT_2_HOST32(fp0, SupportedServiceClass);
3051 	MPT_2_HOST32(fp0, SupportedSpeeds);
3052 	MPT_2_HOST32(fp0, CurrentSpeed);
3053 	MPT_2_HOST32(fp0, MaxFrameSize);
3054 	MPT_2_HOST32(fp0, FabricWWNN.Low);
3055 	MPT_2_HOST32(fp0, FabricWWNN.High);
3056 	MPT_2_HOST32(fp0, FabricWWPN.Low);
3057 	MPT_2_HOST32(fp0, FabricWWPN.High);
3058 	MPT_2_HOST32(fp0, DiscoveredPortsCount);
3059 	MPT_2_HOST32(fp0, MaxInitiators);
3060 }
3061 
3062 void
3063 mpt2host_config_page_fc_port_1(CONFIG_PAGE_FC_PORT_1 *fp1)
3064 {
3065 
3066 	MPT_2_HOST32(fp1, Flags);
3067 	MPT_2_HOST32(fp1, NoSEEPROMWWNN.Low);
3068 	MPT_2_HOST32(fp1, NoSEEPROMWWNN.High);
3069 	MPT_2_HOST32(fp1, NoSEEPROMWWPN.Low);
3070 	MPT_2_HOST32(fp1, NoSEEPROMWWPN.High);
3071 }
3072 
3073 void
3074 host2mpt_config_page_fc_port_1(CONFIG_PAGE_FC_PORT_1 *fp1)
3075 {
3076 
3077 	HOST_2_MPT32(fp1, Flags);
3078 	HOST_2_MPT32(fp1, NoSEEPROMWWNN.Low);
3079 	HOST_2_MPT32(fp1, NoSEEPROMWWNN.High);
3080 	HOST_2_MPT32(fp1, NoSEEPROMWWPN.Low);
3081 	HOST_2_MPT32(fp1, NoSEEPROMWWPN.High);
3082 }
3083 
3084 void
3085 mpt2host_config_page_raid_vol_0(CONFIG_PAGE_RAID_VOL_0 *volp)
3086 {
3087 	int i;
3088 
3089 	MPT_2_HOST16(volp, VolumeStatus.Reserved);
3090 	MPT_2_HOST16(volp, VolumeSettings.Settings);
3091 	MPT_2_HOST32(volp, MaxLBA);
3092 	MPT_2_HOST32(volp, MaxLBAHigh);
3093 	MPT_2_HOST32(volp, StripeSize);
3094 	MPT_2_HOST32(volp, Reserved2);
3095 	MPT_2_HOST32(volp, Reserved3);
3096 	for (i = 0; i < MPI_RAID_VOL_PAGE_0_PHYSDISK_MAX; i++) {
3097 		MPT_2_HOST16(volp, PhysDisk[i].Reserved);
3098 	}
3099 }
3100 
3101 void
3102 mpt2host_config_page_raid_phys_disk_0(CONFIG_PAGE_RAID_PHYS_DISK_0 *rpd0)
3103 {
3104 
3105 	MPT_2_HOST32(rpd0, Reserved1);
3106 	MPT_2_HOST16(rpd0, PhysDiskStatus.Reserved);
3107 	MPT_2_HOST32(rpd0, MaxLBA);
3108 	MPT_2_HOST16(rpd0, ErrorData.Reserved);
3109 	MPT_2_HOST16(rpd0, ErrorData.ErrorCount);
3110 	MPT_2_HOST16(rpd0, ErrorData.SmartCount);
3111 }
3112 
3113 void
3114 mpt2host_mpi_raid_vol_indicator(MPI_RAID_VOL_INDICATOR *vi)
3115 {
3116 
3117 	MPT_2_HOST16(vi, TotalBlocks.High);
3118 	MPT_2_HOST16(vi, TotalBlocks.Low);
3119 	MPT_2_HOST16(vi, BlocksRemaining.High);
3120 	MPT_2_HOST16(vi, BlocksRemaining.Low);
3121 }
3122 #endif
3123