]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/mps/mps.c
Link Interface has no Link Error registers.
[FreeBSD/FreeBSD.git] / sys / dev / mps / mps.c
1 /*-
2  * Copyright (c) 2009 Yahoo! Inc.
3  * Copyright (c) 2011-2015 LSI Corp.
4  * Copyright (c) 2013-2015 Avago Technologies
5  * All rights reserved.
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, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
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
20  * FOR 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  * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
29  *
30  * $FreeBSD$
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 /* Communications core for Avago Technologies (LSI) MPT2 */
37
38 /* TODO Move headers to mpsvar */
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/selinfo.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/module.h>
47 #include <sys/bus.h>
48 #include <sys/conf.h>
49 #include <sys/bio.h>
50 #include <sys/malloc.h>
51 #include <sys/uio.h>
52 #include <sys/sysctl.h>
53 #include <sys/queue.h>
54 #include <sys/kthread.h>
55 #include <sys/taskqueue.h>
56 #include <sys/endian.h>
57 #include <sys/eventhandler.h>
58
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 #include <sys/rman.h>
62 #include <sys/proc.h>
63
64 #include <dev/pci/pcivar.h>
65
66 #include <cam/cam.h>
67 #include <cam/scsi/scsi_all.h>
68
69 #include <dev/mps/mpi/mpi2_type.h>
70 #include <dev/mps/mpi/mpi2.h>
71 #include <dev/mps/mpi/mpi2_ioc.h>
72 #include <dev/mps/mpi/mpi2_sas.h>
73 #include <dev/mps/mpi/mpi2_cnfg.h>
74 #include <dev/mps/mpi/mpi2_init.h>
75 #include <dev/mps/mpi/mpi2_tool.h>
76 #include <dev/mps/mps_ioctl.h>
77 #include <dev/mps/mpsvar.h>
78 #include <dev/mps/mps_table.h>
79
80 static int mps_diag_reset(struct mps_softc *sc, int sleep_flag);
81 static int mps_init_queues(struct mps_softc *sc);
82 static int mps_message_unit_reset(struct mps_softc *sc, int sleep_flag);
83 static int mps_transition_operational(struct mps_softc *sc);
84 static int mps_iocfacts_allocate(struct mps_softc *sc, uint8_t attaching);
85 static void mps_iocfacts_free(struct mps_softc *sc);
86 static void mps_startup(void *arg);
87 static int mps_send_iocinit(struct mps_softc *sc);
88 static int mps_alloc_queues(struct mps_softc *sc);
89 static int mps_alloc_replies(struct mps_softc *sc);
90 static int mps_alloc_requests(struct mps_softc *sc);
91 static int mps_attach_log(struct mps_softc *sc);
92 static __inline void mps_complete_command(struct mps_softc *sc,
93     struct mps_command *cm);
94 static void mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
95     MPI2_EVENT_NOTIFICATION_REPLY *reply);
96 static void mps_config_complete(struct mps_softc *sc, struct mps_command *cm);
97 static void mps_periodic(void *);
98 static int mps_reregister_events(struct mps_softc *sc);
99 static void mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm);
100 static int mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts);
101 static int mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag);
102 SYSCTL_NODE(_hw, OID_AUTO, mps, CTLFLAG_RD, 0, "MPS Driver Parameters");
103
104 MALLOC_DEFINE(M_MPT2, "mps", "mpt2 driver memory");
105
106 /*
107  * Do a "Diagnostic Reset" aka a hard reset.  This should get the chip out of
108  * any state and back to its initialization state machine.
109  */
110 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
111
112 /* Added this union to smoothly convert le64toh cm->cm_desc.Words.
113  * Compiler only support unint64_t to be passed as argument.
114  * Otherwise it will throw below error
115  * "aggregate value used where an integer was expected"
116  */
117
118 typedef union _reply_descriptor {
119         u64 word;
120         struct {
121                 u32 low;
122                 u32 high;
123         } u;
124 }reply_descriptor,address_descriptor;
125
126 /* Rate limit chain-fail messages to 1 per minute */
127 static struct timeval mps_chainfail_interval = { 60, 0 };
128
129 /* 
130  * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
131  * If this function is called from process context, it can sleep
132  * and there is no harm to sleep, in case if this fuction is called
133  * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
134  * based on sleep flags driver will call either msleep, pause or DELAY.
135  * msleep and pause are of same variant, but pause is used when mps_mtx
136  * is not hold by driver.
137  *
138  */
139 static int
140 mps_diag_reset(struct mps_softc *sc,int sleep_flag)
141 {
142         uint32_t reg;
143         int i, error, tries = 0;
144         uint8_t first_wait_done = FALSE;
145
146         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
147
148         /* Clear any pending interrupts */
149         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
150
151         /*
152          * Force NO_SLEEP for threads prohibited to sleep
153          * e.a Thread from interrupt handler are prohibited to sleep.
154          */
155         if (curthread->td_no_sleeping != 0)
156                 sleep_flag = NO_SLEEP;
157
158         mps_dprint(sc, MPS_INIT, "sequence start, sleep_flag= %d\n", sleep_flag);
159  
160         /* Push the magic sequence */
161         error = ETIMEDOUT;
162         while (tries++ < 20) {
163                 for (i = 0; i < sizeof(mpt2_reset_magic); i++)
164                         mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
165                             mpt2_reset_magic[i]);
166                 /* wait 100 msec */
167                 if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
168                         msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
169                             "mpsdiag", hz/10);
170                 else if (sleep_flag == CAN_SLEEP)
171                         pause("mpsdiag", hz/10);
172                 else
173                         DELAY(100 * 1000);
174
175                 reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
176                 if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
177                         error = 0;
178                         break;
179                 }
180         }
181         if (error) {
182                 mps_dprint(sc, MPS_INIT, "sequence failed, error=%d, exit\n",
183                     error);
184                 return (error);
185         }
186
187         /* Send the actual reset.  XXX need to refresh the reg? */
188         reg |= MPI2_DIAG_RESET_ADAPTER;
189         mps_dprint(sc, MPS_INIT, "sequence success, sending reset, reg= 0x%x\n",
190                 reg);
191         mps_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET, reg);
192
193         /* Wait up to 300 seconds in 50ms intervals */
194         error = ETIMEDOUT;
195         for (i = 0; i < 6000; i++) {
196                 /*
197                  * Wait 50 msec. If this is the first time through, wait 256
198                  * msec to satisfy Diag Reset timing requirements.
199                  */
200                 if (first_wait_done) {
201                         if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
202                                 msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0,
203                                     "mpsdiag", hz/20);
204                         else if (sleep_flag == CAN_SLEEP)
205                                 pause("mpsdiag", hz/20);
206                         else
207                                 DELAY(50 * 1000);
208                 } else {
209                         DELAY(256 * 1000);
210                         first_wait_done = TRUE;
211                 }
212                 /*
213                  * Check for the RESET_ADAPTER bit to be cleared first, then
214                  * wait for the RESET state to be cleared, which takes a little
215                  * longer.
216                  */
217                 reg = mps_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
218                 if (reg & MPI2_DIAG_RESET_ADAPTER) {
219                         continue;
220                 }
221                 reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
222                 if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
223                         error = 0;
224                         break;
225                 }
226         }
227         if (error) {
228                 mps_dprint(sc, MPS_INIT, "reset failed, error= %d, exit\n",
229                     error);
230                 return (error);
231         }
232
233         mps_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
234         mps_dprint(sc, MPS_INIT, "diag reset success, exit\n");
235
236         return (0);
237 }
238
239 static int
240 mps_message_unit_reset(struct mps_softc *sc, int sleep_flag)
241 {
242         int error;
243
244         MPS_FUNCTRACE(sc);
245
246         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
247
248         error = 0;
249         mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
250             MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
251             MPI2_DOORBELL_FUNCTION_SHIFT);
252
253         if (mps_wait_db_ack(sc, 5, sleep_flag) != 0) {
254                 mps_dprint(sc, MPS_INIT|MPS_FAULT,
255                     "Doorbell handshake failed\n");
256                 error = ETIMEDOUT;
257         }
258
259         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
260         return (error);
261 }
262
263 static int
264 mps_transition_ready(struct mps_softc *sc)
265 {
266         uint32_t reg, state;
267         int error, tries = 0;
268         int sleep_flags;
269
270         MPS_FUNCTRACE(sc);
271         /* If we are in attach call, do not sleep */
272         sleep_flags = (sc->mps_flags & MPS_FLAGS_ATTACH_DONE)
273                                         ? CAN_SLEEP:NO_SLEEP;
274         error = 0;
275
276         mps_dprint(sc, MPS_INIT, "%s entered, sleep_flags= %d\n",
277            __func__, sleep_flags);
278
279         while (tries++ < 1200) {
280                 reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
281                 mps_dprint(sc, MPS_INIT, "  Doorbell= 0x%x\n", reg);
282
283                 /*
284                  * Ensure the IOC is ready to talk.  If it's not, try
285                  * resetting it.
286                  */
287                 if (reg & MPI2_DOORBELL_USED) {
288                         mps_dprint(sc, MPS_INIT, "  Not ready, sending diag "
289                             "reset\n");
290                         mps_diag_reset(sc, sleep_flags);
291                         DELAY(50000);
292                         continue;
293                 }
294
295                 /* Is the adapter owned by another peer? */
296                 if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
297                     (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
298                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC is under the "
299                             "control of another peer host, aborting "
300                             "initialization.\n");
301                         error = ENXIO;
302                         break;
303                 }
304                 
305                 state = reg & MPI2_IOC_STATE_MASK;
306                 if (state == MPI2_IOC_STATE_READY) {
307                         /* Ready to go! */
308                         error = 0;
309                         break;
310                 } else if (state == MPI2_IOC_STATE_FAULT) {
311                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC in fault "
312                             "state 0x%x, resetting\n",
313                             state & MPI2_DOORBELL_FAULT_CODE_MASK);
314                         mps_diag_reset(sc, sleep_flags);
315                 } else if (state == MPI2_IOC_STATE_OPERATIONAL) {
316                         /* Need to take ownership */
317                         mps_message_unit_reset(sc, sleep_flags);
318                 } else if (state == MPI2_IOC_STATE_RESET) {
319                         /* Wait a bit, IOC might be in transition */
320                         mps_dprint(sc, MPS_INIT|MPS_FAULT,
321                             "IOC in unexpected reset state\n");
322                 } else {
323                         mps_dprint(sc, MPS_INIT|MPS_FAULT,
324                             "IOC in unknown state 0x%x\n", state);
325                         error = EINVAL;
326                         break;
327                 }
328         
329                 /* Wait 50ms for things to settle down. */
330                 DELAY(50000);
331         }
332
333         if (error)
334                 mps_dprint(sc, MPS_INIT|MPS_FAULT,
335                     "Cannot transition IOC to ready\n");
336         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
337
338         return (error);
339 }
340
341 static int
342 mps_transition_operational(struct mps_softc *sc)
343 {
344         uint32_t reg, state;
345         int error;
346
347         MPS_FUNCTRACE(sc);
348
349         error = 0;
350         reg = mps_regread(sc, MPI2_DOORBELL_OFFSET);
351         mps_dprint(sc, MPS_INIT, "%s entered, Doorbell= 0x%x\n", __func__, reg);
352
353         state = reg & MPI2_IOC_STATE_MASK;
354         if (state != MPI2_IOC_STATE_READY) {
355                 mps_dprint(sc, MPS_INIT, "IOC not ready\n");
356                 if ((error = mps_transition_ready(sc)) != 0) {
357                         mps_dprint(sc, MPS_INIT|MPS_FAULT, 
358                             "failed to transition ready, exit\n");
359                         return (error);
360                 }
361         }
362
363         error = mps_send_iocinit(sc);
364         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
365
366         return (error);
367 }
368
369 /*
370  * This is called during attach and when re-initializing due to a Diag Reset.
371  * IOC Facts is used to allocate many of the structures needed by the driver.
372  * If called from attach, de-allocation is not required because the driver has
373  * not allocated any structures yet, but if called from a Diag Reset, previously
374  * allocated structures based on IOC Facts will need to be freed and re-
375  * allocated bases on the latest IOC Facts.
376  */
377 static int
378 mps_iocfacts_allocate(struct mps_softc *sc, uint8_t attaching)
379 {
380         int error;
381         Mpi2IOCFactsReply_t saved_facts;
382         uint8_t saved_mode, reallocating;
383
384         mps_dprint(sc, MPS_INIT|MPS_TRACE, "%s entered\n", __func__);
385
386         /* Save old IOC Facts and then only reallocate if Facts have changed */
387         if (!attaching) {
388                 bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
389         }
390
391         /*
392          * Get IOC Facts.  In all cases throughout this function, panic if doing
393          * a re-initialization and only return the error if attaching so the OS
394          * can handle it.
395          */
396         if ((error = mps_get_iocfacts(sc, sc->facts)) != 0) {
397                 if (attaching) {
398                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to get "
399                             "IOC Facts with error %d, exit\n", error);
400                         return (error);
401                 } else {
402                         panic("%s failed to get IOC Facts with error %d\n",
403                             __func__, error);
404                 }
405         }
406
407         MPS_DPRINT_PAGE(sc, MPS_XINFO, iocfacts, sc->facts);
408
409         snprintf(sc->fw_version, sizeof(sc->fw_version), 
410             "%02d.%02d.%02d.%02d", 
411             sc->facts->FWVersion.Struct.Major,
412             sc->facts->FWVersion.Struct.Minor,
413             sc->facts->FWVersion.Struct.Unit,
414             sc->facts->FWVersion.Struct.Dev);
415
416         mps_dprint(sc, MPS_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
417             MPS_DRIVER_VERSION);
418         mps_dprint(sc, MPS_INFO, "IOCCapabilities: %b\n",
419              sc->facts->IOCCapabilities,
420             "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
421             "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
422             "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc");
423
424         /*
425          * If the chip doesn't support event replay then a hard reset will be
426          * required to trigger a full discovery.  Do the reset here then
427          * retransition to Ready.  A hard reset might have already been done,
428          * but it doesn't hurt to do it again.  Only do this if attaching, not
429          * for a Diag Reset.
430          */
431         if (attaching && ((sc->facts->IOCCapabilities &
432             MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
433                 mps_dprint(sc, MPS_INIT, "No event replay, reseting\n");
434                 mps_diag_reset(sc, NO_SLEEP);
435                 if ((error = mps_transition_ready(sc)) != 0) {
436                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to "
437                             "transition to ready with error %d, exit\n",
438                             error);
439                         return (error);
440                 }
441         }
442
443         /*
444          * Set flag if IR Firmware is loaded.  If the RAID Capability has
445          * changed from the previous IOC Facts, log a warning, but only if
446          * checking this after a Diag Reset and not during attach.
447          */
448         saved_mode = sc->ir_firmware;
449         if (sc->facts->IOCCapabilities &
450             MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
451                 sc->ir_firmware = 1;
452         if (!attaching) {
453                 if (sc->ir_firmware != saved_mode) {
454                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "new IR/IT mode "
455                             "in IOC Facts does not match previous mode\n");
456                 }
457         }
458
459         /* Only deallocate and reallocate if relevant IOC Facts have changed */
460         reallocating = FALSE;
461         sc->mps_flags &= ~MPS_FLAGS_REALLOCATED;
462
463         if ((!attaching) &&
464             ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
465             (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
466             (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
467             (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
468             (saved_facts.ProductID != sc->facts->ProductID) ||
469             (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
470             (saved_facts.IOCRequestFrameSize !=
471             sc->facts->IOCRequestFrameSize) ||
472             (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
473             (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
474             (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
475             (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
476             (saved_facts.MaxReplyDescriptorPostQueueDepth !=
477             sc->facts->MaxReplyDescriptorPostQueueDepth) ||
478             (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
479             (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
480             (saved_facts.MaxPersistentEntries !=
481             sc->facts->MaxPersistentEntries))) {
482                 reallocating = TRUE;
483
484                 /* Record that we reallocated everything */
485                 sc->mps_flags |= MPS_FLAGS_REALLOCATED;
486         }
487
488         /*
489          * Some things should be done if attaching or re-allocating after a Diag
490          * Reset, but are not needed after a Diag Reset if the FW has not
491          * changed.
492          */
493         if (attaching || reallocating) {
494                 /*
495                  * Check if controller supports FW diag buffers and set flag to
496                  * enable each type.
497                  */
498                 if (sc->facts->IOCCapabilities &
499                     MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
500                         sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
501                             enabled = TRUE;
502                 if (sc->facts->IOCCapabilities &
503                     MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
504                         sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
505                             enabled = TRUE;
506                 if (sc->facts->IOCCapabilities &
507                     MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
508                         sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
509                             enabled = TRUE;
510
511                 /*
512                  * Set flag if EEDP is supported and if TLR is supported.
513                  */
514                 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
515                         sc->eedp_enabled = TRUE;
516                 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
517                         sc->control_TLR = TRUE;
518
519                 /*
520                  * Size the queues. Since the reply queues always need one free
521                  * entry, we'll just deduct one reply message here.
522                  */
523                 sc->num_reqs = MIN(MPS_REQ_FRAMES, sc->facts->RequestCredit);
524                 sc->num_replies = MIN(MPS_REPLY_FRAMES + MPS_EVT_REPLY_FRAMES,
525                     sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
526
527                 /*
528                  * Initialize all Tail Queues
529                  */
530                 TAILQ_INIT(&sc->req_list);
531                 TAILQ_INIT(&sc->high_priority_req_list);
532                 TAILQ_INIT(&sc->chain_list);
533                 TAILQ_INIT(&sc->tm_list);
534         }
535
536         /*
537          * If doing a Diag Reset and the FW is significantly different
538          * (reallocating will be set above in IOC Facts comparison), then all
539          * buffers based on the IOC Facts will need to be freed before they are
540          * reallocated.
541          */
542         if (reallocating) {
543                 mps_iocfacts_free(sc);
544                 mpssas_realloc_targets(sc, saved_facts.MaxTargets +
545                     saved_facts.MaxVolumes);
546         }
547
548         /*
549          * Any deallocation has been completed.  Now start reallocating
550          * if needed.  Will only need to reallocate if attaching or if the new
551          * IOC Facts are different from the previous IOC Facts after a Diag
552          * Reset. Targets have already been allocated above if needed.
553          */
554         if (attaching || reallocating) {
555                 if (((error = mps_alloc_queues(sc)) != 0) ||
556                     ((error = mps_alloc_replies(sc)) != 0) ||
557                     ((error = mps_alloc_requests(sc)) != 0)) {
558                         if (attaching ) {
559                                 mps_dprint(sc, MPS_INIT|MPS_FAULT,
560                                     "Failed to alloc queues with error %d\n",
561                                     error);
562                                 mps_free(sc);
563                                 return (error);
564                         } else {
565                                 panic("%s failed to alloc queues with error "
566                                     "%d\n", __func__, error);
567                         }
568                 }
569         }
570
571         /* Always initialize the queues */
572         bzero(sc->free_queue, sc->fqdepth * 4);
573         mps_init_queues(sc);
574
575         /*
576          * Always get the chip out of the reset state, but only panic if not
577          * attaching.  If attaching and there is an error, that is handled by
578          * the OS.
579          */
580         error = mps_transition_operational(sc);
581         if (error != 0) {
582                 if (attaching) {
583                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to "
584                             "transition to operational with error %d\n", error);
585                         mps_free(sc);
586                         return (error);
587                 } else {
588                         panic("%s failed to transition to operational with "
589                             "error %d\n", __func__, error);
590                 }
591         }
592
593         /*
594          * Finish the queue initialization.
595          * These are set here instead of in mps_init_queues() because the
596          * IOC resets these values during the state transition in
597          * mps_transition_operational().  The free index is set to 1
598          * because the corresponding index in the IOC is set to 0, and the
599          * IOC treats the queues as full if both are set to the same value.
600          * Hence the reason that the queue can't hold all of the possible
601          * replies.
602          */
603         sc->replypostindex = 0;
604         mps_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
605         mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
606
607         /*
608          * Attach the subsystems so they can prepare their event masks.
609          */
610         /* XXX Should be dynamic so that IM/IR and user modules can attach */
611         if (attaching) {
612                 mps_dprint(sc, MPS_INIT, "Attaching subsystems\n");
613                 if (((error = mps_attach_log(sc)) != 0) ||
614                     ((error = mps_attach_sas(sc)) != 0) ||
615                     ((error = mps_attach_user(sc)) != 0)) {
616                         mps_dprint(sc, MPS_INIT|MPS_FAULT,"Failed to attach "
617                             "all subsystems: error %d\n", error);
618                         mps_free(sc);
619                         return (error);
620                 }
621
622                 if ((error = mps_pci_setup_interrupts(sc)) != 0) {
623                         mps_dprint(sc, MPS_INIT|MPS_FAULT, "Failed to setup "
624                             "interrupts\n");
625                         mps_free(sc);
626                         return (error);
627                 }
628         }
629
630         /*
631          * Set flag if this is a WD controller.  This shouldn't ever change, but
632          * reset it after a Diag Reset, just in case.
633          */
634         sc->WD_available = FALSE;
635         if (pci_get_device(sc->mps_dev) == MPI2_MFGPAGE_DEVID_SSS6200)
636                 sc->WD_available = TRUE;
637
638         return (error);
639 }
640
641 /*
642  * This is called if memory is being free (during detach for example) and when
643  * buffers need to be reallocated due to a Diag Reset.
644  */
645 static void
646 mps_iocfacts_free(struct mps_softc *sc)
647 {
648         struct mps_command *cm;
649         int i;
650
651         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
652
653         if (sc->free_busaddr != 0)
654                 bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
655         if (sc->free_queue != NULL)
656                 bus_dmamem_free(sc->queues_dmat, sc->free_queue,
657                     sc->queues_map);
658         if (sc->queues_dmat != NULL)
659                 bus_dma_tag_destroy(sc->queues_dmat);
660
661         if (sc->chain_busaddr != 0)
662                 bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
663         if (sc->chain_frames != NULL)
664                 bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
665                     sc->chain_map);
666         if (sc->chain_dmat != NULL)
667                 bus_dma_tag_destroy(sc->chain_dmat);
668
669         if (sc->sense_busaddr != 0)
670                 bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
671         if (sc->sense_frames != NULL)
672                 bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
673                     sc->sense_map);
674         if (sc->sense_dmat != NULL)
675                 bus_dma_tag_destroy(sc->sense_dmat);
676
677         if (sc->reply_busaddr != 0)
678                 bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
679         if (sc->reply_frames != NULL)
680                 bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
681                     sc->reply_map);
682         if (sc->reply_dmat != NULL)
683                 bus_dma_tag_destroy(sc->reply_dmat);
684
685         if (sc->req_busaddr != 0)
686                 bus_dmamap_unload(sc->req_dmat, sc->req_map);
687         if (sc->req_frames != NULL)
688                 bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
689         if (sc->req_dmat != NULL)
690                 bus_dma_tag_destroy(sc->req_dmat);
691
692         if (sc->chains != NULL)
693                 free(sc->chains, M_MPT2);
694         if (sc->commands != NULL) {
695                 for (i = 1; i < sc->num_reqs; i++) {
696                         cm = &sc->commands[i];
697                         bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
698                 }
699                 free(sc->commands, M_MPT2);
700         }
701         if (sc->buffer_dmat != NULL)
702                 bus_dma_tag_destroy(sc->buffer_dmat);
703 }
704
705 /* 
706  * The terms diag reset and hard reset are used interchangeably in the MPI
707  * docs to mean resetting the controller chip.  In this code diag reset
708  * cleans everything up, and the hard reset function just sends the reset
709  * sequence to the chip.  This should probably be refactored so that every
710  * subsystem gets a reset notification of some sort, and can clean up
711  * appropriately.
712  */
713 int
714 mps_reinit(struct mps_softc *sc)
715 {
716         int error;
717         struct mpssas_softc *sassc;
718
719         sassc = sc->sassc;
720
721         MPS_FUNCTRACE(sc);
722
723         mtx_assert(&sc->mps_mtx, MA_OWNED);
724
725         mps_dprint(sc, MPS_INIT|MPS_INFO, "Reinitializing controller\n");
726         if (sc->mps_flags & MPS_FLAGS_DIAGRESET) {
727                 mps_dprint(sc, MPS_INIT, "Reset already in progress\n");
728                 return 0;
729         }
730
731         /* make sure the completion callbacks can recognize they're getting
732          * a NULL cm_reply due to a reset.
733          */
734         sc->mps_flags |= MPS_FLAGS_DIAGRESET;
735
736         /*
737          * Mask interrupts here.
738          */
739         mps_dprint(sc, MPS_INIT, "masking interrupts and resetting\n");
740         mps_mask_intr(sc);
741
742         error = mps_diag_reset(sc, CAN_SLEEP);
743         if (error != 0) {
744                 /* XXXSL No need to panic here */
745                 panic("%s hard reset failed with error %d\n",
746                     __func__, error);
747         }
748
749         /* Restore the PCI state, including the MSI-X registers */
750         mps_pci_restore(sc);
751
752         /* Give the I/O subsystem special priority to get itself prepared */
753         mpssas_handle_reinit(sc);
754
755         /*
756          * Get IOC Facts and allocate all structures based on this information.
757          * The attach function will also call mps_iocfacts_allocate at startup.
758          * If relevant values have changed in IOC Facts, this function will free
759          * all of the memory based on IOC Facts and reallocate that memory.
760          */
761         if ((error = mps_iocfacts_allocate(sc, FALSE)) != 0) {
762                 panic("%s IOC Facts based allocation failed with error %d\n",
763                     __func__, error);
764         }
765
766         /*
767          * Mapping structures will be re-allocated after getting IOC Page8, so
768          * free these structures here.
769          */
770         mps_mapping_exit(sc);
771
772         /*
773          * The static page function currently read is IOC Page8.  Others can be
774          * added in future.  It's possible that the values in IOC Page8 have
775          * changed after a Diag Reset due to user modification, so always read
776          * these.  Interrupts are masked, so unmask them before getting config
777          * pages.
778          */
779         mps_unmask_intr(sc);
780         sc->mps_flags &= ~MPS_FLAGS_DIAGRESET;
781         mps_base_static_config_pages(sc);
782
783         /*
784          * Some mapping info is based in IOC Page8 data, so re-initialize the
785          * mapping tables.
786          */
787         mps_mapping_initialize(sc);
788
789         /*
790          * Restart will reload the event masks clobbered by the reset, and
791          * then enable the port.
792          */
793         mps_reregister_events(sc);
794
795         /* the end of discovery will release the simq, so we're done. */
796         mps_dprint(sc, MPS_INIT|MPS_XINFO, "Finished sc %p post %u free %u\n", 
797             sc, sc->replypostindex, sc->replyfreeindex);
798
799         mpssas_release_simq_reinit(sassc);
800         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
801
802         return 0;
803 }
804
805 /* Wait for the chip to ACK a word that we've put into its FIFO 
806  * Wait for <timeout> seconds. In single loop wait for busy loop
807  * for 500 microseconds.
808  * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
809  * */
810 static int
811 mps_wait_db_ack(struct mps_softc *sc, int timeout, int sleep_flag)
812 {
813
814         u32 cntdn, count;
815         u32 int_status;
816         u32 doorbell;
817
818         count = 0;
819         cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
820         do {
821                 int_status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
822                 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
823                         mps_dprint(sc, MPS_TRACE, 
824                         "%s: successful count(%d), timeout(%d)\n",
825                         __func__, count, timeout);
826                 return 0;
827                 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
828                         doorbell = mps_regread(sc, MPI2_DOORBELL_OFFSET);
829                         if ((doorbell & MPI2_IOC_STATE_MASK) ==
830                                 MPI2_IOC_STATE_FAULT) {
831                                 mps_dprint(sc, MPS_FAULT, 
832                                         "fault_state(0x%04x)!\n", doorbell);
833                                 return (EFAULT);
834                         }
835                 } else if (int_status == 0xFFFFFFFF)
836                         goto out;
837
838                 /* If it can sleep, sleep for 1 milisecond, else busy loop for 
839                 * 0.5 milisecond */
840                 if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP)
841                         msleep(&sc->msleep_fake_chan, &sc->mps_mtx, 0, 
842                         "mpsdba", hz/1000);
843                 else if (sleep_flag == CAN_SLEEP)
844                         pause("mpsdba", hz/1000);
845                 else
846                         DELAY(500);
847                 count++;
848         } while (--cntdn);
849
850         out:
851         mps_dprint(sc, MPS_FAULT, "%s: failed due to timeout count(%d), "
852                 "int_status(%x)!\n", __func__, count, int_status);
853         return (ETIMEDOUT);
854
855 }
856
857 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
858 static int
859 mps_wait_db_int(struct mps_softc *sc)
860 {
861         int retry;
862
863         for (retry = 0; retry < MPS_DB_MAX_WAIT; retry++) {
864                 if ((mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
865                     MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
866                         return (0);
867                 DELAY(2000);
868         }
869         return (ETIMEDOUT);
870 }
871
872 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
873 static int
874 mps_request_sync(struct mps_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
875     int req_sz, int reply_sz, int timeout)
876 {
877         uint32_t *data32;
878         uint16_t *data16;
879         int i, count, ioc_sz, residual;
880         int sleep_flags = CAN_SLEEP;
881
882         if (curthread->td_no_sleeping != 0)
883                 sleep_flags = NO_SLEEP;
884
885         /* Step 1 */
886         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
887
888         /* Step 2 */
889         if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
890                 return (EBUSY);
891
892         /* Step 3
893          * Announce that a message is coming through the doorbell.  Messages
894          * are pushed at 32bit words, so round up if needed.
895          */
896         count = (req_sz + 3) / 4;
897         mps_regwrite(sc, MPI2_DOORBELL_OFFSET,
898             (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
899             (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
900
901         /* Step 4 */
902         if (mps_wait_db_int(sc) ||
903             (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
904                 mps_dprint(sc, MPS_FAULT, "Doorbell failed to activate\n");
905                 return (ENXIO);
906         }
907         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
908         if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
909                 mps_dprint(sc, MPS_FAULT, "Doorbell handshake failed\n");
910                 return (ENXIO);
911         }
912
913         /* Step 5 */
914         /* Clock out the message data synchronously in 32-bit dwords*/
915         data32 = (uint32_t *)req;
916         for (i = 0; i < count; i++) {
917                 mps_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
918                 if (mps_wait_db_ack(sc, 5, sleep_flags) != 0) {
919                         mps_dprint(sc, MPS_FAULT,
920                             "Timeout while writing doorbell\n");
921                         return (ENXIO);
922                 }
923         }
924
925         /* Step 6 */
926         /* Clock in the reply in 16-bit words.  The total length of the
927          * message is always in the 4th byte, so clock out the first 2 words
928          * manually, then loop the rest.
929          */
930         data16 = (uint16_t *)reply;
931         if (mps_wait_db_int(sc) != 0) {
932                 mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 0\n");
933                 return (ENXIO);
934         }
935         data16[0] =
936             mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
937         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
938         if (mps_wait_db_int(sc) != 0) {
939                 mps_dprint(sc, MPS_FAULT, "Timeout reading doorbell 1\n");
940                 return (ENXIO);
941         }
942         data16[1] =
943             mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
944         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
945
946         /* Number of 32bit words in the message */
947         ioc_sz = reply->MsgLength;
948
949         /*
950          * Figure out how many 16bit words to clock in without overrunning.
951          * The precision loss with dividing reply_sz can safely be
952          * ignored because the messages can only be multiples of 32bits.
953          */
954         residual = 0;
955         count = MIN((reply_sz / 4), ioc_sz) * 2;
956         if (count < ioc_sz * 2) {
957                 residual = ioc_sz * 2 - count;
958                 mps_dprint(sc, MPS_ERROR, "Driver error, throwing away %d "
959                     "residual message words\n", residual);
960         }
961
962         for (i = 2; i < count; i++) {
963                 if (mps_wait_db_int(sc) != 0) {
964                         mps_dprint(sc, MPS_FAULT,
965                             "Timeout reading doorbell %d\n", i);
966                         return (ENXIO);
967                 }
968                 data16[i] = mps_regread(sc, MPI2_DOORBELL_OFFSET) &
969                     MPI2_DOORBELL_DATA_MASK;
970                 mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
971         }
972
973         /*
974          * Pull out residual words that won't fit into the provided buffer.
975          * This keeps the chip from hanging due to a driver programming
976          * error.
977          */
978         while (residual--) {
979                 if (mps_wait_db_int(sc) != 0) {
980                         mps_dprint(sc, MPS_FAULT,
981                             "Timeout reading doorbell\n");
982                         return (ENXIO);
983                 }
984                 (void)mps_regread(sc, MPI2_DOORBELL_OFFSET);
985                 mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
986         }
987
988         /* Step 7 */
989         if (mps_wait_db_int(sc) != 0) {
990                 mps_dprint(sc, MPS_FAULT, "Timeout waiting to exit doorbell\n");
991                 return (ENXIO);
992         }
993         if (mps_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
994                 mps_dprint(sc, MPS_FAULT, "Warning, doorbell still active\n");
995         mps_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
996
997         return (0);
998 }
999
1000 static void
1001 mps_enqueue_request(struct mps_softc *sc, struct mps_command *cm)
1002 {
1003         reply_descriptor rd;
1004         MPS_FUNCTRACE(sc);
1005         mps_dprint(sc, MPS_TRACE, "SMID %u cm %p ccb %p\n",
1006             cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1007
1008         if (sc->mps_flags & MPS_FLAGS_ATTACH_DONE && !(sc->mps_flags & MPS_FLAGS_SHUTDOWN))
1009                 mtx_assert(&sc->mps_mtx, MA_OWNED);
1010
1011         if (++sc->io_cmds_active > sc->io_cmds_highwater)
1012                 sc->io_cmds_highwater++;
1013         rd.u.low = cm->cm_desc.Words.Low;
1014         rd.u.high = cm->cm_desc.Words.High;
1015         rd.word = htole64(rd.word);
1016         /* TODO-We may need to make below regwrite atomic */
1017         mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1018             rd.u.low);
1019         mps_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1020             rd.u.high);
1021 }
1022
1023 /*
1024  * Just the FACTS, ma'am.
1025  */
1026 static int
1027 mps_get_iocfacts(struct mps_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1028 {
1029         MPI2_DEFAULT_REPLY *reply;
1030         MPI2_IOC_FACTS_REQUEST request;
1031         int error, req_sz, reply_sz;
1032
1033         MPS_FUNCTRACE(sc);
1034         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1035
1036         req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1037         reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1038         reply = (MPI2_DEFAULT_REPLY *)facts;
1039
1040         bzero(&request, req_sz);
1041         request.Function = MPI2_FUNCTION_IOC_FACTS;
1042         error = mps_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1043         mps_dprint(sc, MPS_INIT, "%s exit error= %d\n", __func__, error);
1044
1045         return (error);
1046 }
1047
1048 static int
1049 mps_send_iocinit(struct mps_softc *sc)
1050 {
1051         MPI2_IOC_INIT_REQUEST   init;
1052         MPI2_DEFAULT_REPLY      reply;
1053         int req_sz, reply_sz, error;
1054         struct timeval now;
1055         uint64_t time_in_msec;
1056
1057         MPS_FUNCTRACE(sc);
1058         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1059
1060         req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1061         reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1062         bzero(&init, req_sz);
1063         bzero(&reply, reply_sz);
1064
1065         /*
1066          * Fill in the init block.  Note that most addresses are
1067          * deliberately in the lower 32bits of memory.  This is a micro-
1068          * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1069          */
1070         init.Function = MPI2_FUNCTION_IOC_INIT;
1071         init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1072         init.MsgVersion = htole16(MPI2_VERSION);
1073         init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1074         init.SystemRequestFrameSize = htole16(sc->facts->IOCRequestFrameSize);
1075         init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1076         init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1077         init.SenseBufferAddressHigh = 0;
1078         init.SystemReplyAddressHigh = 0;
1079         init.SystemRequestFrameBaseAddress.High = 0;
1080         init.SystemRequestFrameBaseAddress.Low = htole32((uint32_t)sc->req_busaddr);
1081         init.ReplyDescriptorPostQueueAddress.High = 0;
1082         init.ReplyDescriptorPostQueueAddress.Low = htole32((uint32_t)sc->post_busaddr);
1083         init.ReplyFreeQueueAddress.High = 0;
1084         init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1085         getmicrotime(&now);
1086         time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1087         init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1088         init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1089
1090         error = mps_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1091         if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1092                 error = ENXIO;
1093
1094         mps_dprint(sc, MPS_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1095         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
1096         return (error);
1097 }
1098
1099 void
1100 mps_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1101 {
1102         bus_addr_t *addr;
1103
1104         addr = arg;
1105         *addr = segs[0].ds_addr;
1106 }
1107
1108 static int
1109 mps_alloc_queues(struct mps_softc *sc)
1110 {
1111         bus_addr_t queues_busaddr;
1112         uint8_t *queues;
1113         int qsize, fqsize, pqsize;
1114
1115         /*
1116          * The reply free queue contains 4 byte entries in multiples of 16 and
1117          * aligned on a 16 byte boundary. There must always be an unused entry.
1118          * This queue supplies fresh reply frames for the firmware to use.
1119          *
1120          * The reply descriptor post queue contains 8 byte entries in
1121          * multiples of 16 and aligned on a 16 byte boundary.  This queue
1122          * contains filled-in reply frames sent from the firmware to the host.
1123          *
1124          * These two queues are allocated together for simplicity.
1125          */
1126         sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1127         sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1128         fqsize= sc->fqdepth * 4;
1129         pqsize = sc->pqdepth * 8;
1130         qsize = fqsize + pqsize;
1131
1132         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1133                                 16, 0,                  /* algnmnt, boundary */
1134                                 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1135                                 BUS_SPACE_MAXADDR,      /* highaddr */
1136                                 NULL, NULL,             /* filter, filterarg */
1137                                 qsize,                  /* maxsize */
1138                                 1,                      /* nsegments */
1139                                 qsize,                  /* maxsegsize */
1140                                 0,                      /* flags */
1141                                 NULL, NULL,             /* lockfunc, lockarg */
1142                                 &sc->queues_dmat)) {
1143                 mps_dprint(sc, MPS_ERROR, "Cannot allocate queues DMA tag\n");
1144                 return (ENOMEM);
1145         }
1146         if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1147             &sc->queues_map)) {
1148                 mps_dprint(sc, MPS_ERROR, "Cannot allocate queues memory\n");
1149                 return (ENOMEM);
1150         }
1151         bzero(queues, qsize);
1152         bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1153             mps_memaddr_cb, &queues_busaddr, 0);
1154
1155         sc->free_queue = (uint32_t *)queues;
1156         sc->free_busaddr = queues_busaddr;
1157         sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1158         sc->post_busaddr = queues_busaddr + fqsize;
1159
1160         return (0);
1161 }
1162
1163 static int
1164 mps_alloc_replies(struct mps_softc *sc)
1165 {
1166         int rsize, num_replies;
1167
1168         /*
1169          * sc->num_replies should be one less than sc->fqdepth.  We need to
1170          * allocate space for sc->fqdepth replies, but only sc->num_replies
1171          * replies can be used at once.
1172          */
1173         num_replies = max(sc->fqdepth, sc->num_replies);
1174
1175         rsize = sc->facts->ReplyFrameSize * num_replies * 4; 
1176         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1177                                 4, 0,                   /* algnmnt, boundary */
1178                                 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1179                                 BUS_SPACE_MAXADDR,      /* highaddr */
1180                                 NULL, NULL,             /* filter, filterarg */
1181                                 rsize,                  /* maxsize */
1182                                 1,                      /* nsegments */
1183                                 rsize,                  /* maxsegsize */
1184                                 0,                      /* flags */
1185                                 NULL, NULL,             /* lockfunc, lockarg */
1186                                 &sc->reply_dmat)) {
1187                 mps_dprint(sc, MPS_ERROR, "Cannot allocate replies DMA tag\n");
1188                 return (ENOMEM);
1189         }
1190         if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1191             BUS_DMA_NOWAIT, &sc->reply_map)) {
1192                 mps_dprint(sc, MPS_ERROR, "Cannot allocate replies memory\n");
1193                 return (ENOMEM);
1194         }
1195         bzero(sc->reply_frames, rsize);
1196         bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1197             mps_memaddr_cb, &sc->reply_busaddr, 0);
1198
1199         return (0);
1200 }
1201
1202 static int
1203 mps_alloc_requests(struct mps_softc *sc)
1204 {
1205         struct mps_command *cm;
1206         struct mps_chain *chain;
1207         int i, rsize, nsegs;
1208
1209         rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
1210         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1211                                 16, 0,                  /* algnmnt, boundary */
1212                                 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1213                                 BUS_SPACE_MAXADDR,      /* highaddr */
1214                                 NULL, NULL,             /* filter, filterarg */
1215                                 rsize,                  /* maxsize */
1216                                 1,                      /* nsegments */
1217                                 rsize,                  /* maxsegsize */
1218                                 0,                      /* flags */
1219                                 NULL, NULL,             /* lockfunc, lockarg */
1220                                 &sc->req_dmat)) {
1221                 mps_dprint(sc, MPS_ERROR, "Cannot allocate request DMA tag\n");
1222                 return (ENOMEM);
1223         }
1224         if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1225             BUS_DMA_NOWAIT, &sc->req_map)) {
1226                 mps_dprint(sc, MPS_ERROR, "Cannot allocate request memory\n");
1227                 return (ENOMEM);
1228         }
1229         bzero(sc->req_frames, rsize);
1230         bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1231             mps_memaddr_cb, &sc->req_busaddr, 0);
1232
1233         rsize = sc->facts->IOCRequestFrameSize * sc->max_chains * 4;
1234         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1235                                 16, 0,                  /* algnmnt, boundary */
1236                                 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1237                                 BUS_SPACE_MAXADDR,      /* highaddr */
1238                                 NULL, NULL,             /* filter, filterarg */
1239                                 rsize,                  /* maxsize */
1240                                 1,                      /* nsegments */
1241                                 rsize,                  /* maxsegsize */
1242                                 0,                      /* flags */
1243                                 NULL, NULL,             /* lockfunc, lockarg */
1244                                 &sc->chain_dmat)) {
1245                 mps_dprint(sc, MPS_ERROR, "Cannot allocate chain DMA tag\n");
1246                 return (ENOMEM);
1247         }
1248         if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1249             BUS_DMA_NOWAIT, &sc->chain_map)) {
1250                 mps_dprint(sc, MPS_ERROR, "Cannot allocate chain memory\n");
1251                 return (ENOMEM);
1252         }
1253         bzero(sc->chain_frames, rsize);
1254         bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1255             mps_memaddr_cb, &sc->chain_busaddr, 0);
1256
1257         rsize = MPS_SENSE_LEN * sc->num_reqs;
1258         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1259                                 1, 0,                   /* algnmnt, boundary */
1260                                 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1261                                 BUS_SPACE_MAXADDR,      /* highaddr */
1262                                 NULL, NULL,             /* filter, filterarg */
1263                                 rsize,                  /* maxsize */
1264                                 1,                      /* nsegments */
1265                                 rsize,                  /* maxsegsize */
1266                                 0,                      /* flags */
1267                                 NULL, NULL,             /* lockfunc, lockarg */
1268                                 &sc->sense_dmat)) {
1269                 mps_dprint(sc, MPS_ERROR, "Cannot allocate sense DMA tag\n");
1270                 return (ENOMEM);
1271         }
1272         if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1273             BUS_DMA_NOWAIT, &sc->sense_map)) {
1274                 mps_dprint(sc, MPS_ERROR, "Cannot allocate sense memory\n");
1275                 return (ENOMEM);
1276         }
1277         bzero(sc->sense_frames, rsize);
1278         bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1279             mps_memaddr_cb, &sc->sense_busaddr, 0);
1280
1281         sc->chains = malloc(sizeof(struct mps_chain) * sc->max_chains, M_MPT2,
1282             M_WAITOK | M_ZERO);
1283         if(!sc->chains) {
1284                 mps_dprint(sc, MPS_ERROR, "Cannot allocate chains memory\n");
1285                 return (ENOMEM);
1286         }
1287         for (i = 0; i < sc->max_chains; i++) {
1288                 chain = &sc->chains[i];
1289                 chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1290                     i * sc->facts->IOCRequestFrameSize * 4);
1291                 chain->chain_busaddr = sc->chain_busaddr +
1292                     i * sc->facts->IOCRequestFrameSize * 4;
1293                 mps_free_chain(sc, chain);
1294                 sc->chain_free_lowwater++;
1295         }
1296
1297         /* XXX Need to pick a more precise value */
1298         nsegs = (MAXPHYS / PAGE_SIZE) + 1;
1299         if (bus_dma_tag_create( sc->mps_parent_dmat,    /* parent */
1300                                 1, 0,                   /* algnmnt, boundary */
1301                                 BUS_SPACE_MAXADDR,      /* lowaddr */
1302                                 BUS_SPACE_MAXADDR,      /* highaddr */
1303                                 NULL, NULL,             /* filter, filterarg */
1304                                 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1305                                 nsegs,                  /* nsegments */
1306                                 BUS_SPACE_MAXSIZE_24BIT,/* maxsegsize */
1307                                 BUS_DMA_ALLOCNOW,       /* flags */
1308                                 busdma_lock_mutex,      /* lockfunc */
1309                                 &sc->mps_mtx,           /* lockarg */
1310                                 &sc->buffer_dmat)) {
1311                 mps_dprint(sc, MPS_ERROR, "Cannot allocate buffer DMA tag\n");
1312                 return (ENOMEM);
1313         }
1314
1315         /*
1316          * SMID 0 cannot be used as a free command per the firmware spec.
1317          * Just drop that command instead of risking accounting bugs.
1318          */
1319         sc->commands = malloc(sizeof(struct mps_command) * sc->num_reqs,
1320             M_MPT2, M_WAITOK | M_ZERO);
1321         if(!sc->commands) {
1322                 mps_dprint(sc, MPS_ERROR, "Cannot allocate command memory\n");
1323                 return (ENOMEM);
1324         }
1325         for (i = 1; i < sc->num_reqs; i++) {
1326                 cm = &sc->commands[i];
1327                 cm->cm_req = sc->req_frames +
1328                     i * sc->facts->IOCRequestFrameSize * 4;
1329                 cm->cm_req_busaddr = sc->req_busaddr +
1330                     i * sc->facts->IOCRequestFrameSize * 4;
1331                 cm->cm_sense = &sc->sense_frames[i];
1332                 cm->cm_sense_busaddr = sc->sense_busaddr + i * MPS_SENSE_LEN;
1333                 cm->cm_desc.Default.SMID = i;
1334                 cm->cm_sc = sc;
1335                 TAILQ_INIT(&cm->cm_chain_list);
1336                 callout_init_mtx(&cm->cm_callout, &sc->mps_mtx, 0);
1337
1338                 /* XXX Is a failure here a critical problem? */
1339                 if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap) == 0)
1340                         if (i <= sc->facts->HighPriorityCredit)
1341                                 mps_free_high_priority_command(sc, cm);
1342                         else
1343                                 mps_free_command(sc, cm);
1344                 else {
1345                         panic("failed to allocate command %d\n", i);
1346                         sc->num_reqs = i;
1347                         break;
1348                 }
1349         }
1350
1351         return (0);
1352 }
1353
1354 static int
1355 mps_init_queues(struct mps_softc *sc)
1356 {
1357         int i;
1358
1359         memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1360
1361         /*
1362          * According to the spec, we need to use one less reply than we
1363          * have space for on the queue.  So sc->num_replies (the number we
1364          * use) should be less than sc->fqdepth (allocated size).
1365          */
1366         if (sc->num_replies >= sc->fqdepth)
1367                 return (EINVAL);
1368
1369         /*
1370          * Initialize all of the free queue entries.
1371          */
1372         for (i = 0; i < sc->fqdepth; i++)
1373                 sc->free_queue[i] = sc->reply_busaddr + (i * sc->facts->ReplyFrameSize * 4);
1374         sc->replyfreeindex = sc->num_replies;
1375
1376         return (0);
1377 }
1378
1379 /* Get the driver parameter tunables.  Lowest priority are the driver defaults.
1380  * Next are the global settings, if they exist.  Highest are the per-unit
1381  * settings, if they exist.
1382  */
1383 void
1384 mps_get_tunables(struct mps_softc *sc)
1385 {
1386         char tmpstr[80];
1387
1388         /* XXX default to some debugging for now */
1389         sc->mps_debug = MPS_INFO|MPS_FAULT;
1390         sc->disable_msix = 0;
1391         sc->disable_msi = 0;
1392         sc->max_chains = MPS_CHAIN_FRAMES;
1393         sc->max_io_pages = MPS_MAXIO_PAGES;
1394         sc->enable_ssu = MPS_SSU_ENABLE_SSD_DISABLE_HDD;
1395         sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1396         sc->use_phynum = 1;
1397
1398         /*
1399          * Grab the global variables.
1400          */
1401         TUNABLE_INT_FETCH("hw.mps.debug_level", &sc->mps_debug);
1402         TUNABLE_INT_FETCH("hw.mps.disable_msix", &sc->disable_msix);
1403         TUNABLE_INT_FETCH("hw.mps.disable_msi", &sc->disable_msi);
1404         TUNABLE_INT_FETCH("hw.mps.max_chains", &sc->max_chains);
1405         TUNABLE_INT_FETCH("hw.mps.max_io_pages", &sc->max_io_pages);
1406         TUNABLE_INT_FETCH("hw.mps.enable_ssu", &sc->enable_ssu);
1407         TUNABLE_INT_FETCH("hw.mps.spinup_wait_time", &sc->spinup_wait_time);
1408         TUNABLE_INT_FETCH("hw.mps.use_phy_num", &sc->use_phynum);
1409
1410         /* Grab the unit-instance variables */
1411         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.debug_level",
1412             device_get_unit(sc->mps_dev));
1413         TUNABLE_INT_FETCH(tmpstr, &sc->mps_debug);
1414
1415         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msix",
1416             device_get_unit(sc->mps_dev));
1417         TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1418
1419         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.disable_msi",
1420             device_get_unit(sc->mps_dev));
1421         TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1422
1423         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_chains",
1424             device_get_unit(sc->mps_dev));
1425         TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1426
1427         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.max_io_pages",
1428             device_get_unit(sc->mps_dev));
1429         TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1430
1431         bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1432         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.exclude_ids",
1433             device_get_unit(sc->mps_dev));
1434         TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1435
1436         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.enable_ssu",
1437             device_get_unit(sc->mps_dev));
1438         TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1439
1440         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.spinup_wait_time",
1441             device_get_unit(sc->mps_dev));
1442         TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1443
1444         snprintf(tmpstr, sizeof(tmpstr), "dev.mps.%d.use_phy_num",
1445             device_get_unit(sc->mps_dev));
1446         TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1447 }
1448
1449 static void
1450 mps_setup_sysctl(struct mps_softc *sc)
1451 {
1452         struct sysctl_ctx_list  *sysctl_ctx = NULL;
1453         struct sysctl_oid       *sysctl_tree = NULL;
1454         char tmpstr[80], tmpstr2[80];
1455
1456         /*
1457          * Setup the sysctl variable so the user can change the debug level
1458          * on the fly.
1459          */
1460         snprintf(tmpstr, sizeof(tmpstr), "MPS controller %d",
1461             device_get_unit(sc->mps_dev));
1462         snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mps_dev));
1463
1464         sysctl_ctx = device_get_sysctl_ctx(sc->mps_dev);
1465         if (sysctl_ctx != NULL)
1466                 sysctl_tree = device_get_sysctl_tree(sc->mps_dev);
1467
1468         if (sysctl_tree == NULL) {
1469                 sysctl_ctx_init(&sc->sysctl_ctx);
1470                 sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1471                     SYSCTL_STATIC_CHILDREN(_hw_mps), OID_AUTO, tmpstr2,
1472                     CTLFLAG_RD, 0, tmpstr);
1473                 if (sc->sysctl_tree == NULL)
1474                         return;
1475                 sysctl_ctx = &sc->sysctl_ctx;
1476                 sysctl_tree = sc->sysctl_tree;
1477         }
1478
1479         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1480             OID_AUTO, "debug_level", CTLFLAG_RW, &sc->mps_debug, 0,
1481             "mps debug level");
1482
1483         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1484             OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1485             "Disable the use of MSI-X interrupts");
1486
1487         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1488             OID_AUTO, "disable_msi", CTLFLAG_RD, &sc->disable_msi, 0,
1489             "Disable the use of MSI interrupts");
1490
1491         SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1492             OID_AUTO, "firmware_version", CTLFLAG_RW, sc->fw_version,
1493             strlen(sc->fw_version), "firmware version");
1494
1495         SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1496             OID_AUTO, "driver_version", CTLFLAG_RW, MPS_DRIVER_VERSION,
1497             strlen(MPS_DRIVER_VERSION), "driver version");
1498
1499         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1500             OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1501             &sc->io_cmds_active, 0, "number of currently active commands");
1502
1503         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1504             OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1505             &sc->io_cmds_highwater, 0, "maximum active commands seen");
1506
1507         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1508             OID_AUTO, "chain_free", CTLFLAG_RD,
1509             &sc->chain_free, 0, "number of free chain elements");
1510
1511         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1512             OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1513             &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1514
1515         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1516             OID_AUTO, "max_chains", CTLFLAG_RD,
1517             &sc->max_chains, 0,"maximum chain frames that will be allocated");
1518
1519         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1520             OID_AUTO, "max_io_pages", CTLFLAG_RD,
1521             &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1522             "IOCFacts)");
1523
1524         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1525             OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1526             "enable SSU to SATA SSD/HDD at shutdown");
1527
1528         SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1529             OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1530             &sc->chain_alloc_fail, "chain allocation failures");
1531
1532         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1533             OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1534             &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1535             "spinup after SATA ID error");
1536
1537         SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1538             OID_AUTO, "mapping_table_dump", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
1539             mps_mapping_dump, "A", "Mapping Table Dump");
1540
1541         SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1542             OID_AUTO, "encl_table_dump", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
1543             mps_mapping_encl_dump, "A", "Enclosure Table Dump");
1544
1545         SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1546             OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1547             "Use the phy number for enumeration");
1548 }
1549
1550 int
1551 mps_attach(struct mps_softc *sc)
1552 {
1553         int error;
1554
1555         MPS_FUNCTRACE(sc);
1556         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1557
1558         mtx_init(&sc->mps_mtx, "MPT2SAS lock", NULL, MTX_DEF);
1559         callout_init_mtx(&sc->periodic, &sc->mps_mtx, 0);
1560         callout_init_mtx(&sc->device_check_callout, &sc->mps_mtx, 0);
1561         TAILQ_INIT(&sc->event_list);
1562         timevalclear(&sc->lastfail);
1563
1564         if ((error = mps_transition_ready(sc)) != 0) {
1565                 mps_dprint(sc, MPS_INIT|MPS_FAULT, "failed to transition "
1566                     "ready\n");
1567                 return (error);
1568         }
1569
1570         sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPT2,
1571             M_ZERO|M_NOWAIT);
1572         if(!sc->facts) {
1573                 mps_dprint(sc, MPS_INIT|MPS_FAULT, "Cannot allocate memory, "
1574                     "exit\n");
1575                 return (ENOMEM);
1576         }
1577
1578         /*
1579          * Get IOC Facts and allocate all structures based on this information.
1580          * A Diag Reset will also call mps_iocfacts_allocate and re-read the IOC
1581          * Facts. If relevant values have changed in IOC Facts, this function
1582          * will free all of the memory based on IOC Facts and reallocate that
1583          * memory.  If this fails, any allocated memory should already be freed.
1584          */
1585         if ((error = mps_iocfacts_allocate(sc, TRUE)) != 0) {
1586                 mps_dprint(sc, MPS_INIT|MPS_FAULT, "IOC Facts based allocation "
1587                     "failed with error %d, exit\n", error);
1588                 return (error);
1589         }
1590
1591         /* Start the periodic watchdog check on the IOC Doorbell */
1592         mps_periodic(sc);
1593
1594         /*
1595          * The portenable will kick off discovery events that will drive the
1596          * rest of the initialization process.  The CAM/SAS module will
1597          * hold up the boot sequence until discovery is complete.
1598          */
1599         sc->mps_ich.ich_func = mps_startup;
1600         sc->mps_ich.ich_arg = sc;
1601         if (config_intrhook_establish(&sc->mps_ich) != 0) {
1602                 mps_dprint(sc, MPS_INIT|MPS_ERROR,
1603                     "Cannot establish MPS config hook\n");
1604                 error = EINVAL;
1605         }
1606
1607         /*
1608          * Allow IR to shutdown gracefully when shutdown occurs.
1609          */
1610         sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
1611             mpssas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
1612
1613         if (sc->shutdown_eh == NULL)
1614                 mps_dprint(sc, MPS_INIT|MPS_ERROR,
1615                     "shutdown event registration failed\n");
1616
1617         mps_setup_sysctl(sc);
1618
1619         sc->mps_flags |= MPS_FLAGS_ATTACH_DONE;
1620         mps_dprint(sc, MPS_INIT, "%s exit error= %d\n", __func__, error);
1621
1622         return (error);
1623 }
1624
1625 /* Run through any late-start handlers. */
1626 static void
1627 mps_startup(void *arg)
1628 {
1629         struct mps_softc *sc;
1630
1631         sc = (struct mps_softc *)arg;
1632         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1633
1634         mps_lock(sc);
1635         mps_unmask_intr(sc);
1636
1637         /* initialize device mapping tables */
1638         mps_base_static_config_pages(sc);
1639         mps_mapping_initialize(sc);
1640         mpssas_startup(sc);
1641         mps_unlock(sc);
1642         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
1643 }
1644
1645 /* Periodic watchdog.  Is called with the driver lock already held. */
1646 static void
1647 mps_periodic(void *arg)
1648 {
1649         struct mps_softc *sc;
1650         uint32_t db;
1651
1652         sc = (struct mps_softc *)arg;
1653         if (sc->mps_flags & MPS_FLAGS_SHUTDOWN)
1654                 return;
1655
1656         db = mps_regread(sc, MPI2_DOORBELL_OFFSET);
1657         if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
1658                 mps_dprint(sc, MPS_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
1659                 mps_reinit(sc);
1660         }
1661
1662         callout_reset(&sc->periodic, MPS_PERIODIC_DELAY * hz, mps_periodic, sc);
1663 }
1664
1665 static void
1666 mps_log_evt_handler(struct mps_softc *sc, uintptr_t data,
1667     MPI2_EVENT_NOTIFICATION_REPLY *event)
1668 {
1669         MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
1670
1671         MPS_DPRINT_EVENT(sc, generic, event);
1672
1673         switch (event->Event) {
1674         case MPI2_EVENT_LOG_DATA:
1675                 mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_DATA:\n");
1676                 if (sc->mps_debug & MPS_EVENT)
1677                         hexdump(event->EventData, event->EventDataLength, NULL, 0);
1678                 break;
1679         case MPI2_EVENT_LOG_ENTRY_ADDED:
1680                 entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
1681                 mps_dprint(sc, MPS_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
1682                     "0x%x Sequence %d:\n", entry->LogEntryQualifier,
1683                      entry->LogSequence);
1684                 break;
1685         default:
1686                 break;
1687         }
1688         return;
1689 }
1690
1691 static int
1692 mps_attach_log(struct mps_softc *sc)
1693 {
1694         u32 events[MPI2_EVENT_NOTIFY_EVENTMASK_WORDS];
1695
1696         bzero(events, 16);
1697         setbit(events, MPI2_EVENT_LOG_DATA);
1698         setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
1699
1700         mps_register_events(sc, events, mps_log_evt_handler, NULL,
1701             &sc->mps_log_eh);
1702
1703         return (0);
1704 }
1705
1706 static int
1707 mps_detach_log(struct mps_softc *sc)
1708 {
1709
1710         if (sc->mps_log_eh != NULL)
1711                 mps_deregister_events(sc, sc->mps_log_eh);
1712         return (0);
1713 }
1714
1715 /*
1716  * Free all of the driver resources and detach submodules.  Should be called
1717  * without the lock held.
1718  */
1719 int
1720 mps_free(struct mps_softc *sc)
1721 {
1722         int error;
1723
1724         mps_dprint(sc, MPS_INIT, "%s entered\n", __func__);
1725         /* Turn off the watchdog */
1726         mps_lock(sc);
1727         sc->mps_flags |= MPS_FLAGS_SHUTDOWN;
1728         mps_unlock(sc);
1729         /* Lock must not be held for this */
1730         callout_drain(&sc->periodic);
1731         callout_drain(&sc->device_check_callout);
1732
1733         if (((error = mps_detach_log(sc)) != 0) ||
1734             ((error = mps_detach_sas(sc)) != 0)) {
1735                 mps_dprint(sc, MPS_INIT|MPS_FAULT, "failed to detach "
1736                     "subsystems, exit\n");
1737                 return (error);
1738         }
1739
1740         mps_detach_user(sc);
1741
1742         /* Put the IOC back in the READY state. */
1743         mps_lock(sc);
1744         if ((error = mps_transition_ready(sc)) != 0) {
1745                 mps_unlock(sc);
1746                 return (error);
1747         }
1748         mps_unlock(sc);
1749
1750         if (sc->facts != NULL)
1751                 free(sc->facts, M_MPT2);
1752
1753         /*
1754          * Free all buffers that are based on IOC Facts.  A Diag Reset may need
1755          * to free these buffers too.
1756          */
1757         mps_iocfacts_free(sc);
1758
1759         if (sc->sysctl_tree != NULL)
1760                 sysctl_ctx_free(&sc->sysctl_ctx);
1761
1762         /* Deregister the shutdown function */
1763         if (sc->shutdown_eh != NULL)
1764                 EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
1765
1766         mtx_destroy(&sc->mps_mtx);
1767         mps_dprint(sc, MPS_INIT, "%s exit\n", __func__);
1768
1769         return (0);
1770 }
1771
1772 static __inline void
1773 mps_complete_command(struct mps_softc *sc, struct mps_command *cm)
1774 {
1775         MPS_FUNCTRACE(sc);
1776
1777         if (cm == NULL) {
1778                 mps_dprint(sc, MPS_ERROR, "Completing NULL command\n");
1779                 return;
1780         }
1781
1782         if (cm->cm_flags & MPS_CM_FLAGS_POLLED)
1783                 cm->cm_flags |= MPS_CM_FLAGS_COMPLETE;
1784
1785         if (cm->cm_complete != NULL) {
1786                 mps_dprint(sc, MPS_TRACE,
1787                            "%s cm %p calling cm_complete %p data %p reply %p\n",
1788                            __func__, cm, cm->cm_complete, cm->cm_complete_data,
1789                            cm->cm_reply);
1790                 cm->cm_complete(sc, cm);
1791         }
1792
1793         if (cm->cm_flags & MPS_CM_FLAGS_WAKEUP) {
1794                 mps_dprint(sc, MPS_TRACE, "waking up %p\n", cm);
1795                 wakeup(cm);
1796         }
1797
1798         if (cm->cm_sc->io_cmds_active != 0) {
1799                 cm->cm_sc->io_cmds_active--;
1800         } else {
1801                 mps_dprint(sc, MPS_ERROR, "Warning: io_cmds_active is "
1802                     "out of sync - resynching to 0\n");
1803         }
1804 }
1805
1806
1807 static void
1808 mps_sas_log_info(struct mps_softc *sc , u32 log_info)
1809 {
1810         union loginfo_type {
1811                 u32     loginfo;
1812                 struct {
1813                         u32     subcode:16;
1814                         u32     code:8;
1815                         u32     originator:4;
1816                         u32     bus_type:4;
1817                 } dw;
1818         };
1819         union loginfo_type sas_loginfo;
1820         char *originator_str = NULL;
1821
1822         sas_loginfo.loginfo = log_info;
1823         if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
1824                 return;
1825
1826         /* each nexus loss loginfo */
1827         if (log_info == 0x31170000)
1828                 return;
1829
1830         /* eat the loginfos associated with task aborts */
1831         if ((log_info == 30050000 || log_info ==
1832             0x31140000 || log_info == 0x31130000))
1833                 return;
1834
1835         switch (sas_loginfo.dw.originator) {
1836         case 0:
1837                 originator_str = "IOP";
1838                 break;
1839         case 1:
1840                 originator_str = "PL";
1841                 break;
1842         case 2:
1843                 originator_str = "IR";
1844                 break;
1845 }
1846
1847         mps_dprint(sc, MPS_LOG, "log_info(0x%08x): originator(%s), "
1848         "code(0x%02x), sub_code(0x%04x)\n", log_info,
1849         originator_str, sas_loginfo.dw.code,
1850         sas_loginfo.dw.subcode);
1851 }
1852
1853 static void
1854 mps_display_reply_info(struct mps_softc *sc, uint8_t *reply)
1855 {
1856         MPI2DefaultReply_t *mpi_reply;
1857         u16 sc_status;
1858
1859         mpi_reply = (MPI2DefaultReply_t*)reply;
1860         sc_status = le16toh(mpi_reply->IOCStatus);
1861         if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
1862                 mps_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
1863 }
1864 void
1865 mps_intr(void *data)
1866 {
1867         struct mps_softc *sc;
1868         uint32_t status;
1869
1870         sc = (struct mps_softc *)data;
1871         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1872
1873         /*
1874          * Check interrupt status register to flush the bus.  This is
1875          * needed for both INTx interrupts and driver-driven polling
1876          */
1877         status = mps_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
1878         if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
1879                 return;
1880
1881         mps_lock(sc);
1882         mps_intr_locked(data);
1883         mps_unlock(sc);
1884         return;
1885 }
1886
1887 /*
1888  * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
1889  * chip.  Hopefully this theory is correct.
1890  */
1891 void
1892 mps_intr_msi(void *data)
1893 {
1894         struct mps_softc *sc;
1895
1896         sc = (struct mps_softc *)data;
1897         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
1898         mps_lock(sc);
1899         mps_intr_locked(data);
1900         mps_unlock(sc);
1901         return;
1902 }
1903
1904 /*
1905  * The locking is overly broad and simplistic, but easy to deal with for now.
1906  */
1907 void
1908 mps_intr_locked(void *data)
1909 {
1910         MPI2_REPLY_DESCRIPTORS_UNION *desc;
1911         struct mps_softc *sc;
1912         struct mps_command *cm = NULL;
1913         uint8_t flags;
1914         u_int pq;
1915         MPI2_DIAG_RELEASE_REPLY *rel_rep;
1916         mps_fw_diagnostic_buffer_t *pBuffer;
1917
1918         sc = (struct mps_softc *)data;
1919
1920         pq = sc->replypostindex;
1921         mps_dprint(sc, MPS_TRACE,
1922             "%s sc %p starting with replypostindex %u\n", 
1923             __func__, sc, sc->replypostindex);
1924
1925         for ( ;; ) {
1926                 cm = NULL;
1927                 desc = &sc->post_queue[sc->replypostindex];
1928                 flags = desc->Default.ReplyFlags &
1929                     MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
1930                 if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED)
1931                  || (le32toh(desc->Words.High) == 0xffffffff))
1932                         break;
1933
1934                 /* increment the replypostindex now, so that event handlers
1935                  * and cm completion handlers which decide to do a diag
1936                  * reset can zero it without it getting incremented again
1937                  * afterwards, and we break out of this loop on the next
1938                  * iteration since the reply post queue has been cleared to
1939                  * 0xFF and all descriptors look unused (which they are).
1940                  */
1941                 if (++sc->replypostindex >= sc->pqdepth)
1942                         sc->replypostindex = 0;
1943
1944                 switch (flags) {
1945                 case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
1946                         cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
1947                         cm->cm_reply = NULL;
1948                         break;
1949                 case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
1950                 {
1951                         uint32_t baddr;
1952                         uint8_t *reply;
1953
1954                         /*
1955                          * Re-compose the reply address from the address
1956                          * sent back from the chip.  The ReplyFrameAddress
1957                          * is the lower 32 bits of the physical address of
1958                          * particular reply frame.  Convert that address to
1959                          * host format, and then use that to provide the
1960                          * offset against the virtual address base
1961                          * (sc->reply_frames).
1962                          */
1963                         baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
1964                         reply = sc->reply_frames +
1965                                 (baddr - ((uint32_t)sc->reply_busaddr));
1966                         /*
1967                          * Make sure the reply we got back is in a valid
1968                          * range.  If not, go ahead and panic here, since
1969                          * we'll probably panic as soon as we deference the
1970                          * reply pointer anyway.
1971                          */
1972                         if ((reply < sc->reply_frames)
1973                          || (reply > (sc->reply_frames +
1974                              (sc->fqdepth * sc->facts->ReplyFrameSize * 4)))) {
1975                                 printf("%s: WARNING: reply %p out of range!\n",
1976                                        __func__, reply);
1977                                 printf("%s: reply_frames %p, fqdepth %d, "
1978                                        "frame size %d\n", __func__,
1979                                        sc->reply_frames, sc->fqdepth,
1980                                        sc->facts->ReplyFrameSize * 4);
1981                                 printf("%s: baddr %#x,\n", __func__, baddr);
1982                                 /* LSI-TODO. See Linux Code. Need Graceful exit*/
1983                                 panic("Reply address out of range");
1984                         }
1985                         if (le16toh(desc->AddressReply.SMID) == 0) {
1986                                 if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
1987                                     MPI2_FUNCTION_DIAG_BUFFER_POST) {
1988                                         /*
1989                                          * If SMID is 0 for Diag Buffer Post,
1990                                          * this implies that the reply is due to
1991                                          * a release function with a status that
1992                                          * the buffer has been released.  Set
1993                                          * the buffer flags accordingly.
1994                                          */
1995                                         rel_rep =
1996                                             (MPI2_DIAG_RELEASE_REPLY *)reply;
1997                                         if ((le16toh(rel_rep->IOCStatus) &
1998                                             MPI2_IOCSTATUS_MASK) ==
1999                                             MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2000                                         {
2001                                                 pBuffer =
2002                                                     &sc->fw_diag_buffer_list[
2003                                                     rel_rep->BufferType];
2004                                                 pBuffer->valid_data = TRUE;
2005                                                 pBuffer->owned_by_firmware =
2006                                                     FALSE;
2007                                                 pBuffer->immediate = FALSE;
2008                                         }
2009                                 } else
2010                                         mps_dispatch_event(sc, baddr,
2011                                             (MPI2_EVENT_NOTIFICATION_REPLY *)
2012                                             reply);
2013                         } else {
2014                                 cm = &sc->commands[le16toh(desc->AddressReply.SMID)];
2015                                 cm->cm_reply = reply;
2016                                 cm->cm_reply_data =
2017                                     le32toh(desc->AddressReply.ReplyFrameAddress);
2018                         }
2019                         break;
2020                 }
2021                 case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2022                 case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2023                 case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2024                 default:
2025                         /* Unhandled */
2026                         mps_dprint(sc, MPS_ERROR, "Unhandled reply 0x%x\n",
2027                             desc->Default.ReplyFlags);
2028                         cm = NULL;
2029                         break;
2030                 }
2031                 
2032
2033                 if (cm != NULL) {
2034                         // Print Error reply frame
2035                         if (cm->cm_reply)
2036                                 mps_display_reply_info(sc,cm->cm_reply);
2037                         mps_complete_command(sc, cm);
2038                 }
2039
2040                 desc->Words.Low = 0xffffffff;
2041                 desc->Words.High = 0xffffffff;
2042         }
2043
2044         if (pq != sc->replypostindex) {
2045                 mps_dprint(sc, MPS_TRACE,
2046                     "%s sc %p writing postindex %d\n",
2047                     __func__, sc, sc->replypostindex);
2048                 mps_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, sc->replypostindex);
2049         }
2050
2051         return;
2052 }
2053
2054 static void
2055 mps_dispatch_event(struct mps_softc *sc, uintptr_t data,
2056     MPI2_EVENT_NOTIFICATION_REPLY *reply)
2057 {
2058         struct mps_event_handle *eh;
2059         int event, handled = 0;
2060
2061         event = le16toh(reply->Event);
2062         TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2063                 if (isset(eh->mask, event)) {
2064                         eh->callback(sc, data, reply);
2065                         handled++;
2066                 }
2067         }
2068
2069         if (handled == 0)
2070                 mps_dprint(sc, MPS_EVENT, "Unhandled event 0x%x\n", le16toh(event));
2071
2072         /*
2073          * This is the only place that the event/reply should be freed.
2074          * Anything wanting to hold onto the event data should have
2075          * already copied it into their own storage.
2076          */
2077         mps_free_reply(sc, data);
2078 }
2079
2080 static void
2081 mps_reregister_events_complete(struct mps_softc *sc, struct mps_command *cm)
2082 {
2083         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2084
2085         if (cm->cm_reply)
2086                 MPS_DPRINT_EVENT(sc, generic,
2087                         (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2088
2089         mps_free_command(sc, cm);
2090
2091         /* next, send a port enable */
2092         mpssas_startup(sc);
2093 }
2094
2095 /*
2096  * For both register_events and update_events, the caller supplies a bitmap
2097  * of events that it _wants_.  These functions then turn that into a bitmask
2098  * suitable for the controller.
2099  */
2100 int
2101 mps_register_events(struct mps_softc *sc, u32 *mask,
2102     mps_evt_callback_t *cb, void *data, struct mps_event_handle **handle)
2103 {
2104         struct mps_event_handle *eh;
2105         int error = 0;
2106
2107         eh = malloc(sizeof(struct mps_event_handle), M_MPT2, M_WAITOK|M_ZERO);
2108         if(!eh) {
2109                 mps_dprint(sc, MPS_ERROR, "Cannot allocate event memory\n");
2110                 return (ENOMEM);
2111         }
2112         eh->callback = cb;
2113         eh->data = data;
2114         TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2115         if (mask != NULL)
2116                 error = mps_update_events(sc, eh, mask);
2117         *handle = eh;
2118
2119         return (error);
2120 }
2121
2122 int
2123 mps_update_events(struct mps_softc *sc, struct mps_event_handle *handle,
2124     u32 *mask)
2125 {
2126         MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2127         MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2128         struct mps_command *cm;
2129         int error, i;
2130
2131         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2132
2133         if ((mask != NULL) && (handle != NULL))
2134                 bcopy(mask, &handle->mask[0], sizeof(u32) * 
2135                                 MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2136     
2137         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2138                 sc->event_mask[i] = -1;
2139
2140         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2141                 sc->event_mask[i] &= ~handle->mask[i];
2142
2143
2144         if ((cm = mps_alloc_command(sc)) == NULL)
2145                 return (EBUSY);
2146         evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2147         evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2148         evtreq->MsgFlags = 0;
2149         evtreq->SASBroadcastPrimitiveMasks = 0;
2150 #ifdef MPS_DEBUG_ALL_EVENTS
2151         {
2152                 u_char fullmask[16];
2153                 memset(fullmask, 0x00, 16);
2154                 bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) * 
2155                                 MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2156         }
2157 #else
2158         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2159                 evtreq->EventMasks[i] =
2160                     htole32(sc->event_mask[i]);
2161 #endif
2162         cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2163         cm->cm_data = NULL;
2164
2165         error = mps_wait_command(sc, &cm, 60, 0);
2166         if (cm != NULL)
2167                 reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2168         if ((reply == NULL) ||
2169             (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2170                 error = ENXIO;
2171
2172         if (reply)
2173                 MPS_DPRINT_EVENT(sc, generic, reply);
2174
2175         mps_dprint(sc, MPS_TRACE, "%s finished error %d\n", __func__, error);
2176
2177         if (cm != NULL)
2178                 mps_free_command(sc, cm);
2179         return (error);
2180 }
2181
2182 static int
2183 mps_reregister_events(struct mps_softc *sc)
2184 {
2185         MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2186         struct mps_command *cm;
2187         struct mps_event_handle *eh;
2188         int error, i;
2189
2190         mps_dprint(sc, MPS_TRACE, "%s\n", __func__);
2191
2192         /* first, reregister events */
2193
2194         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2195                 sc->event_mask[i] = -1;
2196
2197         TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2198                 for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2199                         sc->event_mask[i] &= ~eh->mask[i];
2200         }
2201
2202         if ((cm = mps_alloc_command(sc)) == NULL)
2203                 return (EBUSY);
2204         evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2205         evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2206         evtreq->MsgFlags = 0;
2207         evtreq->SASBroadcastPrimitiveMasks = 0;
2208 #ifdef MPS_DEBUG_ALL_EVENTS
2209         {
2210                 u_char fullmask[16];
2211                 memset(fullmask, 0x00, 16);
2212                 bcopy(fullmask, &evtreq->EventMasks[0], sizeof(u32) *
2213                         MPI2_EVENT_NOTIFY_EVENTMASK_WORDS);
2214         }
2215 #else
2216         for (i = 0; i < MPI2_EVENT_NOTIFY_EVENTMASK_WORDS; i++)
2217                 evtreq->EventMasks[i] =
2218                     htole32(sc->event_mask[i]);
2219 #endif
2220         cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2221         cm->cm_data = NULL;
2222         cm->cm_complete = mps_reregister_events_complete;
2223
2224         error = mps_map_command(sc, cm);
2225
2226         mps_dprint(sc, MPS_TRACE, "%s finished with error %d\n", __func__,
2227             error);
2228         return (error);
2229 }
2230
2231 void
2232 mps_deregister_events(struct mps_softc *sc, struct mps_event_handle *handle)
2233 {
2234
2235         TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2236         free(handle, M_MPT2);
2237 }
2238
2239 /*
2240  * Add a chain element as the next SGE for the specified command.
2241  * Reset cm_sge and cm_sgesize to indicate all the available space.
2242  */
2243 static int
2244 mps_add_chain(struct mps_command *cm)
2245 {
2246         MPI2_SGE_CHAIN32 *sgc;
2247         struct mps_chain *chain;
2248         int space;
2249
2250         if (cm->cm_sglsize < MPS_SGC_SIZE)
2251                 panic("MPS: Need SGE Error Code\n");
2252
2253         chain = mps_alloc_chain(cm->cm_sc);
2254         if (chain == NULL)
2255                 return (ENOBUFS);
2256
2257         space = (int)cm->cm_sc->facts->IOCRequestFrameSize * 4;
2258
2259         /*
2260          * Note: a double-linked list is used to make it easier to
2261          * walk for debugging.
2262          */
2263         TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
2264
2265         sgc = (MPI2_SGE_CHAIN32 *)&cm->cm_sge->MpiChain;
2266         sgc->Length = htole16(space);
2267         sgc->NextChainOffset = 0;
2268         /* TODO Looks like bug in Setting sgc->Flags. 
2269          *      sgc->Flags = ( MPI2_SGE_FLAGS_CHAIN_ELEMENT | MPI2_SGE_FLAGS_64_BIT_ADDRESSING |
2270          *                  MPI2_SGE_FLAGS_SYSTEM_ADDRESS) << MPI2_SGE_FLAGS_SHIFT
2271          *      This is fine.. because we are not using simple element. In case of 
2272          *      MPI2_SGE_CHAIN32, we have separate Length and Flags feild.
2273          */
2274         sgc->Flags = MPI2_SGE_FLAGS_CHAIN_ELEMENT;
2275         sgc->Address = htole32(chain->chain_busaddr);
2276
2277         cm->cm_sge = (MPI2_SGE_IO_UNION *)&chain->chain->MpiSimple;
2278         cm->cm_sglsize = space;
2279         return (0);
2280 }
2281
2282 /*
2283  * Add one scatter-gather element (chain, simple, transaction context)
2284  * to the scatter-gather list for a command.  Maintain cm_sglsize and
2285  * cm_sge as the remaining size and pointer to the next SGE to fill
2286  * in, respectively.
2287  */
2288 int
2289 mps_push_sge(struct mps_command *cm, void *sgep, size_t len, int segsleft)
2290 {
2291         MPI2_SGE_TRANSACTION_UNION *tc = sgep;
2292         MPI2_SGE_SIMPLE64 *sge = sgep;
2293         int error, type;
2294         uint32_t saved_buf_len, saved_address_low, saved_address_high;
2295
2296         type = (tc->Flags & MPI2_SGE_FLAGS_ELEMENT_MASK);
2297
2298 #ifdef INVARIANTS
2299         switch (type) {
2300         case MPI2_SGE_FLAGS_TRANSACTION_ELEMENT: {
2301                 if (len != tc->DetailsLength + 4)
2302                         panic("TC %p length %u or %zu?", tc,
2303                             tc->DetailsLength + 4, len);
2304                 }
2305                 break;
2306         case MPI2_SGE_FLAGS_CHAIN_ELEMENT:
2307                 /* Driver only uses 32-bit chain elements */
2308                 if (len != MPS_SGC_SIZE)
2309                         panic("CHAIN %p length %u or %zu?", sgep,
2310                             MPS_SGC_SIZE, len);
2311                 break;
2312         case MPI2_SGE_FLAGS_SIMPLE_ELEMENT:
2313                 /* Driver only uses 64-bit SGE simple elements */
2314                 if (len != MPS_SGE64_SIZE)
2315                         panic("SGE simple %p length %u or %zu?", sge,
2316                             MPS_SGE64_SIZE, len);
2317                 if (((le32toh(sge->FlagsLength) >> MPI2_SGE_FLAGS_SHIFT) &
2318                     MPI2_SGE_FLAGS_ADDRESS_SIZE) == 0)
2319                         panic("SGE simple %p not marked 64-bit?", sge);
2320
2321                 break;
2322         default:
2323                 panic("Unexpected SGE %p, flags %02x", tc, tc->Flags);
2324         }
2325 #endif
2326
2327         /*
2328          * case 1: 1 more segment, enough room for it
2329          * case 2: 2 more segments, enough room for both
2330          * case 3: >=2 more segments, only enough room for 1 and a chain
2331          * case 4: >=1 more segment, enough room for only a chain
2332          * case 5: >=1 more segment, no room for anything (error)
2333          */
2334
2335         /*
2336          * There should be room for at least a chain element, or this
2337          * code is buggy.  Case (5).
2338          */
2339         if (cm->cm_sglsize < MPS_SGC_SIZE)
2340                 panic("MPS: Need SGE Error Code\n");
2341
2342         if (segsleft >= 2 &&
2343             cm->cm_sglsize < len + MPS_SGC_SIZE + MPS_SGE64_SIZE) {
2344                 /*
2345                  * There are 2 or more segments left to add, and only
2346                  * enough room for 1 and a chain.  Case (3).
2347                  *
2348                  * Mark as last element in this chain if necessary.
2349                  */
2350                 if (type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2351                         sge->FlagsLength |= htole32(
2352                             MPI2_SGE_FLAGS_LAST_ELEMENT << MPI2_SGE_FLAGS_SHIFT);
2353                 }
2354
2355                 /*
2356                  * Add the item then a chain.  Do the chain now,
2357                  * rather than on the next iteration, to simplify
2358                  * understanding the code.
2359                  */
2360                 cm->cm_sglsize -= len;
2361                 bcopy(sgep, cm->cm_sge, len);
2362                 cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2363                 return (mps_add_chain(cm));
2364         }
2365
2366         if (segsleft >= 1 && cm->cm_sglsize < len + MPS_SGC_SIZE) {
2367                 /*
2368                  * 1 or more segment, enough room for only a chain.
2369                  * Hope the previous element wasn't a Simple entry
2370                  * that needed to be marked with
2371                  * MPI2_SGE_FLAGS_LAST_ELEMENT.  Case (4).
2372                  */
2373                 if ((error = mps_add_chain(cm)) != 0)
2374                         return (error);
2375         }
2376
2377 #ifdef INVARIANTS
2378         /* Case 1: 1 more segment, enough room for it. */
2379         if (segsleft == 1 && cm->cm_sglsize < len)
2380                 panic("1 seg left and no room? %u versus %zu",
2381                     cm->cm_sglsize, len);
2382
2383         /* Case 2: 2 more segments, enough room for both */
2384         if (segsleft == 2 && cm->cm_sglsize < len + MPS_SGE64_SIZE)
2385                 panic("2 segs left and no room? %u versus %zu",
2386                     cm->cm_sglsize, len);
2387 #endif
2388
2389         if (segsleft == 1 && type == MPI2_SGE_FLAGS_SIMPLE_ELEMENT) {
2390                 /*
2391                  * If this is a bi-directional request, need to account for that
2392                  * here.  Save the pre-filled sge values.  These will be used
2393                  * either for the 2nd SGL or for a single direction SGL.  If
2394                  * cm_out_len is non-zero, this is a bi-directional request, so
2395                  * fill in the OUT SGL first, then the IN SGL, otherwise just
2396                  * fill in the IN SGL.  Note that at this time, when filling in
2397                  * 2 SGL's for a bi-directional request, they both use the same
2398                  * DMA buffer (same cm command).
2399                  */
2400                 saved_buf_len = le32toh(sge->FlagsLength) & 0x00FFFFFF;
2401                 saved_address_low = sge->Address.Low;
2402                 saved_address_high = sge->Address.High;
2403                 if (cm->cm_out_len) {
2404                         sge->FlagsLength = htole32(cm->cm_out_len |
2405                             ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2406                             MPI2_SGE_FLAGS_END_OF_BUFFER |
2407                             MPI2_SGE_FLAGS_HOST_TO_IOC |
2408                             MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2409                             MPI2_SGE_FLAGS_SHIFT));
2410                         cm->cm_sglsize -= len;
2411                         bcopy(sgep, cm->cm_sge, len);
2412                         cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge
2413                             + len);
2414                 }
2415                 saved_buf_len |=
2416                     ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2417                     MPI2_SGE_FLAGS_END_OF_BUFFER |
2418                     MPI2_SGE_FLAGS_LAST_ELEMENT |
2419                     MPI2_SGE_FLAGS_END_OF_LIST |
2420                     MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
2421                     MPI2_SGE_FLAGS_SHIFT);
2422                 if (cm->cm_flags & MPS_CM_FLAGS_DATAIN) {
2423                         saved_buf_len |=
2424                             ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
2425                             MPI2_SGE_FLAGS_SHIFT);
2426                 } else {
2427                         saved_buf_len |=
2428                             ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
2429                             MPI2_SGE_FLAGS_SHIFT);
2430                 }
2431                 sge->FlagsLength = htole32(saved_buf_len);
2432                 sge->Address.Low = saved_address_low;
2433                 sge->Address.High = saved_address_high;
2434         }
2435
2436         cm->cm_sglsize -= len;
2437         bcopy(sgep, cm->cm_sge, len);
2438         cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
2439         return (0);
2440 }
2441
2442 /*
2443  * Add one dma segment to the scatter-gather list for a command.
2444  */
2445 int
2446 mps_add_dmaseg(struct mps_command *cm, vm_paddr_t pa, size_t len, u_int flags,
2447     int segsleft)
2448 {
2449         MPI2_SGE_SIMPLE64 sge;
2450
2451         /*
2452          * This driver always uses 64-bit address elements for simplicity.
2453          */
2454         bzero(&sge, sizeof(sge));
2455         flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
2456             MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
2457         sge.FlagsLength = htole32(len | (flags << MPI2_SGE_FLAGS_SHIFT));
2458         mps_from_u64(pa, &sge.Address);
2459
2460         return (mps_push_sge(cm, &sge, sizeof sge, segsleft));
2461 }
2462
2463 static void
2464 mps_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2465 {
2466         struct mps_softc *sc;
2467         struct mps_command *cm;
2468         u_int i, dir, sflags;
2469
2470         cm = (struct mps_command *)arg;
2471         sc = cm->cm_sc;
2472
2473         /*
2474          * In this case, just print out a warning and let the chip tell the
2475          * user they did the wrong thing.
2476          */
2477         if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
2478                 mps_dprint(sc, MPS_ERROR,
2479                            "%s: warning: busdma returned %d segments, "
2480                            "more than the %d allowed\n", __func__, nsegs,
2481                            cm->cm_max_segs);
2482         }
2483
2484         /*
2485          * Set up DMA direction flags.  Bi-directional requests are also handled
2486          * here.  In that case, both direction flags will be set.
2487          */
2488         sflags = 0;
2489         if (cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) {
2490                 /*
2491                  * We have to add a special case for SMP passthrough, there
2492                  * is no easy way to generically handle it.  The first
2493                  * S/G element is used for the command (therefore the
2494                  * direction bit needs to be set).  The second one is used
2495                  * for the reply.  We'll leave it to the caller to make
2496                  * sure we only have two buffers.
2497                  */
2498                 /*
2499                  * Even though the busdma man page says it doesn't make
2500                  * sense to have both direction flags, it does in this case.
2501                  * We have one s/g element being accessed in each direction.
2502                  */
2503                 dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
2504
2505                 /*
2506                  * Set the direction flag on the first buffer in the SMP
2507                  * passthrough request.  We'll clear it for the second one.
2508                  */
2509                 sflags |= MPI2_SGE_FLAGS_DIRECTION |
2510                           MPI2_SGE_FLAGS_END_OF_BUFFER;
2511         } else if (cm->cm_flags & MPS_CM_FLAGS_DATAOUT) {
2512                 sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
2513                 dir = BUS_DMASYNC_PREWRITE;
2514         } else
2515                 dir = BUS_DMASYNC_PREREAD;
2516
2517         for (i = 0; i < nsegs; i++) {
2518                 if ((cm->cm_flags & MPS_CM_FLAGS_SMP_PASS) && (i != 0)) {
2519                         sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
2520                 }
2521                 error = mps_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
2522                     sflags, nsegs - i);
2523                 if (error != 0) {
2524                         /* Resource shortage, roll back! */
2525                         if (ratecheck(&sc->lastfail, &mps_chainfail_interval))
2526                                 mps_dprint(sc, MPS_INFO, "Out of chain frames, "
2527                                     "consider increasing hw.mps.max_chains.\n");
2528                         cm->cm_flags |= MPS_CM_FLAGS_CHAIN_FAILED;
2529                         mps_complete_command(sc, cm);
2530                         return;
2531                 }
2532         }
2533
2534         bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
2535         mps_enqueue_request(sc, cm);
2536
2537         return;
2538 }
2539
2540 static void
2541 mps_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
2542              int error)
2543 {
2544         mps_data_cb(arg, segs, nsegs, error);
2545 }
2546
2547 /*
2548  * This is the routine to enqueue commands ansynchronously.
2549  * Note that the only error path here is from bus_dmamap_load(), which can
2550  * return EINPROGRESS if it is waiting for resources.  Other than this, it's
2551  * assumed that if you have a command in-hand, then you have enough credits
2552  * to use it.
2553  */
2554 int
2555 mps_map_command(struct mps_softc *sc, struct mps_command *cm)
2556 {
2557         int error = 0;
2558
2559         if (cm->cm_flags & MPS_CM_FLAGS_USE_UIO) {
2560                 error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
2561                     &cm->cm_uio, mps_data_cb2, cm, 0);
2562         } else if (cm->cm_flags & MPS_CM_FLAGS_USE_CCB) {
2563                 error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
2564                     cm->cm_data, mps_data_cb, cm, 0);
2565         } else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
2566                 error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
2567                     cm->cm_data, cm->cm_length, mps_data_cb, cm, 0);
2568         } else {
2569                 /* Add a zero-length element as needed */
2570                 if (cm->cm_sge != NULL)
2571                         mps_add_dmaseg(cm, 0, 0, 0, 1);
2572                 mps_enqueue_request(sc, cm);    
2573         }
2574
2575         return (error);
2576 }
2577
2578 /*
2579  * This is the routine to enqueue commands synchronously.  An error of
2580  * EINPROGRESS from mps_map_command() is ignored since the command will
2581  * be executed and enqueued automatically.  Other errors come from msleep().
2582  */
2583 int
2584 mps_wait_command(struct mps_softc *sc, struct mps_command **cmp, int timeout,
2585     int sleep_flag)
2586 {
2587         int error, rc;
2588         struct timeval cur_time, start_time;
2589         struct mps_command *cm = *cmp;
2590
2591         if (sc->mps_flags & MPS_FLAGS_DIAGRESET) 
2592                 return  EBUSY;
2593
2594         cm->cm_complete = NULL;
2595         cm->cm_flags |= MPS_CM_FLAGS_POLLED;
2596         error = mps_map_command(sc, cm);
2597         if ((error != 0) && (error != EINPROGRESS))
2598                 return (error);
2599
2600         /*
2601          * Check for context and wait for 50 mSec at a time until time has
2602          * expired or the command has finished.  If msleep can't be used, need
2603          * to poll.
2604          */
2605         if (curthread->td_no_sleeping != 0)
2606                 sleep_flag = NO_SLEEP;
2607         getmicrouptime(&start_time);
2608         if (mtx_owned(&sc->mps_mtx) && sleep_flag == CAN_SLEEP) {
2609                 cm->cm_flags |= MPS_CM_FLAGS_WAKEUP;
2610                 error = msleep(cm, &sc->mps_mtx, 0, "mpswait", timeout*hz);
2611                 if (error == EWOULDBLOCK) {
2612                         /*
2613                          * Record the actual elapsed time in the case of a
2614                          * timeout for the message below.
2615                          */
2616                         getmicrouptime(&cur_time);
2617                         timevalsub(&cur_time, &start_time);
2618                 }
2619         } else {
2620                 while ((cm->cm_flags & MPS_CM_FLAGS_COMPLETE) == 0) {
2621                         mps_intr_locked(sc);
2622                         if (sleep_flag == CAN_SLEEP)
2623                                 pause("mpswait", hz/20);
2624                         else
2625                                 DELAY(50000);
2626                 
2627                         getmicrouptime(&cur_time);
2628                         timevalsub(&cur_time, &start_time);
2629                         if (cur_time.tv_sec > timeout) {
2630                                 error = EWOULDBLOCK;
2631                                 break;
2632                         }
2633                 }
2634         }
2635
2636         if (error == EWOULDBLOCK) {
2637                 mps_dprint(sc, MPS_FAULT, "Calling Reinit from %s, timeout=%d,"
2638                     " elapsed=%jd\n", __func__, timeout,
2639                     (intmax_t)cur_time.tv_sec);
2640                 rc = mps_reinit(sc);
2641                 mps_dprint(sc, MPS_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
2642                     "failed");
2643                 if (sc->mps_flags & MPS_FLAGS_REALLOCATED) {
2644                         /*
2645                          * Tell the caller that we freed the command in a
2646                          * reinit.
2647                          */
2648                         *cmp = NULL;
2649                 }
2650                 error = ETIMEDOUT;
2651         }
2652         return (error);
2653 }
2654
2655 /*
2656  * The MPT driver had a verbose interface for config pages.  In this driver,
2657  * reduce it to much simpler terms, similar to the Linux driver.
2658  */
2659 int
2660 mps_read_config_page(struct mps_softc *sc, struct mps_config_params *params)
2661 {
2662         MPI2_CONFIG_REQUEST *req;
2663         struct mps_command *cm;
2664         int error;
2665
2666         if (sc->mps_flags & MPS_FLAGS_BUSY) {
2667                 return (EBUSY);
2668         }
2669
2670         cm = mps_alloc_command(sc);
2671         if (cm == NULL) {
2672                 return (EBUSY);
2673         }
2674
2675         req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
2676         req->Function = MPI2_FUNCTION_CONFIG;
2677         req->Action = params->action;
2678         req->SGLFlags = 0;
2679         req->ChainOffset = 0;
2680         req->PageAddress = params->page_address;
2681         if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
2682                 MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
2683
2684                 hdr = &params->hdr.Ext;
2685                 req->ExtPageType = hdr->ExtPageType;
2686                 req->ExtPageLength = hdr->ExtPageLength;
2687                 req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
2688                 req->Header.PageLength = 0; /* Must be set to zero */
2689                 req->Header.PageNumber = hdr->PageNumber;
2690                 req->Header.PageVersion = hdr->PageVersion;
2691         } else {
2692                 MPI2_CONFIG_PAGE_HEADER *hdr;
2693
2694                 hdr = &params->hdr.Struct;
2695                 req->Header.PageType = hdr->PageType;
2696                 req->Header.PageNumber = hdr->PageNumber;
2697                 req->Header.PageLength = hdr->PageLength;
2698                 req->Header.PageVersion = hdr->PageVersion;
2699         }
2700
2701         cm->cm_data = params->buffer;
2702         cm->cm_length = params->length;
2703         if (cm->cm_data != NULL) {
2704                 cm->cm_sge = &req->PageBufferSGE;
2705                 cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
2706                 cm->cm_flags = MPS_CM_FLAGS_SGE_SIMPLE | MPS_CM_FLAGS_DATAIN;
2707         } else
2708                 cm->cm_sge = NULL;
2709         cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2710
2711         cm->cm_complete_data = params;
2712         if (params->callback != NULL) {
2713                 cm->cm_complete = mps_config_complete;
2714                 return (mps_map_command(sc, cm));
2715         } else {
2716                 error = mps_wait_command(sc, &cm, 0, CAN_SLEEP);
2717                 if (error) {
2718                         mps_dprint(sc, MPS_FAULT,
2719                             "Error %d reading config page\n", error);
2720                         if (cm != NULL)
2721                                 mps_free_command(sc, cm);
2722                         return (error);
2723                 }
2724                 mps_config_complete(sc, cm);
2725         }
2726
2727         return (0);
2728 }
2729
2730 int
2731 mps_write_config_page(struct mps_softc *sc, struct mps_config_params *params)
2732 {
2733         return (EINVAL);
2734 }
2735
2736 static void
2737 mps_config_complete(struct mps_softc *sc, struct mps_command *cm)
2738 {
2739         MPI2_CONFIG_REPLY *reply;
2740         struct mps_config_params *params;
2741
2742         MPS_FUNCTRACE(sc);
2743         params = cm->cm_complete_data;
2744
2745         if (cm->cm_data != NULL) {
2746                 bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
2747                     BUS_DMASYNC_POSTREAD);
2748                 bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
2749         }
2750
2751         /*
2752          * XXX KDM need to do more error recovery?  This results in the
2753          * device in question not getting probed.
2754          */
2755         if ((cm->cm_flags & MPS_CM_FLAGS_ERROR_MASK) != 0) {
2756                 params->status = MPI2_IOCSTATUS_BUSY;
2757                 goto done;
2758         }
2759
2760         reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
2761         if (reply == NULL) {
2762                 params->status = MPI2_IOCSTATUS_BUSY;
2763                 goto done;
2764         }
2765         params->status = reply->IOCStatus;
2766         if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
2767                 params->hdr.Ext.ExtPageType = reply->ExtPageType;
2768                 params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
2769                 params->hdr.Ext.PageType = reply->Header.PageType;
2770                 params->hdr.Ext.PageNumber = reply->Header.PageNumber;
2771                 params->hdr.Ext.PageVersion = reply->Header.PageVersion;
2772         } else {
2773                 params->hdr.Struct.PageType = reply->Header.PageType;
2774                 params->hdr.Struct.PageNumber = reply->Header.PageNumber;
2775                 params->hdr.Struct.PageLength = reply->Header.PageLength;
2776                 params->hdr.Struct.PageVersion = reply->Header.PageVersion;
2777         }
2778
2779 done:
2780         mps_free_command(sc, cm);
2781         if (params->callback != NULL)
2782                 params->callback(sc, params);
2783
2784         return;
2785 }