The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/mps/mps.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: ca4f59fccac0c0b2025e6f10adebbedf


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.