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