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