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