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