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