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