2 * Copyright (c) 2009 Yahoo! Inc.
3 * Copyright (c) 2011-2015 LSI Corp.
4 * Copyright (c) 2013-2016 Avago Technologies
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * Avago Technologies (LSI) MPT-Fusion Host Adapter FreeBSD
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 /* Communications core for Avago Technologies (LSI) MPT3 */
37 /* TODO Move headers to mprvar */
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/selinfo.h>
44 #include <sys/mutex.h>
45 #include <sys/module.h>
49 #include <sys/malloc.h>
51 #include <sys/sysctl.h>
53 #include <sys/queue.h>
54 #include <sys/kthread.h>
55 #include <sys/taskqueue.h>
56 #include <sys/endian.h>
57 #include <sys/eventhandler.h>
60 #include <machine/bus.h>
61 #include <machine/resource.h>
65 #include <dev/pci/pcivar.h>
68 #include <cam/cam_ccb.h>
69 #include <cam/scsi/scsi_all.h>
71 #include <dev/mpr/mpi/mpi2_type.h>
72 #include <dev/mpr/mpi/mpi2.h>
73 #include <dev/mpr/mpi/mpi2_ioc.h>
74 #include <dev/mpr/mpi/mpi2_sas.h>
75 #include <dev/mpr/mpi/mpi2_pci.h>
76 #include <dev/mpr/mpi/mpi2_cnfg.h>
77 #include <dev/mpr/mpi/mpi2_init.h>
78 #include <dev/mpr/mpi/mpi2_tool.h>
79 #include <dev/mpr/mpr_ioctl.h>
80 #include <dev/mpr/mprvar.h>
81 #include <dev/mpr/mpr_table.h>
82 #include <dev/mpr/mpr_sas.h>
84 static int mpr_diag_reset(struct mpr_softc *sc, int sleep_flag);
85 static int mpr_init_queues(struct mpr_softc *sc);
86 static void mpr_resize_queues(struct mpr_softc *sc);
87 static int mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag);
88 static int mpr_transition_operational(struct mpr_softc *sc);
89 static int mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching);
90 static void mpr_iocfacts_free(struct mpr_softc *sc);
91 static void mpr_startup(void *arg);
92 static int mpr_send_iocinit(struct mpr_softc *sc);
93 static int mpr_alloc_queues(struct mpr_softc *sc);
94 static int mpr_alloc_hw_queues(struct mpr_softc *sc);
95 static int mpr_alloc_replies(struct mpr_softc *sc);
96 static int mpr_alloc_requests(struct mpr_softc *sc);
97 static int mpr_alloc_nvme_prp_pages(struct mpr_softc *sc);
98 static int mpr_attach_log(struct mpr_softc *sc);
99 static __inline void mpr_complete_command(struct mpr_softc *sc,
100 struct mpr_command *cm);
101 static void mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
102 MPI2_EVENT_NOTIFICATION_REPLY *reply);
103 static void mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm);
104 static void mpr_periodic(void *);
105 static int mpr_reregister_events(struct mpr_softc *sc);
106 static void mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm);
107 static int mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts);
108 static int mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag);
109 static int mpr_debug_sysctl(SYSCTL_HANDLER_ARGS);
110 static void mpr_parse_debug(struct mpr_softc *sc, char *list);
112 SYSCTL_NODE(_hw, OID_AUTO, mpr, CTLFLAG_RD, 0, "MPR Driver Parameters");
114 MALLOC_DEFINE(M_MPR, "mpr", "mpr driver memory");
117 * Do a "Diagnostic Reset" aka a hard reset. This should get the chip out of
118 * any state and back to its initialization state machine.
120 static char mpt2_reset_magic[] = { 0x00, 0x0f, 0x04, 0x0b, 0x02, 0x07, 0x0d };
123 * Added this union to smoothly convert le64toh cm->cm_desc.Words.
124 * Compiler only supports uint64_t to be passed as an argument.
125 * Otherwise it will throw this error:
126 * "aggregate value used where an integer was expected"
128 typedef union _reply_descriptor {
134 } reply_descriptor, request_descriptor;
136 /* Rate limit chain-fail messages to 1 per minute */
137 static struct timeval mpr_chainfail_interval = { 60, 0 };
140 * sleep_flag can be either CAN_SLEEP or NO_SLEEP.
141 * If this function is called from process context, it can sleep
142 * and there is no harm to sleep, in case if this fuction is called
143 * from Interrupt handler, we can not sleep and need NO_SLEEP flag set.
144 * based on sleep flags driver will call either msleep, pause or DELAY.
145 * msleep and pause are of same variant, but pause is used when mpr_mtx
146 * is not hold by driver.
149 mpr_diag_reset(struct mpr_softc *sc,int sleep_flag)
152 int i, error, tries = 0;
153 uint8_t first_wait_done = FALSE;
155 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
157 /* Clear any pending interrupts */
158 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
161 * Force NO_SLEEP for threads prohibited to sleep
162 * e.a Thread from interrupt handler are prohibited to sleep.
164 #if __FreeBSD_version >= 1000029
165 if (curthread->td_no_sleeping)
166 #else //__FreeBSD_version < 1000029
167 if (curthread->td_pflags & TDP_NOSLEEPING)
168 #endif //__FreeBSD_version >= 1000029
169 sleep_flag = NO_SLEEP;
171 mpr_dprint(sc, MPR_INIT, "sequence start, sleep_flag=%d\n", sleep_flag);
172 /* Push the magic sequence */
174 while (tries++ < 20) {
175 for (i = 0; i < sizeof(mpt2_reset_magic); i++)
176 mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET,
177 mpt2_reset_magic[i]);
180 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
181 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
183 else if (sleep_flag == CAN_SLEEP)
184 pause("mprdiag", hz/10);
188 reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
189 if (reg & MPI2_DIAG_DIAG_WRITE_ENABLE) {
195 mpr_dprint(sc, MPR_INIT, "sequence failed, error=%d, exit\n",
200 /* Send the actual reset. XXX need to refresh the reg? */
201 reg |= MPI2_DIAG_RESET_ADAPTER;
202 mpr_dprint(sc, MPR_INIT, "sequence success, sending reset, reg= 0x%x\n",
204 mpr_regwrite(sc, MPI2_HOST_DIAGNOSTIC_OFFSET, reg);
206 /* Wait up to 300 seconds in 50ms intervals */
208 for (i = 0; i < 6000; i++) {
210 * Wait 50 msec. If this is the first time through, wait 256
211 * msec to satisfy Diag Reset timing requirements.
213 if (first_wait_done) {
214 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
215 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
217 else if (sleep_flag == CAN_SLEEP)
218 pause("mprdiag", hz/20);
223 first_wait_done = TRUE;
226 * Check for the RESET_ADAPTER bit to be cleared first, then
227 * wait for the RESET state to be cleared, which takes a little
230 reg = mpr_regread(sc, MPI2_HOST_DIAGNOSTIC_OFFSET);
231 if (reg & MPI2_DIAG_RESET_ADAPTER) {
234 reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
235 if ((reg & MPI2_IOC_STATE_MASK) != MPI2_IOC_STATE_RESET) {
241 mpr_dprint(sc, MPR_INIT, "reset failed, error= %d, exit\n",
246 mpr_regwrite(sc, MPI2_WRITE_SEQUENCE_OFFSET, 0x0);
247 mpr_dprint(sc, MPR_INIT, "diag reset success, exit\n");
253 mpr_message_unit_reset(struct mpr_softc *sc, int sleep_flag)
259 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
262 mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
263 MPI2_FUNCTION_IOC_MESSAGE_UNIT_RESET <<
264 MPI2_DOORBELL_FUNCTION_SHIFT);
266 if (mpr_wait_db_ack(sc, 5, sleep_flag) != 0) {
267 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
268 "Doorbell handshake failed\n");
272 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
277 mpr_transition_ready(struct mpr_softc *sc)
280 int error, tries = 0;
284 /* If we are in attach call, do not sleep */
285 sleep_flags = (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE)
286 ? CAN_SLEEP : NO_SLEEP;
290 mpr_dprint(sc, MPR_INIT, "%s entered, sleep_flags= %d\n",
291 __func__, sleep_flags);
293 while (tries++ < 1200) {
294 reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
295 mpr_dprint(sc, MPR_INIT, " Doorbell= 0x%x\n", reg);
298 * Ensure the IOC is ready to talk. If it's not, try
301 if (reg & MPI2_DOORBELL_USED) {
302 mpr_dprint(sc, MPR_INIT, " Not ready, sending diag "
304 mpr_diag_reset(sc, sleep_flags);
309 /* Is the adapter owned by another peer? */
310 if ((reg & MPI2_DOORBELL_WHO_INIT_MASK) ==
311 (MPI2_WHOINIT_PCI_PEER << MPI2_DOORBELL_WHO_INIT_SHIFT)) {
312 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC is under the "
313 "control of another peer host, aborting "
314 "initialization.\n");
319 state = reg & MPI2_IOC_STATE_MASK;
320 if (state == MPI2_IOC_STATE_READY) {
324 } else if (state == MPI2_IOC_STATE_FAULT) {
325 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC in fault "
326 "state 0x%x, resetting\n",
327 state & MPI2_DOORBELL_FAULT_CODE_MASK);
328 mpr_diag_reset(sc, sleep_flags);
329 } else if (state == MPI2_IOC_STATE_OPERATIONAL) {
330 /* Need to take ownership */
331 mpr_message_unit_reset(sc, sleep_flags);
332 } else if (state == MPI2_IOC_STATE_RESET) {
333 /* Wait a bit, IOC might be in transition */
334 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
335 "IOC in unexpected reset state\n");
337 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
338 "IOC in unknown state 0x%x\n", state);
343 /* Wait 50ms for things to settle down. */
348 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
349 "Cannot transition IOC to ready\n");
350 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
355 mpr_transition_operational(struct mpr_softc *sc)
363 reg = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
364 mpr_dprint(sc, MPR_INIT, "%s entered, Doorbell= 0x%x\n", __func__, reg);
366 state = reg & MPI2_IOC_STATE_MASK;
367 if (state != MPI2_IOC_STATE_READY) {
368 mpr_dprint(sc, MPR_INIT, "IOC not ready\n");
369 if ((error = mpr_transition_ready(sc)) != 0) {
370 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
371 "failed to transition ready, exit\n");
376 error = mpr_send_iocinit(sc);
377 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
383 mpr_resize_queues(struct mpr_softc *sc)
385 u_int reqcr, prireqcr, maxio, sges_per_frame;
388 * Size the queues. Since the reply queues always need one free
389 * entry, we'll deduct one reply message here. The LSI documents
390 * suggest instead to add a count to the request queue, but I think
391 * that it's better to deduct from reply queue.
393 prireqcr = MAX(1, sc->max_prireqframes);
394 prireqcr = MIN(prireqcr, sc->facts->HighPriorityCredit);
396 reqcr = MAX(2, sc->max_reqframes);
397 reqcr = MIN(reqcr, sc->facts->RequestCredit);
399 sc->num_reqs = prireqcr + reqcr;
400 sc->num_prireqs = prireqcr;
401 sc->num_replies = MIN(sc->max_replyframes + sc->max_evtframes,
402 sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
404 /* Store the request frame size in bytes rather than as 32bit words */
405 sc->reqframesz = sc->facts->IOCRequestFrameSize * 4;
408 * Gen3 and beyond uses the IOCMaxChainSegmentSize from IOC Facts to
409 * get the size of a Chain Frame. Previous versions use the size as a
410 * Request Frame for the Chain Frame size. If IOCMaxChainSegmentSize
411 * is 0, use the default value. The IOCMaxChainSegmentSize is the
412 * number of 16-byte elelements that can fit in a Chain Frame, which is
413 * the size of an IEEE Simple SGE.
415 if (sc->facts->MsgVersion >= MPI2_VERSION_02_05) {
417 htole16(sc->facts->IOCMaxChainSegmentSize);
418 if (sc->chain_seg_size == 0) {
419 sc->chain_frame_size = MPR_DEFAULT_CHAIN_SEG_SIZE *
420 MPR_MAX_CHAIN_ELEMENT_SIZE;
422 sc->chain_frame_size = sc->chain_seg_size *
423 MPR_MAX_CHAIN_ELEMENT_SIZE;
426 sc->chain_frame_size = sc->reqframesz;
430 * Max IO Size is Page Size * the following:
431 * ((SGEs per frame - 1 for chain element) * Max Chain Depth)
432 * + 1 for no chain needed in last frame
434 * If user suggests a Max IO size to use, use the smaller of the
435 * user's value and the calculated value as long as the user's
436 * value is larger than 0. The user's value is in pages.
438 sges_per_frame = sc->chain_frame_size/sizeof(MPI2_IEEE_SGE_SIMPLE64)-1;
439 maxio = (sges_per_frame * sc->facts->MaxChainDepth + 1) * PAGE_SIZE;
442 * If I/O size limitation requested then use it and pass up to CAM.
443 * If not, use MAXPHYS as an optimization hint, but report HW limit.
445 if (sc->max_io_pages > 0) {
446 maxio = min(maxio, sc->max_io_pages * PAGE_SIZE);
450 maxio = min(maxio, MAXPHYS);
453 sc->num_chains = (maxio / PAGE_SIZE + sges_per_frame - 2) /
454 sges_per_frame * reqcr;
455 if (sc->max_chains > 0 && sc->max_chains < sc->num_chains)
456 sc->num_chains = sc->max_chains;
459 * Figure out the number of MSIx-based queues. If the firmware or
460 * user has done something crazy and not allowed enough credit for
461 * the queues to be useful then don't enable multi-queue.
463 if (sc->facts->MaxMSIxVectors < 2)
466 if (sc->msi_msgs > 1) {
467 sc->msi_msgs = MIN(sc->msi_msgs, mp_ncpus);
468 sc->msi_msgs = MIN(sc->msi_msgs, sc->facts->MaxMSIxVectors);
469 if (sc->num_reqs / sc->msi_msgs < 2)
473 mpr_dprint(sc, MPR_INIT, "Sized queues to q=%d reqs=%d replies=%d\n",
474 sc->msi_msgs, sc->num_reqs, sc->num_replies);
478 * This is called during attach and when re-initializing due to a Diag Reset.
479 * IOC Facts is used to allocate many of the structures needed by the driver.
480 * If called from attach, de-allocation is not required because the driver has
481 * not allocated any structures yet, but if called from a Diag Reset, previously
482 * allocated structures based on IOC Facts will need to be freed and re-
483 * allocated bases on the latest IOC Facts.
486 mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching)
489 Mpi2IOCFactsReply_t saved_facts;
490 uint8_t saved_mode, reallocating;
492 mpr_dprint(sc, MPR_INIT|MPR_TRACE, "%s entered\n", __func__);
494 /* Save old IOC Facts and then only reallocate if Facts have changed */
496 bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
500 * Get IOC Facts. In all cases throughout this function, panic if doing
501 * a re-initialization and only return the error if attaching so the OS
504 if ((error = mpr_get_iocfacts(sc, sc->facts)) != 0) {
506 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to get "
507 "IOC Facts with error %d, exit\n", error);
510 panic("%s failed to get IOC Facts with error %d\n",
515 MPR_DPRINT_PAGE(sc, MPR_XINFO, iocfacts, sc->facts);
517 snprintf(sc->fw_version, sizeof(sc->fw_version),
518 "%02d.%02d.%02d.%02d",
519 sc->facts->FWVersion.Struct.Major,
520 sc->facts->FWVersion.Struct.Minor,
521 sc->facts->FWVersion.Struct.Unit,
522 sc->facts->FWVersion.Struct.Dev);
524 mpr_dprint(sc, MPR_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
526 mpr_dprint(sc, MPR_INFO,
527 "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
528 "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
529 "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
530 "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc"
531 "\22FastPath" "\23RDPQArray" "\24AtomicReqDesc" "\25PCIeSRIOV");
534 * If the chip doesn't support event replay then a hard reset will be
535 * required to trigger a full discovery. Do the reset here then
536 * retransition to Ready. A hard reset might have already been done,
537 * but it doesn't hurt to do it again. Only do this if attaching, not
540 if (attaching && ((sc->facts->IOCCapabilities &
541 MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
542 mpr_dprint(sc, MPR_INIT, "No event replay, resetting\n");
543 mpr_diag_reset(sc, NO_SLEEP);
544 if ((error = mpr_transition_ready(sc)) != 0) {
545 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
546 "transition to ready with error %d, exit\n",
553 * Set flag if IR Firmware is loaded. If the RAID Capability has
554 * changed from the previous IOC Facts, log a warning, but only if
555 * checking this after a Diag Reset and not during attach.
557 saved_mode = sc->ir_firmware;
558 if (sc->facts->IOCCapabilities &
559 MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
562 if (sc->ir_firmware != saved_mode) {
563 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "new IR/IT mode "
564 "in IOC Facts does not match previous mode\n");
568 /* Only deallocate and reallocate if relevant IOC Facts have changed */
569 reallocating = FALSE;
570 sc->mpr_flags &= ~MPR_FLAGS_REALLOCATED;
573 ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
574 (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
575 (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
576 (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
577 (saved_facts.ProductID != sc->facts->ProductID) ||
578 (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
579 (saved_facts.IOCRequestFrameSize !=
580 sc->facts->IOCRequestFrameSize) ||
581 (saved_facts.IOCMaxChainSegmentSize !=
582 sc->facts->IOCMaxChainSegmentSize) ||
583 (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
584 (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
585 (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
586 (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
587 (saved_facts.MaxReplyDescriptorPostQueueDepth !=
588 sc->facts->MaxReplyDescriptorPostQueueDepth) ||
589 (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
590 (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
591 (saved_facts.MaxPersistentEntries !=
592 sc->facts->MaxPersistentEntries))) {
595 /* Record that we reallocated everything */
596 sc->mpr_flags |= MPR_FLAGS_REALLOCATED;
600 * Some things should be done if attaching or re-allocating after a Diag
601 * Reset, but are not needed after a Diag Reset if the FW has not
604 if (attaching || reallocating) {
606 * Check if controller supports FW diag buffers and set flag to
609 if (sc->facts->IOCCapabilities &
610 MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
611 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
613 if (sc->facts->IOCCapabilities &
614 MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
615 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
617 if (sc->facts->IOCCapabilities &
618 MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
619 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
623 * Set flags for some supported items.
625 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
626 sc->eedp_enabled = TRUE;
627 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
628 sc->control_TLR = TRUE;
629 if (sc->facts->IOCCapabilities &
630 MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ)
631 sc->atomic_desc_capable = TRUE;
633 mpr_resize_queues(sc);
636 * Initialize all Tail Queues
638 TAILQ_INIT(&sc->req_list);
639 TAILQ_INIT(&sc->high_priority_req_list);
640 TAILQ_INIT(&sc->chain_list);
641 TAILQ_INIT(&sc->prp_page_list);
642 TAILQ_INIT(&sc->tm_list);
646 * If doing a Diag Reset and the FW is significantly different
647 * (reallocating will be set above in IOC Facts comparison), then all
648 * buffers based on the IOC Facts will need to be freed before they are
652 mpr_iocfacts_free(sc);
653 mprsas_realloc_targets(sc, saved_facts.MaxTargets +
654 saved_facts.MaxVolumes);
658 * Any deallocation has been completed. Now start reallocating
659 * if needed. Will only need to reallocate if attaching or if the new
660 * IOC Facts are different from the previous IOC Facts after a Diag
661 * Reset. Targets have already been allocated above if needed.
664 while (attaching || reallocating) {
665 if ((error = mpr_alloc_hw_queues(sc)) != 0)
667 if ((error = mpr_alloc_replies(sc)) != 0)
669 if ((error = mpr_alloc_requests(sc)) != 0)
671 if ((error = mpr_alloc_queues(sc)) != 0)
676 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
677 "Failed to alloc queues with error %d\n", error);
682 /* Always initialize the queues */
683 bzero(sc->free_queue, sc->fqdepth * 4);
687 * Always get the chip out of the reset state, but only panic if not
688 * attaching. If attaching and there is an error, that is handled by
691 error = mpr_transition_operational(sc);
693 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
694 "transition to operational with error %d\n", error);
700 * Finish the queue initialization.
701 * These are set here instead of in mpr_init_queues() because the
702 * IOC resets these values during the state transition in
703 * mpr_transition_operational(). The free index is set to 1
704 * because the corresponding index in the IOC is set to 0, and the
705 * IOC treats the queues as full if both are set to the same value.
706 * Hence the reason that the queue can't hold all of the possible
709 sc->replypostindex = 0;
710 mpr_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
711 mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
714 * Attach the subsystems so they can prepare their event masks.
715 * XXX Should be dynamic so that IM/IR and user modules can attach
719 mpr_dprint(sc, MPR_INIT, "Attaching subsystems\n");
720 if ((error = mpr_attach_log(sc)) != 0)
722 if ((error = mpr_attach_sas(sc)) != 0)
724 if ((error = mpr_attach_user(sc)) != 0)
729 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
730 "Failed to attach all subsystems: error %d\n", error);
736 * XXX If the number of MSI-X vectors changes during re-init, this
737 * won't see it and adjust.
739 if (attaching && (error = mpr_pci_setup_interrupts(sc)) != 0) {
740 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
741 "Failed to setup interrupts\n");
750 * This is called if memory is being free (during detach for example) and when
751 * buffers need to be reallocated due to a Diag Reset.
754 mpr_iocfacts_free(struct mpr_softc *sc)
756 struct mpr_command *cm;
759 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
761 if (sc->free_busaddr != 0)
762 bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
763 if (sc->free_queue != NULL)
764 bus_dmamem_free(sc->queues_dmat, sc->free_queue,
766 if (sc->queues_dmat != NULL)
767 bus_dma_tag_destroy(sc->queues_dmat);
769 if (sc->chain_busaddr != 0)
770 bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
771 if (sc->chain_frames != NULL)
772 bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
774 if (sc->chain_dmat != NULL)
775 bus_dma_tag_destroy(sc->chain_dmat);
777 if (sc->sense_busaddr != 0)
778 bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
779 if (sc->sense_frames != NULL)
780 bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
782 if (sc->sense_dmat != NULL)
783 bus_dma_tag_destroy(sc->sense_dmat);
785 if (sc->prp_page_busaddr != 0)
786 bus_dmamap_unload(sc->prp_page_dmat, sc->prp_page_map);
787 if (sc->prp_pages != NULL)
788 bus_dmamem_free(sc->prp_page_dmat, sc->prp_pages,
790 if (sc->prp_page_dmat != NULL)
791 bus_dma_tag_destroy(sc->prp_page_dmat);
793 if (sc->reply_busaddr != 0)
794 bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
795 if (sc->reply_frames != NULL)
796 bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
798 if (sc->reply_dmat != NULL)
799 bus_dma_tag_destroy(sc->reply_dmat);
801 if (sc->req_busaddr != 0)
802 bus_dmamap_unload(sc->req_dmat, sc->req_map);
803 if (sc->req_frames != NULL)
804 bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
805 if (sc->req_dmat != NULL)
806 bus_dma_tag_destroy(sc->req_dmat);
808 if (sc->chains != NULL)
809 free(sc->chains, M_MPR);
810 if (sc->prps != NULL)
811 free(sc->prps, M_MPR);
812 if (sc->commands != NULL) {
813 for (i = 1; i < sc->num_reqs; i++) {
814 cm = &sc->commands[i];
815 bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
817 free(sc->commands, M_MPR);
819 if (sc->buffer_dmat != NULL)
820 bus_dma_tag_destroy(sc->buffer_dmat);
822 mpr_pci_free_interrupts(sc);
823 free(sc->queues, M_MPR);
828 * The terms diag reset and hard reset are used interchangeably in the MPI
829 * docs to mean resetting the controller chip. In this code diag reset
830 * cleans everything up, and the hard reset function just sends the reset
831 * sequence to the chip. This should probably be refactored so that every
832 * subsystem gets a reset notification of some sort, and can clean up
836 mpr_reinit(struct mpr_softc *sc)
839 struct mprsas_softc *sassc;
845 mtx_assert(&sc->mpr_mtx, MA_OWNED);
847 mpr_dprint(sc, MPR_INIT|MPR_INFO, "Reinitializing controller\n");
848 if (sc->mpr_flags & MPR_FLAGS_DIAGRESET) {
849 mpr_dprint(sc, MPR_INIT, "Reset already in progress\n");
854 * Make sure the completion callbacks can recognize they're getting
855 * a NULL cm_reply due to a reset.
857 sc->mpr_flags |= MPR_FLAGS_DIAGRESET;
860 * Mask interrupts here.
862 mpr_dprint(sc, MPR_INIT, "Masking interrupts and resetting\n");
865 error = mpr_diag_reset(sc, CAN_SLEEP);
867 panic("%s hard reset failed with error %d\n", __func__, error);
870 /* Restore the PCI state, including the MSI-X registers */
873 /* Give the I/O subsystem special priority to get itself prepared */
874 mprsas_handle_reinit(sc);
877 * Get IOC Facts and allocate all structures based on this information.
878 * The attach function will also call mpr_iocfacts_allocate at startup.
879 * If relevant values have changed in IOC Facts, this function will free
880 * all of the memory based on IOC Facts and reallocate that memory.
882 if ((error = mpr_iocfacts_allocate(sc, FALSE)) != 0) {
883 panic("%s IOC Facts based allocation failed with error %d\n",
888 * Mapping structures will be re-allocated after getting IOC Page8, so
889 * free these structures here.
891 mpr_mapping_exit(sc);
894 * The static page function currently read is IOC Page8. Others can be
895 * added in future. It's possible that the values in IOC Page8 have
896 * changed after a Diag Reset due to user modification, so always read
897 * these. Interrupts are masked, so unmask them before getting config
901 sc->mpr_flags &= ~MPR_FLAGS_DIAGRESET;
902 mpr_base_static_config_pages(sc);
905 * Some mapping info is based in IOC Page8 data, so re-initialize the
908 mpr_mapping_initialize(sc);
911 * Restart will reload the event masks clobbered by the reset, and
912 * then enable the port.
914 mpr_reregister_events(sc);
916 /* the end of discovery will release the simq, so we're done. */
917 mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Finished sc %p post %u free %u\n",
918 sc, sc->replypostindex, sc->replyfreeindex);
919 mprsas_release_simq_reinit(sassc);
920 mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
925 /* Wait for the chip to ACK a word that we've put into its FIFO
926 * Wait for <timeout> seconds. In single loop wait for busy loop
927 * for 500 microseconds.
928 * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
931 mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag)
938 cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
940 int_status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
941 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
942 mpr_dprint(sc, MPR_TRACE, "%s: successful count(%d), "
943 "timeout(%d)\n", __func__, count, timeout);
945 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
946 doorbell = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
947 if ((doorbell & MPI2_IOC_STATE_MASK) ==
948 MPI2_IOC_STATE_FAULT) {
949 mpr_dprint(sc, MPR_FAULT,
950 "fault_state(0x%04x)!\n", doorbell);
953 } else if (int_status == 0xFFFFFFFF)
957 * If it can sleep, sleep for 1 milisecond, else busy loop for
960 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
961 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0, "mprdba",
963 else if (sleep_flag == CAN_SLEEP)
964 pause("mprdba", hz/1000);
971 mpr_dprint(sc, MPR_FAULT, "%s: failed due to timeout count(%d), "
972 "int_status(%x)!\n", __func__, count, int_status);
976 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
978 mpr_wait_db_int(struct mpr_softc *sc)
982 for (retry = 0; retry < MPR_DB_MAX_WAIT; retry++) {
983 if ((mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
984 MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
991 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
993 mpr_request_sync(struct mpr_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
994 int req_sz, int reply_sz, int timeout)
998 int i, count, ioc_sz, residual;
999 int sleep_flags = CAN_SLEEP;
1001 #if __FreeBSD_version >= 1000029
1002 if (curthread->td_no_sleeping)
1003 #else //__FreeBSD_version < 1000029
1004 if (curthread->td_pflags & TDP_NOSLEEPING)
1005 #endif //__FreeBSD_version >= 1000029
1006 sleep_flags = NO_SLEEP;
1009 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1012 if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1016 * Announce that a message is coming through the doorbell. Messages
1017 * are pushed at 32bit words, so round up if needed.
1019 count = (req_sz + 3) / 4;
1020 mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
1021 (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
1022 (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
1025 if (mpr_wait_db_int(sc) ||
1026 (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
1027 mpr_dprint(sc, MPR_FAULT, "Doorbell failed to activate\n");
1030 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1031 if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
1032 mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed\n");
1037 /* Clock out the message data synchronously in 32-bit dwords*/
1038 data32 = (uint32_t *)req;
1039 for (i = 0; i < count; i++) {
1040 mpr_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
1041 if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
1042 mpr_dprint(sc, MPR_FAULT,
1043 "Timeout while writing doorbell\n");
1049 /* Clock in the reply in 16-bit words. The total length of the
1050 * message is always in the 4th byte, so clock out the first 2 words
1051 * manually, then loop the rest.
1053 data16 = (uint16_t *)reply;
1054 if (mpr_wait_db_int(sc) != 0) {
1055 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 0\n");
1059 mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1060 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1061 if (mpr_wait_db_int(sc) != 0) {
1062 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 1\n");
1066 mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1067 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1069 /* Number of 32bit words in the message */
1070 ioc_sz = reply->MsgLength;
1073 * Figure out how many 16bit words to clock in without overrunning.
1074 * The precision loss with dividing reply_sz can safely be
1075 * ignored because the messages can only be multiples of 32bits.
1078 count = MIN((reply_sz / 4), ioc_sz) * 2;
1079 if (count < ioc_sz * 2) {
1080 residual = ioc_sz * 2 - count;
1081 mpr_dprint(sc, MPR_ERROR, "Driver error, throwing away %d "
1082 "residual message words\n", residual);
1085 for (i = 2; i < count; i++) {
1086 if (mpr_wait_db_int(sc) != 0) {
1087 mpr_dprint(sc, MPR_FAULT,
1088 "Timeout reading doorbell %d\n", i);
1091 data16[i] = mpr_regread(sc, MPI2_DOORBELL_OFFSET) &
1092 MPI2_DOORBELL_DATA_MASK;
1093 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1097 * Pull out residual words that won't fit into the provided buffer.
1098 * This keeps the chip from hanging due to a driver programming
1101 while (residual--) {
1102 if (mpr_wait_db_int(sc) != 0) {
1103 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell\n");
1106 (void)mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1107 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1111 if (mpr_wait_db_int(sc) != 0) {
1112 mpr_dprint(sc, MPR_FAULT, "Timeout waiting to exit doorbell\n");
1115 if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1116 mpr_dprint(sc, MPR_FAULT, "Warning, doorbell still active\n");
1117 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1123 mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm)
1125 request_descriptor rd;
1128 mpr_dprint(sc, MPR_TRACE, "SMID %u cm %p ccb %p\n",
1129 cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1131 if (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE && !(sc->mpr_flags &
1132 MPR_FLAGS_SHUTDOWN))
1133 mtx_assert(&sc->mpr_mtx, MA_OWNED);
1135 if (++sc->io_cmds_active > sc->io_cmds_highwater)
1136 sc->io_cmds_highwater++;
1138 KASSERT(cm->cm_state == MPR_CM_STATE_BUSY, ("command not busy\n"));
1139 cm->cm_state = MPR_CM_STATE_INQUEUE;
1141 if (sc->atomic_desc_capable) {
1142 rd.u.low = cm->cm_desc.Words.Low;
1143 mpr_regwrite(sc, MPI26_ATOMIC_REQUEST_DESCRIPTOR_POST_OFFSET,
1146 rd.u.low = cm->cm_desc.Words.Low;
1147 rd.u.high = cm->cm_desc.Words.High;
1148 rd.word = htole64(rd.word);
1149 mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1151 mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1157 * Just the FACTS, ma'am.
1160 mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1162 MPI2_DEFAULT_REPLY *reply;
1163 MPI2_IOC_FACTS_REQUEST request;
1164 int error, req_sz, reply_sz;
1167 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1169 req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1170 reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1171 reply = (MPI2_DEFAULT_REPLY *)facts;
1173 bzero(&request, req_sz);
1174 request.Function = MPI2_FUNCTION_IOC_FACTS;
1175 error = mpr_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1177 mpr_dprint(sc, MPR_INIT, "%s exit, error= %d\n", __func__, error);
1182 mpr_send_iocinit(struct mpr_softc *sc)
1184 MPI2_IOC_INIT_REQUEST init;
1185 MPI2_DEFAULT_REPLY reply;
1186 int req_sz, reply_sz, error;
1188 uint64_t time_in_msec;
1191 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1193 /* Do a quick sanity check on proper initialization */
1194 if ((sc->pqdepth == 0) || (sc->fqdepth == 0) || (sc->reqframesz == 0)
1195 || (sc->replyframesz == 0)) {
1196 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
1197 "Driver not fully initialized for IOCInit\n");
1201 req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1202 reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1203 bzero(&init, req_sz);
1204 bzero(&reply, reply_sz);
1207 * Fill in the init block. Note that most addresses are
1208 * deliberately in the lower 32bits of memory. This is a micro-
1209 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1211 init.Function = MPI2_FUNCTION_IOC_INIT;
1212 init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1213 init.MsgVersion = htole16(MPI2_VERSION);
1214 init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1215 init.SystemRequestFrameSize = htole16((uint16_t)(sc->reqframesz / 4));
1216 init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1217 init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1218 init.SenseBufferAddressHigh = 0;
1219 init.SystemReplyAddressHigh = 0;
1220 init.SystemRequestFrameBaseAddress.High = 0;
1221 init.SystemRequestFrameBaseAddress.Low =
1222 htole32((uint32_t)sc->req_busaddr);
1223 init.ReplyDescriptorPostQueueAddress.High = 0;
1224 init.ReplyDescriptorPostQueueAddress.Low =
1225 htole32((uint32_t)sc->post_busaddr);
1226 init.ReplyFreeQueueAddress.High = 0;
1227 init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1229 time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1230 init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1231 init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1232 init.HostPageSize = HOST_PAGE_SIZE_4K;
1234 error = mpr_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1235 if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1238 mpr_dprint(sc, MPR_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1239 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
1244 mpr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1249 *addr = segs[0].ds_addr;
1253 mpr_memaddr_wait_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1255 struct mpr_busdma_context *ctx;
1256 int need_unload, need_free;
1258 ctx = (struct mpr_busdma_context *)arg;
1262 mpr_lock(ctx->softc);
1265 if ((error == 0) && (ctx->abandoned == 0)) {
1266 *ctx->addr = segs[0].ds_addr;
1270 if (ctx->abandoned != 0)
1276 mpr_unlock(ctx->softc);
1278 if (need_unload != 0) {
1279 bus_dmamap_unload(ctx->buffer_dmat,
1280 ctx->buffer_dmamap);
1289 mpr_alloc_queues(struct mpr_softc *sc)
1291 struct mpr_queue *q;
1295 mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Allocating %d I/O queues\n", nq);
1297 sc->queues = malloc(sizeof(struct mpr_queue) * nq, M_MPR,
1299 if (sc->queues == NULL)
1302 for (i = 0; i < nq; i++) {
1304 mpr_dprint(sc, MPR_INIT, "Configuring queue %d %p\n", i, q);
1312 mpr_alloc_hw_queues(struct mpr_softc *sc)
1314 bus_addr_t queues_busaddr;
1316 int qsize, fqsize, pqsize;
1319 * The reply free queue contains 4 byte entries in multiples of 16 and
1320 * aligned on a 16 byte boundary. There must always be an unused entry.
1321 * This queue supplies fresh reply frames for the firmware to use.
1323 * The reply descriptor post queue contains 8 byte entries in
1324 * multiples of 16 and aligned on a 16 byte boundary. This queue
1325 * contains filled-in reply frames sent from the firmware to the host.
1327 * These two queues are allocated together for simplicity.
1329 sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1330 sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1331 fqsize= sc->fqdepth * 4;
1332 pqsize = sc->pqdepth * 8;
1333 qsize = fqsize + pqsize;
1335 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1336 16, 0, /* algnmnt, boundary */
1337 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1338 BUS_SPACE_MAXADDR, /* highaddr */
1339 NULL, NULL, /* filter, filterarg */
1340 qsize, /* maxsize */
1342 qsize, /* maxsegsize */
1344 NULL, NULL, /* lockfunc, lockarg */
1345 &sc->queues_dmat)) {
1346 mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues DMA tag\n");
1349 if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1351 mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues memory\n");
1354 bzero(queues, qsize);
1355 bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1356 mpr_memaddr_cb, &queues_busaddr, 0);
1358 sc->free_queue = (uint32_t *)queues;
1359 sc->free_busaddr = queues_busaddr;
1360 sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1361 sc->post_busaddr = queues_busaddr + fqsize;
1362 mpr_dprint(sc, MPR_INIT, "free queue busaddr= %#016jx size= %d\n",
1363 (uintmax_t)sc->free_busaddr, fqsize);
1364 mpr_dprint(sc, MPR_INIT, "reply queue busaddr= %#016jx size= %d\n",
1365 (uintmax_t)sc->post_busaddr, pqsize);
1371 mpr_alloc_replies(struct mpr_softc *sc)
1373 int rsize, num_replies;
1375 /* Store the reply frame size in bytes rather than as 32bit words */
1376 sc->replyframesz = sc->facts->ReplyFrameSize * 4;
1379 * sc->num_replies should be one less than sc->fqdepth. We need to
1380 * allocate space for sc->fqdepth replies, but only sc->num_replies
1381 * replies can be used at once.
1383 num_replies = max(sc->fqdepth, sc->num_replies);
1385 rsize = sc->replyframesz * num_replies;
1386 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1387 4, 0, /* algnmnt, boundary */
1388 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1389 BUS_SPACE_MAXADDR, /* highaddr */
1390 NULL, NULL, /* filter, filterarg */
1391 rsize, /* maxsize */
1393 rsize, /* maxsegsize */
1395 NULL, NULL, /* lockfunc, lockarg */
1397 mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies DMA tag\n");
1400 if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1401 BUS_DMA_NOWAIT, &sc->reply_map)) {
1402 mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies memory\n");
1405 bzero(sc->reply_frames, rsize);
1406 bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1407 mpr_memaddr_cb, &sc->reply_busaddr, 0);
1408 mpr_dprint(sc, MPR_INIT, "reply frames busaddr= %#016jx size= %d\n",
1409 (uintmax_t)sc->reply_busaddr, rsize);
1415 mpr_alloc_requests(struct mpr_softc *sc)
1417 struct mpr_command *cm;
1418 struct mpr_chain *chain;
1419 int i, rsize, nsegs;
1421 rsize = sc->reqframesz * sc->num_reqs;
1422 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1423 16, 0, /* algnmnt, boundary */
1424 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1425 BUS_SPACE_MAXADDR, /* highaddr */
1426 NULL, NULL, /* filter, filterarg */
1427 rsize, /* maxsize */
1429 rsize, /* maxsegsize */
1431 NULL, NULL, /* lockfunc, lockarg */
1433 mpr_dprint(sc, MPR_ERROR, "Cannot allocate request DMA tag\n");
1436 if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1437 BUS_DMA_NOWAIT, &sc->req_map)) {
1438 mpr_dprint(sc, MPR_ERROR, "Cannot allocate request memory\n");
1441 bzero(sc->req_frames, rsize);
1442 bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1443 mpr_memaddr_cb, &sc->req_busaddr, 0);
1444 mpr_dprint(sc, MPR_INIT, "request frames busaddr= %#016jx size= %d\n",
1445 (uintmax_t)sc->req_busaddr, rsize);
1447 rsize = sc->chain_frame_size * sc->num_chains;
1448 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1449 16, 0, /* algnmnt, boundary */
1450 BUS_SPACE_MAXADDR, /* lowaddr */
1451 BUS_SPACE_MAXADDR, /* highaddr */
1452 NULL, NULL, /* filter, filterarg */
1453 rsize, /* maxsize */
1455 rsize, /* maxsegsize */
1457 NULL, NULL, /* lockfunc, lockarg */
1459 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain DMA tag\n");
1462 if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1463 BUS_DMA_NOWAIT, &sc->chain_map)) {
1464 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1467 bzero(sc->chain_frames, rsize);
1468 bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1469 mpr_memaddr_cb, &sc->chain_busaddr, 0);
1470 mpr_dprint(sc, MPR_INIT, "chain frames busaddr= %#016jx size= %d\n",
1471 (uintmax_t)sc->chain_busaddr, rsize);
1473 rsize = MPR_SENSE_LEN * sc->num_reqs;
1474 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1475 1, 0, /* algnmnt, boundary */
1476 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1477 BUS_SPACE_MAXADDR, /* highaddr */
1478 NULL, NULL, /* filter, filterarg */
1479 rsize, /* maxsize */
1481 rsize, /* maxsegsize */
1483 NULL, NULL, /* lockfunc, lockarg */
1485 mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense DMA tag\n");
1488 if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1489 BUS_DMA_NOWAIT, &sc->sense_map)) {
1490 mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense memory\n");
1493 bzero(sc->sense_frames, rsize);
1494 bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1495 mpr_memaddr_cb, &sc->sense_busaddr, 0);
1496 mpr_dprint(sc, MPR_INIT, "sense frames busaddr= %#016jx size= %d\n",
1497 (uintmax_t)sc->sense_busaddr, rsize);
1499 sc->chains = malloc(sizeof(struct mpr_chain) * sc->num_chains, M_MPR,
1502 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1505 for (i = 0; i < sc->num_chains; i++) {
1506 chain = &sc->chains[i];
1507 chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1508 i * sc->chain_frame_size);
1509 chain->chain_busaddr = sc->chain_busaddr +
1510 i * sc->chain_frame_size;
1511 mpr_free_chain(sc, chain);
1512 sc->chain_free_lowwater++;
1516 * Allocate NVMe PRP Pages for NVMe SGL support only if the FW supports
1519 if ((sc->facts->MsgVersion >= MPI2_VERSION_02_06) &&
1520 (sc->facts->ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES)) {
1521 if (mpr_alloc_nvme_prp_pages(sc) == ENOMEM)
1525 nsegs = (sc->maxio / PAGE_SIZE) + 1;
1526 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1527 1, 0, /* algnmnt, boundary */
1528 BUS_SPACE_MAXADDR, /* lowaddr */
1529 BUS_SPACE_MAXADDR, /* highaddr */
1530 NULL, NULL, /* filter, filterarg */
1531 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1532 nsegs, /* nsegments */
1533 BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1534 BUS_DMA_ALLOCNOW, /* flags */
1535 busdma_lock_mutex, /* lockfunc */
1536 &sc->mpr_mtx, /* lockarg */
1537 &sc->buffer_dmat)) {
1538 mpr_dprint(sc, MPR_ERROR, "Cannot allocate buffer DMA tag\n");
1543 * SMID 0 cannot be used as a free command per the firmware spec.
1544 * Just drop that command instead of risking accounting bugs.
1546 sc->commands = malloc(sizeof(struct mpr_command) * sc->num_reqs,
1547 M_MPR, M_WAITOK | M_ZERO);
1548 if (!sc->commands) {
1549 mpr_dprint(sc, MPR_ERROR, "Cannot allocate command memory\n");
1552 for (i = 1; i < sc->num_reqs; i++) {
1553 cm = &sc->commands[i];
1554 cm->cm_req = sc->req_frames + i * sc->reqframesz;
1555 cm->cm_req_busaddr = sc->req_busaddr + i * sc->reqframesz;
1556 cm->cm_sense = &sc->sense_frames[i];
1557 cm->cm_sense_busaddr = sc->sense_busaddr + i * MPR_SENSE_LEN;
1558 cm->cm_desc.Default.SMID = i;
1560 cm->cm_state = MPR_CM_STATE_BUSY;
1561 TAILQ_INIT(&cm->cm_chain_list);
1562 TAILQ_INIT(&cm->cm_prp_page_list);
1563 callout_init_mtx(&cm->cm_callout, &sc->mpr_mtx, 0);
1565 /* XXX Is a failure here a critical problem? */
1566 if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap)
1568 if (i <= sc->num_prireqs)
1569 mpr_free_high_priority_command(sc, cm);
1571 mpr_free_command(sc, cm);
1573 panic("failed to allocate command %d\n", i);
1583 * Allocate contiguous buffers for PCIe NVMe devices for building native PRPs,
1584 * which are scatter/gather lists for NVMe devices.
1586 * This buffer must be contiguous due to the nature of how NVMe PRPs are built
1587 * and translated by FW.
1589 * returns ENOMEM if memory could not be allocated, otherwise returns 0.
1592 mpr_alloc_nvme_prp_pages(struct mpr_softc *sc)
1594 int PRPs_per_page, PRPs_required, pages_required;
1596 struct mpr_prp_page *prp_page;
1599 * Assuming a MAX_IO_SIZE of 1MB and a PAGE_SIZE of 4k, the max number
1600 * of PRPs (NVMe's Scatter/Gather Element) needed per I/O is:
1601 * MAX_IO_SIZE / PAGE_SIZE = 256
1603 * 1 PRP entry in main frame for PRP list pointer still leaves 255 PRPs
1604 * required for the remainder of the 1MB I/O. 512 PRPs can fit into one
1605 * page (4096 / 8 = 512), so only one page is required for each I/O.
1607 * Each of these buffers will need to be contiguous. For simplicity,
1608 * only one buffer is allocated here, which has all of the space
1609 * required for the NVMe Queue Depth. If there are problems allocating
1610 * this one buffer, this function will need to change to allocate
1611 * individual, contiguous NVME_QDEPTH buffers.
1613 * The real calculation will use the real max io size. Above is just an
1617 PRPs_required = sc->maxio / PAGE_SIZE;
1618 PRPs_per_page = (PAGE_SIZE / PRP_ENTRY_SIZE) - 1;
1619 pages_required = (PRPs_required / PRPs_per_page) + 1;
1621 sc->prp_buffer_size = PAGE_SIZE * pages_required;
1622 rsize = sc->prp_buffer_size * NVME_QDEPTH;
1623 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1624 4, 0, /* algnmnt, boundary */
1625 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1626 BUS_SPACE_MAXADDR, /* highaddr */
1627 NULL, NULL, /* filter, filterarg */
1628 rsize, /* maxsize */
1630 rsize, /* maxsegsize */
1632 NULL, NULL, /* lockfunc, lockarg */
1633 &sc->prp_page_dmat)) {
1634 mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP DMA "
1638 if (bus_dmamem_alloc(sc->prp_page_dmat, (void **)&sc->prp_pages,
1639 BUS_DMA_NOWAIT, &sc->prp_page_map)) {
1640 mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP memory\n");
1643 bzero(sc->prp_pages, rsize);
1644 bus_dmamap_load(sc->prp_page_dmat, sc->prp_page_map, sc->prp_pages,
1645 rsize, mpr_memaddr_cb, &sc->prp_page_busaddr, 0);
1647 sc->prps = malloc(sizeof(struct mpr_prp_page) * NVME_QDEPTH, M_MPR,
1649 for (i = 0; i < NVME_QDEPTH; i++) {
1650 prp_page = &sc->prps[i];
1651 prp_page->prp_page = (uint64_t *)(sc->prp_pages +
1652 i * sc->prp_buffer_size);
1653 prp_page->prp_page_busaddr = (uint64_t)(sc->prp_page_busaddr +
1654 i * sc->prp_buffer_size);
1655 mpr_free_prp_page(sc, prp_page);
1656 sc->prp_pages_free_lowwater++;
1663 mpr_init_queues(struct mpr_softc *sc)
1667 memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1670 * According to the spec, we need to use one less reply than we
1671 * have space for on the queue. So sc->num_replies (the number we
1672 * use) should be less than sc->fqdepth (allocated size).
1674 if (sc->num_replies >= sc->fqdepth)
1678 * Initialize all of the free queue entries.
1680 for (i = 0; i < sc->fqdepth; i++) {
1681 sc->free_queue[i] = sc->reply_busaddr + (i * sc->replyframesz);
1683 sc->replyfreeindex = sc->num_replies;
1688 /* Get the driver parameter tunables. Lowest priority are the driver defaults.
1689 * Next are the global settings, if they exist. Highest are the per-unit
1690 * settings, if they exist.
1693 mpr_get_tunables(struct mpr_softc *sc)
1695 char tmpstr[80], mpr_debug[80];
1697 /* XXX default to some debugging for now */
1698 sc->mpr_debug = MPR_INFO | MPR_FAULT;
1699 sc->disable_msix = 0;
1700 sc->disable_msi = 0;
1701 sc->max_msix = MPR_MSIX_MAX;
1702 sc->max_chains = MPR_CHAIN_FRAMES;
1703 sc->max_io_pages = MPR_MAXIO_PAGES;
1704 sc->enable_ssu = MPR_SSU_ENABLE_SSD_DISABLE_HDD;
1705 sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1707 sc->max_reqframes = MPR_REQ_FRAMES;
1708 sc->max_prireqframes = MPR_PRI_REQ_FRAMES;
1709 sc->max_replyframes = MPR_REPLY_FRAMES;
1710 sc->max_evtframes = MPR_EVT_REPLY_FRAMES;
1713 * Grab the global variables.
1715 bzero(mpr_debug, 80);
1716 if (TUNABLE_STR_FETCH("hw.mpr.debug_level", mpr_debug, 80) != 0)
1717 mpr_parse_debug(sc, mpr_debug);
1718 TUNABLE_INT_FETCH("hw.mpr.disable_msix", &sc->disable_msix);
1719 TUNABLE_INT_FETCH("hw.mpr.disable_msi", &sc->disable_msi);
1720 TUNABLE_INT_FETCH("hw.mpr.max_msix", &sc->max_msix);
1721 TUNABLE_INT_FETCH("hw.mpr.max_chains", &sc->max_chains);
1722 TUNABLE_INT_FETCH("hw.mpr.max_io_pages", &sc->max_io_pages);
1723 TUNABLE_INT_FETCH("hw.mpr.enable_ssu", &sc->enable_ssu);
1724 TUNABLE_INT_FETCH("hw.mpr.spinup_wait_time", &sc->spinup_wait_time);
1725 TUNABLE_INT_FETCH("hw.mpr.use_phy_num", &sc->use_phynum);
1726 TUNABLE_INT_FETCH("hw.mpr.max_reqframes", &sc->max_reqframes);
1727 TUNABLE_INT_FETCH("hw.mpr.max_prireqframes", &sc->max_prireqframes);
1728 TUNABLE_INT_FETCH("hw.mpr.max_replyframes", &sc->max_replyframes);
1729 TUNABLE_INT_FETCH("hw.mpr.max_evtframes", &sc->max_evtframes);
1731 /* Grab the unit-instance variables */
1732 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.debug_level",
1733 device_get_unit(sc->mpr_dev));
1734 bzero(mpr_debug, 80);
1735 if (TUNABLE_STR_FETCH(tmpstr, mpr_debug, 80) != 0)
1736 mpr_parse_debug(sc, mpr_debug);
1738 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msix",
1739 device_get_unit(sc->mpr_dev));
1740 TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1742 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msi",
1743 device_get_unit(sc->mpr_dev));
1744 TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1746 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_msix",
1747 device_get_unit(sc->mpr_dev));
1748 TUNABLE_INT_FETCH(tmpstr, &sc->max_msix);
1750 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_chains",
1751 device_get_unit(sc->mpr_dev));
1752 TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1754 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_io_pages",
1755 device_get_unit(sc->mpr_dev));
1756 TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1758 bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1759 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.exclude_ids",
1760 device_get_unit(sc->mpr_dev));
1761 TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1763 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.enable_ssu",
1764 device_get_unit(sc->mpr_dev));
1765 TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1767 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.spinup_wait_time",
1768 device_get_unit(sc->mpr_dev));
1769 TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1771 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.use_phy_num",
1772 device_get_unit(sc->mpr_dev));
1773 TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1775 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_reqframes",
1776 device_get_unit(sc->mpr_dev));
1777 TUNABLE_INT_FETCH(tmpstr, &sc->max_reqframes);
1779 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_prireqframes",
1780 device_get_unit(sc->mpr_dev));
1781 TUNABLE_INT_FETCH(tmpstr, &sc->max_prireqframes);
1783 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_replyframes",
1784 device_get_unit(sc->mpr_dev));
1785 TUNABLE_INT_FETCH(tmpstr, &sc->max_replyframes);
1787 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_evtframes",
1788 device_get_unit(sc->mpr_dev));
1789 TUNABLE_INT_FETCH(tmpstr, &sc->max_evtframes);
1793 mpr_setup_sysctl(struct mpr_softc *sc)
1795 struct sysctl_ctx_list *sysctl_ctx = NULL;
1796 struct sysctl_oid *sysctl_tree = NULL;
1797 char tmpstr[80], tmpstr2[80];
1800 * Setup the sysctl variable so the user can change the debug level
1803 snprintf(tmpstr, sizeof(tmpstr), "MPR controller %d",
1804 device_get_unit(sc->mpr_dev));
1805 snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mpr_dev));
1807 sysctl_ctx = device_get_sysctl_ctx(sc->mpr_dev);
1808 if (sysctl_ctx != NULL)
1809 sysctl_tree = device_get_sysctl_tree(sc->mpr_dev);
1811 if (sysctl_tree == NULL) {
1812 sysctl_ctx_init(&sc->sysctl_ctx);
1813 sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1814 SYSCTL_STATIC_CHILDREN(_hw_mpr), OID_AUTO, tmpstr2,
1815 CTLFLAG_RD, 0, tmpstr);
1816 if (sc->sysctl_tree == NULL)
1818 sysctl_ctx = &sc->sysctl_ctx;
1819 sysctl_tree = sc->sysctl_tree;
1822 SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1823 OID_AUTO, "debug_level", CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1824 sc, 0, mpr_debug_sysctl, "A", "mpr debug level");
1826 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1827 OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1828 "Disable the use of MSI-X interrupts");
1830 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1831 OID_AUTO, "max_msix", CTLFLAG_RD, &sc->max_msix, 0,
1832 "User-defined maximum number of MSIX queues");
1834 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1835 OID_AUTO, "msix_msgs", CTLFLAG_RD, &sc->msi_msgs, 0,
1836 "Negotiated number of MSIX queues");
1838 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1839 OID_AUTO, "max_reqframes", CTLFLAG_RD, &sc->max_reqframes, 0,
1840 "Total number of allocated request frames");
1842 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1843 OID_AUTO, "max_prireqframes", CTLFLAG_RD, &sc->max_prireqframes, 0,
1844 "Total number of allocated high priority request frames");
1846 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1847 OID_AUTO, "max_replyframes", CTLFLAG_RD, &sc->max_replyframes, 0,
1848 "Total number of allocated reply frames");
1850 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1851 OID_AUTO, "max_evtframes", CTLFLAG_RD, &sc->max_evtframes, 0,
1852 "Total number of event frames allocated");
1854 SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1855 OID_AUTO, "firmware_version", CTLFLAG_RW, sc->fw_version,
1856 strlen(sc->fw_version), "firmware version");
1858 SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1859 OID_AUTO, "driver_version", CTLFLAG_RW, MPR_DRIVER_VERSION,
1860 strlen(MPR_DRIVER_VERSION), "driver version");
1862 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1863 OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1864 &sc->io_cmds_active, 0, "number of currently active commands");
1866 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1867 OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1868 &sc->io_cmds_highwater, 0, "maximum active commands seen");
1870 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1871 OID_AUTO, "chain_free", CTLFLAG_RD,
1872 &sc->chain_free, 0, "number of free chain elements");
1874 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1875 OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1876 &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1878 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1879 OID_AUTO, "max_chains", CTLFLAG_RD,
1880 &sc->max_chains, 0,"maximum chain frames that will be allocated");
1882 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1883 OID_AUTO, "max_io_pages", CTLFLAG_RD,
1884 &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1887 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1888 OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1889 "enable SSU to SATA SSD/HDD at shutdown");
1891 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1892 OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1893 &sc->chain_alloc_fail, "chain allocation failures");
1895 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1896 OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1897 &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1898 "spinup after SATA ID error");
1900 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1901 OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1902 "Use the phy number for enumeration");
1904 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1905 OID_AUTO, "prp_pages_free", CTLFLAG_RD,
1906 &sc->prp_pages_free, 0, "number of free PRP pages");
1908 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1909 OID_AUTO, "prp_pages_free_lowwater", CTLFLAG_RD,
1910 &sc->prp_pages_free_lowwater, 0,"lowest number of free PRP pages");
1912 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1913 OID_AUTO, "prp_page_alloc_fail", CTLFLAG_RD,
1914 &sc->prp_page_alloc_fail, "PRP page allocation failures");
1917 static struct mpr_debug_string {
1920 } mpr_debug_strings[] = {
1922 {"fault", MPR_FAULT},
1923 {"event", MPR_EVENT},
1925 {"recovery", MPR_RECOVERY},
1926 {"error", MPR_ERROR},
1928 {"xinfo", MPR_XINFO},
1930 {"mapping", MPR_MAPPING},
1931 {"trace", MPR_TRACE}
1934 enum mpr_debug_level_combiner {
1941 mpr_debug_sysctl(SYSCTL_HANDLER_ARGS)
1943 struct mpr_softc *sc;
1944 struct mpr_debug_string *string;
1948 int i, len, debug, error;
1950 sc = (struct mpr_softc *)arg1;
1952 error = sysctl_wire_old_buffer(req, 0);
1956 sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
1957 debug = sc->mpr_debug;
1959 sbuf_printf(sbuf, "%#x", debug);
1961 sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
1962 for (i = 0; i < sz; i++) {
1963 string = &mpr_debug_strings[i];
1964 if (debug & string->flag)
1965 sbuf_printf(sbuf, ",%s", string->name);
1968 error = sbuf_finish(sbuf);
1971 if (error || req->newptr == NULL)
1974 len = req->newlen - req->newidx;
1978 buffer = malloc(len, M_MPR, M_ZERO|M_WAITOK);
1979 error = SYSCTL_IN(req, buffer, len);
1981 mpr_parse_debug(sc, buffer);
1983 free(buffer, M_MPR);
1988 mpr_parse_debug(struct mpr_softc *sc, char *list)
1990 struct mpr_debug_string *string;
1991 enum mpr_debug_level_combiner op;
1992 char *token, *endtoken;
1996 if (list == NULL || *list == '\0')
2002 } else if (*list == '-') {
2011 sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
2012 while ((token = strsep(&list, ":,")) != NULL) {
2014 /* Handle integer flags */
2015 flags |= strtol(token, &endtoken, 0);
2016 if (token != endtoken)
2019 /* Handle text flags */
2020 for (i = 0; i < sz; i++) {
2021 string = &mpr_debug_strings[i];
2022 if (strcasecmp(token, string->name) == 0) {
2023 flags |= string->flag;
2031 sc->mpr_debug = flags;
2034 sc->mpr_debug |= flags;
2037 sc->mpr_debug &= (~flags);
2044 mpr_attach(struct mpr_softc *sc)
2049 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2051 mtx_init(&sc->mpr_mtx, "MPR lock", NULL, MTX_DEF);
2052 callout_init_mtx(&sc->periodic, &sc->mpr_mtx, 0);
2053 callout_init_mtx(&sc->device_check_callout, &sc->mpr_mtx, 0);
2054 TAILQ_INIT(&sc->event_list);
2055 timevalclear(&sc->lastfail);
2057 if ((error = mpr_transition_ready(sc)) != 0) {
2058 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
2059 "Failed to transition ready\n");
2063 sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPR,
2066 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
2067 "Cannot allocate memory, exit\n");
2072 * Get IOC Facts and allocate all structures based on this information.
2073 * A Diag Reset will also call mpr_iocfacts_allocate and re-read the IOC
2074 * Facts. If relevant values have changed in IOC Facts, this function
2075 * will free all of the memory based on IOC Facts and reallocate that
2076 * memory. If this fails, any allocated memory should already be freed.
2078 if ((error = mpr_iocfacts_allocate(sc, TRUE)) != 0) {
2079 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC Facts allocation "
2080 "failed with error %d\n", error);
2084 /* Start the periodic watchdog check on the IOC Doorbell */
2088 * The portenable will kick off discovery events that will drive the
2089 * rest of the initialization process. The CAM/SAS module will
2090 * hold up the boot sequence until discovery is complete.
2092 sc->mpr_ich.ich_func = mpr_startup;
2093 sc->mpr_ich.ich_arg = sc;
2094 if (config_intrhook_establish(&sc->mpr_ich) != 0) {
2095 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
2096 "Cannot establish MPR config hook\n");
2101 * Allow IR to shutdown gracefully when shutdown occurs.
2103 sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
2104 mprsas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
2106 if (sc->shutdown_eh == NULL)
2107 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
2108 "shutdown event registration failed\n");
2110 mpr_setup_sysctl(sc);
2112 sc->mpr_flags |= MPR_FLAGS_ATTACH_DONE;
2113 mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
2118 /* Run through any late-start handlers. */
2120 mpr_startup(void *arg)
2122 struct mpr_softc *sc;
2124 sc = (struct mpr_softc *)arg;
2125 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2128 mpr_unmask_intr(sc);
2130 /* initialize device mapping tables */
2131 mpr_base_static_config_pages(sc);
2132 mpr_mapping_initialize(sc);
2136 mpr_dprint(sc, MPR_INIT, "disestablish config intrhook\n");
2137 config_intrhook_disestablish(&sc->mpr_ich);
2138 sc->mpr_ich.ich_arg = NULL;
2140 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2143 /* Periodic watchdog. Is called with the driver lock already held. */
2145 mpr_periodic(void *arg)
2147 struct mpr_softc *sc;
2150 sc = (struct mpr_softc *)arg;
2151 if (sc->mpr_flags & MPR_FLAGS_SHUTDOWN)
2154 db = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
2155 if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
2156 if ((db & MPI2_DOORBELL_FAULT_CODE_MASK) ==
2157 IFAULT_IOP_OVER_TEMP_THRESHOLD_EXCEEDED) {
2158 panic("TEMPERATURE FAULT: STOPPING.");
2160 mpr_dprint(sc, MPR_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
2164 callout_reset(&sc->periodic, MPR_PERIODIC_DELAY * hz, mpr_periodic, sc);
2168 mpr_log_evt_handler(struct mpr_softc *sc, uintptr_t data,
2169 MPI2_EVENT_NOTIFICATION_REPLY *event)
2171 MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
2173 MPR_DPRINT_EVENT(sc, generic, event);
2175 switch (event->Event) {
2176 case MPI2_EVENT_LOG_DATA:
2177 mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_DATA:\n");
2178 if (sc->mpr_debug & MPR_EVENT)
2179 hexdump(event->EventData, event->EventDataLength, NULL,
2182 case MPI2_EVENT_LOG_ENTRY_ADDED:
2183 entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
2184 mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
2185 "0x%x Sequence %d:\n", entry->LogEntryQualifier,
2186 entry->LogSequence);
2195 mpr_attach_log(struct mpr_softc *sc)
2200 setbit(events, MPI2_EVENT_LOG_DATA);
2201 setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
2203 mpr_register_events(sc, events, mpr_log_evt_handler, NULL,
2210 mpr_detach_log(struct mpr_softc *sc)
2213 if (sc->mpr_log_eh != NULL)
2214 mpr_deregister_events(sc, sc->mpr_log_eh);
2219 * Free all of the driver resources and detach submodules. Should be called
2220 * without the lock held.
2223 mpr_free(struct mpr_softc *sc)
2227 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2228 /* Turn off the watchdog */
2230 sc->mpr_flags |= MPR_FLAGS_SHUTDOWN;
2232 /* Lock must not be held for this */
2233 callout_drain(&sc->periodic);
2234 callout_drain(&sc->device_check_callout);
2236 if (((error = mpr_detach_log(sc)) != 0) ||
2237 ((error = mpr_detach_sas(sc)) != 0)) {
2238 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "failed to detach "
2239 "subsystems, error= %d, exit\n", error);
2243 mpr_detach_user(sc);
2245 /* Put the IOC back in the READY state. */
2247 if ((error = mpr_transition_ready(sc)) != 0) {
2253 if (sc->facts != NULL)
2254 free(sc->facts, M_MPR);
2257 * Free all buffers that are based on IOC Facts. A Diag Reset may need
2258 * to free these buffers too.
2260 mpr_iocfacts_free(sc);
2262 if (sc->sysctl_tree != NULL)
2263 sysctl_ctx_free(&sc->sysctl_ctx);
2265 /* Deregister the shutdown function */
2266 if (sc->shutdown_eh != NULL)
2267 EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
2269 mtx_destroy(&sc->mpr_mtx);
2270 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2275 static __inline void
2276 mpr_complete_command(struct mpr_softc *sc, struct mpr_command *cm)
2281 mpr_dprint(sc, MPR_ERROR, "Completing NULL command\n");
2285 if (cm->cm_flags & MPR_CM_FLAGS_POLLED)
2286 cm->cm_flags |= MPR_CM_FLAGS_COMPLETE;
2288 if (cm->cm_complete != NULL) {
2289 mpr_dprint(sc, MPR_TRACE,
2290 "%s cm %p calling cm_complete %p data %p reply %p\n",
2291 __func__, cm, cm->cm_complete, cm->cm_complete_data,
2293 cm->cm_complete(sc, cm);
2296 if (cm->cm_flags & MPR_CM_FLAGS_WAKEUP) {
2297 mpr_dprint(sc, MPR_TRACE, "waking up %p\n", cm);
2301 if (sc->io_cmds_active != 0) {
2302 sc->io_cmds_active--;
2304 mpr_dprint(sc, MPR_ERROR, "Warning: io_cmds_active is "
2305 "out of sync - resynching to 0\n");
2310 mpr_sas_log_info(struct mpr_softc *sc , u32 log_info)
2312 union loginfo_type {
2321 union loginfo_type sas_loginfo;
2322 char *originator_str = NULL;
2324 sas_loginfo.loginfo = log_info;
2325 if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
2328 /* each nexus loss loginfo */
2329 if (log_info == 0x31170000)
2332 /* eat the loginfos associated with task aborts */
2333 if ((log_info == 30050000) || (log_info == 0x31140000) ||
2334 (log_info == 0x31130000))
2337 switch (sas_loginfo.dw.originator) {
2339 originator_str = "IOP";
2342 originator_str = "PL";
2345 originator_str = "IR";
2349 mpr_dprint(sc, MPR_LOG, "log_info(0x%08x): originator(%s), "
2350 "code(0x%02x), sub_code(0x%04x)\n", log_info, originator_str,
2351 sas_loginfo.dw.code, sas_loginfo.dw.subcode);
2355 mpr_display_reply_info(struct mpr_softc *sc, uint8_t *reply)
2357 MPI2DefaultReply_t *mpi_reply;
2360 mpi_reply = (MPI2DefaultReply_t*)reply;
2361 sc_status = le16toh(mpi_reply->IOCStatus);
2362 if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
2363 mpr_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
2367 mpr_intr(void *data)
2369 struct mpr_softc *sc;
2372 sc = (struct mpr_softc *)data;
2373 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2376 * Check interrupt status register to flush the bus. This is
2377 * needed for both INTx interrupts and driver-driven polling
2379 status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
2380 if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
2384 mpr_intr_locked(data);
2390 * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
2391 * chip. Hopefully this theory is correct.
2394 mpr_intr_msi(void *data)
2396 struct mpr_softc *sc;
2398 sc = (struct mpr_softc *)data;
2399 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2401 mpr_intr_locked(data);
2407 * The locking is overly broad and simplistic, but easy to deal with for now.
2410 mpr_intr_locked(void *data)
2412 MPI2_REPLY_DESCRIPTORS_UNION *desc;
2413 struct mpr_softc *sc;
2414 struct mpr_command *cm = NULL;
2417 MPI2_DIAG_RELEASE_REPLY *rel_rep;
2418 mpr_fw_diagnostic_buffer_t *pBuffer;
2420 sc = (struct mpr_softc *)data;
2422 pq = sc->replypostindex;
2423 mpr_dprint(sc, MPR_TRACE,
2424 "%s sc %p starting with replypostindex %u\n",
2425 __func__, sc, sc->replypostindex);
2429 desc = &sc->post_queue[sc->replypostindex];
2430 flags = desc->Default.ReplyFlags &
2431 MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
2432 if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) ||
2433 (le32toh(desc->Words.High) == 0xffffffff))
2436 /* increment the replypostindex now, so that event handlers
2437 * and cm completion handlers which decide to do a diag
2438 * reset can zero it without it getting incremented again
2439 * afterwards, and we break out of this loop on the next
2440 * iteration since the reply post queue has been cleared to
2441 * 0xFF and all descriptors look unused (which they are).
2443 if (++sc->replypostindex >= sc->pqdepth)
2444 sc->replypostindex = 0;
2447 case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
2448 case MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS:
2449 case MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS:
2450 cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
2451 KASSERT(cm->cm_state == MPR_CM_STATE_INQUEUE,
2452 ("command not inqueue\n"));
2453 cm->cm_state = MPR_CM_STATE_BUSY;
2454 cm->cm_reply = NULL;
2456 case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
2462 * Re-compose the reply address from the address
2463 * sent back from the chip. The ReplyFrameAddress
2464 * is the lower 32 bits of the physical address of
2465 * particular reply frame. Convert that address to
2466 * host format, and then use that to provide the
2467 * offset against the virtual address base
2468 * (sc->reply_frames).
2470 baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
2471 reply = sc->reply_frames +
2472 (baddr - ((uint32_t)sc->reply_busaddr));
2474 * Make sure the reply we got back is in a valid
2475 * range. If not, go ahead and panic here, since
2476 * we'll probably panic as soon as we deference the
2477 * reply pointer anyway.
2479 if ((reply < sc->reply_frames)
2480 || (reply > (sc->reply_frames +
2481 (sc->fqdepth * sc->replyframesz)))) {
2482 printf("%s: WARNING: reply %p out of range!\n",
2484 printf("%s: reply_frames %p, fqdepth %d, "
2485 "frame size %d\n", __func__,
2486 sc->reply_frames, sc->fqdepth,
2488 printf("%s: baddr %#x,\n", __func__, baddr);
2489 /* LSI-TODO. See Linux Code for Graceful exit */
2490 panic("Reply address out of range");
2492 if (le16toh(desc->AddressReply.SMID) == 0) {
2493 if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
2494 MPI2_FUNCTION_DIAG_BUFFER_POST) {
2496 * If SMID is 0 for Diag Buffer Post,
2497 * this implies that the reply is due to
2498 * a release function with a status that
2499 * the buffer has been released. Set
2500 * the buffer flags accordingly.
2503 (MPI2_DIAG_RELEASE_REPLY *)reply;
2504 if ((le16toh(rel_rep->IOCStatus) &
2505 MPI2_IOCSTATUS_MASK) ==
2506 MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2509 &sc->fw_diag_buffer_list[
2510 rel_rep->BufferType];
2511 pBuffer->valid_data = TRUE;
2512 pBuffer->owned_by_firmware =
2514 pBuffer->immediate = FALSE;
2517 mpr_dispatch_event(sc, baddr,
2518 (MPI2_EVENT_NOTIFICATION_REPLY *)
2522 le16toh(desc->AddressReply.SMID)];
2523 KASSERT(cm->cm_state == MPR_CM_STATE_INQUEUE,
2524 ("command not inqueue\n"));
2525 cm->cm_state = MPR_CM_STATE_BUSY;
2526 cm->cm_reply = reply;
2528 le32toh(desc->AddressReply.
2533 case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2534 case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2535 case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2538 mpr_dprint(sc, MPR_ERROR, "Unhandled reply 0x%x\n",
2539 desc->Default.ReplyFlags);
2545 // Print Error reply frame
2547 mpr_display_reply_info(sc,cm->cm_reply);
2548 mpr_complete_command(sc, cm);
2551 desc->Words.Low = 0xffffffff;
2552 desc->Words.High = 0xffffffff;
2555 if (pq != sc->replypostindex) {
2556 mpr_dprint(sc, MPR_TRACE, "%s sc %p writing postindex %d\n",
2557 __func__, sc, sc->replypostindex);
2558 mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
2559 sc->replypostindex);
2566 mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
2567 MPI2_EVENT_NOTIFICATION_REPLY *reply)
2569 struct mpr_event_handle *eh;
2570 int event, handled = 0;
2572 event = le16toh(reply->Event);
2573 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2574 if (isset(eh->mask, event)) {
2575 eh->callback(sc, data, reply);
2581 mpr_dprint(sc, MPR_EVENT, "Unhandled event 0x%x\n",
2585 * This is the only place that the event/reply should be freed.
2586 * Anything wanting to hold onto the event data should have
2587 * already copied it into their own storage.
2589 mpr_free_reply(sc, data);
2593 mpr_reregister_events_complete(struct mpr_softc *sc, struct mpr_command *cm)
2595 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2598 MPR_DPRINT_EVENT(sc, generic,
2599 (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2601 mpr_free_command(sc, cm);
2603 /* next, send a port enable */
2608 * For both register_events and update_events, the caller supplies a bitmap
2609 * of events that it _wants_. These functions then turn that into a bitmask
2610 * suitable for the controller.
2613 mpr_register_events(struct mpr_softc *sc, uint8_t *mask,
2614 mpr_evt_callback_t *cb, void *data, struct mpr_event_handle **handle)
2616 struct mpr_event_handle *eh;
2619 eh = malloc(sizeof(struct mpr_event_handle), M_MPR, M_WAITOK|M_ZERO);
2621 mpr_dprint(sc, MPR_EVENT|MPR_ERROR,
2622 "Cannot allocate event memory\n");
2627 TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2629 error = mpr_update_events(sc, eh, mask);
2636 mpr_update_events(struct mpr_softc *sc, struct mpr_event_handle *handle,
2639 MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2640 MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2641 struct mpr_command *cm = NULL;
2642 struct mpr_event_handle *eh;
2645 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2647 if ((mask != NULL) && (handle != NULL))
2648 bcopy(mask, &handle->mask[0], 16);
2649 memset(sc->event_mask, 0xff, 16);
2651 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2652 for (i = 0; i < 16; i++)
2653 sc->event_mask[i] &= ~eh->mask[i];
2656 if ((cm = mpr_alloc_command(sc)) == NULL)
2658 evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2659 evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2660 evtreq->MsgFlags = 0;
2661 evtreq->SASBroadcastPrimitiveMasks = 0;
2662 #ifdef MPR_DEBUG_ALL_EVENTS
2664 u_char fullmask[16];
2665 memset(fullmask, 0x00, 16);
2666 bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2669 bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2671 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2674 error = mpr_request_polled(sc, &cm);
2676 reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2677 if ((reply == NULL) ||
2678 (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2682 MPR_DPRINT_EVENT(sc, generic, reply);
2684 mpr_dprint(sc, MPR_TRACE, "%s finished error %d\n", __func__, error);
2687 mpr_free_command(sc, cm);
2692 mpr_reregister_events(struct mpr_softc *sc)
2694 MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2695 struct mpr_command *cm;
2696 struct mpr_event_handle *eh;
2699 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2701 /* first, reregister events */
2703 memset(sc->event_mask, 0xff, 16);
2705 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2706 for (i = 0; i < 16; i++)
2707 sc->event_mask[i] &= ~eh->mask[i];
2710 if ((cm = mpr_alloc_command(sc)) == NULL)
2712 evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2713 evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2714 evtreq->MsgFlags = 0;
2715 evtreq->SASBroadcastPrimitiveMasks = 0;
2716 #ifdef MPR_DEBUG_ALL_EVENTS
2718 u_char fullmask[16];
2719 memset(fullmask, 0x00, 16);
2720 bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2723 bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2725 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2727 cm->cm_complete = mpr_reregister_events_complete;
2729 error = mpr_map_command(sc, cm);
2731 mpr_dprint(sc, MPR_TRACE, "%s finished with error %d\n", __func__,
2737 mpr_deregister_events(struct mpr_softc *sc, struct mpr_event_handle *handle)
2740 TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2741 free(handle, M_MPR);
2742 return (mpr_update_events(sc, NULL, NULL));
2746 * mpr_build_nvme_prp - This function is called for NVMe end devices to build a
2747 * native SGL (NVMe PRP). The native SGL is built starting in the first PRP entry
2748 * of the NVMe message (PRP1). If the data buffer is small enough to be described
2749 * entirely using PRP1, then PRP2 is not used. If needed, PRP2 is used to
2750 * describe a larger data buffer. If the data buffer is too large to describe
2751 * using the two PRP entriess inside the NVMe message, then PRP1 describes the
2752 * first data memory segment, and PRP2 contains a pointer to a PRP list located
2753 * elsewhere in memory to describe the remaining data memory segments. The PRP
2754 * list will be contiguous.
2756 * The native SGL for NVMe devices is a Physical Region Page (PRP). A PRP
2757 * consists of a list of PRP entries to describe a number of noncontigous
2758 * physical memory segments as a single memory buffer, just as a SGL does. Note
2759 * however, that this function is only used by the IOCTL call, so the memory
2760 * given will be guaranteed to be contiguous. There is no need to translate
2761 * non-contiguous SGL into a PRP in this case. All PRPs will describe contiguous
2762 * space that is one page size each.
2764 * Each NVMe message contains two PRP entries. The first (PRP1) either contains
2765 * a PRP list pointer or a PRP element, depending upon the command. PRP2 contains
2766 * the second PRP element if the memory being described fits within 2 PRP
2767 * entries, or a PRP list pointer if the PRP spans more than two entries.
2769 * A PRP list pointer contains the address of a PRP list, structured as a linear
2770 * array of PRP entries. Each PRP entry in this list describes a segment of
2773 * Each 64-bit PRP entry comprises an address and an offset field. The address
2774 * always points to the beginning of a PAGE_SIZE physical memory page, and the
2775 * offset describes where within that page the memory segment begins. Only the
2776 * first element in a PRP list may contain a non-zero offest, implying that all
2777 * memory segments following the first begin at the start of a PAGE_SIZE page.
2779 * Each PRP element normally describes a chunck of PAGE_SIZE physical memory,
2780 * with exceptions for the first and last elements in the list. If the memory
2781 * being described by the list begins at a non-zero offset within the first page,
2782 * then the first PRP element will contain a non-zero offset indicating where the
2783 * region begins within the page. The last memory segment may end before the end
2784 * of the PAGE_SIZE segment, depending upon the overall size of the memory being
2785 * described by the PRP list.
2787 * Since PRP entries lack any indication of size, the overall data buffer length
2788 * is used to determine where the end of the data memory buffer is located, and
2789 * how many PRP entries are required to describe it.
2794 mpr_build_nvme_prp(struct mpr_softc *sc, struct mpr_command *cm,
2795 Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request, void *data,
2796 uint32_t data_in_sz, uint32_t data_out_sz)
2798 int prp_size = PRP_ENTRY_SIZE;
2799 uint64_t *prp_entry, *prp1_entry, *prp2_entry;
2800 uint64_t *prp_entry_phys, *prp_page, *prp_page_phys;
2801 uint32_t offset, entry_len, page_mask_result, page_mask;
2804 struct mpr_prp_page *prp_page_info = NULL;
2807 * Not all commands require a data transfer. If no data, just return
2808 * without constructing any PRP.
2810 if (!data_in_sz && !data_out_sz)
2814 * Set pointers to PRP1 and PRP2, which are in the NVMe command. PRP1 is
2815 * located at a 24 byte offset from the start of the NVMe command. Then
2816 * set the current PRP entry pointer to PRP1.
2818 prp1_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2819 NVME_CMD_PRP1_OFFSET);
2820 prp2_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2821 NVME_CMD_PRP2_OFFSET);
2822 prp_entry = prp1_entry;
2825 * For the PRP entries, use the specially allocated buffer of
2826 * contiguous memory. PRP Page allocation failures should not happen
2827 * because there should be enough PRP page buffers to account for the
2828 * possible NVMe QDepth.
2830 prp_page_info = mpr_alloc_prp_page(sc);
2831 KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
2832 "used for building a native NVMe SGL.\n", __func__));
2833 prp_page = (uint64_t *)prp_page_info->prp_page;
2834 prp_page_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
2837 * Insert the allocated PRP page into the command's PRP page list. This
2838 * will be freed when the command is freed.
2840 TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
2843 * Check if we are within 1 entry of a page boundary we don't want our
2844 * first entry to be a PRP List entry.
2846 page_mask = PAGE_SIZE - 1;
2847 page_mask_result = (uintptr_t)((uint8_t *)prp_page + prp_size) &
2849 if (!page_mask_result)
2851 /* Bump up to next page boundary. */
2852 prp_page = (uint64_t *)((uint8_t *)prp_page + prp_size);
2853 prp_page_phys = (uint64_t *)((uint8_t *)prp_page_phys +
2858 * Set PRP physical pointer, which initially points to the current PRP
2861 prp_entry_phys = prp_page_phys;
2863 /* Get physical address and length of the data buffer. */
2864 paddr = (bus_addr_t)(uintptr_t)data;
2866 length = data_in_sz;
2868 length = data_out_sz;
2870 /* Loop while the length is not zero. */
2874 * Check if we need to put a list pointer here if we are at page
2875 * boundary - prp_size (8 bytes).
2877 page_mask_result = (uintptr_t)((uint8_t *)prp_entry_phys +
2878 prp_size) & page_mask;
2879 if (!page_mask_result)
2882 * This is the last entry in a PRP List, so we need to
2883 * put a PRP list pointer here. What this does is:
2884 * - bump the current memory pointer to the next
2885 * address, which will be the next full page.
2886 * - set the PRP Entry to point to that page. This is
2887 * now the PRP List pointer.
2888 * - bump the PRP Entry pointer the start of the next
2889 * page. Since all of this PRP memory is contiguous,
2890 * no need to get a new page - it's just the next
2895 htole64((uint64_t)(uintptr_t)prp_entry_phys);
2899 /* Need to handle if entry will be part of a page. */
2900 offset = (uint32_t)paddr & page_mask;
2901 entry_len = PAGE_SIZE - offset;
2903 if (prp_entry == prp1_entry)
2906 * Must fill in the first PRP pointer (PRP1) before
2909 *prp1_entry = htole64((uint64_t)paddr);
2912 * Now point to the second PRP entry within the
2915 prp_entry = prp2_entry;
2917 else if (prp_entry == prp2_entry)
2920 * Should the PRP2 entry be a PRP List pointer or just a
2921 * regular PRP pointer? If there is more than one more
2922 * page of data, must use a PRP List pointer.
2924 if (length > PAGE_SIZE)
2927 * PRP2 will contain a PRP List pointer because
2928 * more PRP's are needed with this command. The
2929 * list will start at the beginning of the
2930 * contiguous buffer.
2934 (uint64_t)(uintptr_t)prp_entry_phys);
2937 * The next PRP Entry will be the start of the
2940 prp_entry = prp_page;
2945 * After this, the PRP Entries are complete.
2946 * This command uses 2 PRP's and no PRP list.
2948 *prp2_entry = htole64((uint64_t)paddr);
2954 * Put entry in list and bump the addresses.
2956 * After PRP1 and PRP2 are filled in, this will fill in
2957 * all remaining PRP entries in a PRP List, one per each
2958 * time through the loop.
2960 *prp_entry = htole64((uint64_t)paddr);
2966 * Bump the phys address of the command's data buffer by the
2971 /* Decrement length accounting for last partial page. */
2972 if (entry_len > length)
2975 length -= entry_len;
2980 * mpr_check_pcie_native_sgl - This function is called for PCIe end devices to
2981 * determine if the driver needs to build a native SGL. If so, that native SGL
2982 * is built in the contiguous buffers allocated especially for PCIe SGL
2983 * creation. If the driver will not build a native SGL, return TRUE and a
2984 * normal IEEE SGL will be built. Currently this routine supports NVMe devices
2987 * Returns FALSE (0) if native SGL was built, TRUE (1) if no SGL was built.
2990 mpr_check_pcie_native_sgl(struct mpr_softc *sc, struct mpr_command *cm,
2991 bus_dma_segment_t *segs, int segs_left)
2993 uint32_t i, sge_dwords, length, offset, entry_len;
2994 uint32_t num_entries, buff_len = 0, sges_in_segment;
2995 uint32_t page_mask, page_mask_result, *curr_buff;
2996 uint32_t *ptr_sgl, *ptr_first_sgl, first_page_offset;
2997 uint32_t first_page_data_size, end_residual;
3000 int build_native_sgl = 0, first_prp_entry;
3001 int prp_size = PRP_ENTRY_SIZE;
3002 Mpi25IeeeSgeChain64_t *main_chain_element = NULL;
3003 struct mpr_prp_page *prp_page_info = NULL;
3005 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
3008 * Add up the sizes of each segment length to get the total transfer
3009 * size, which will be checked against the Maximum Data Transfer Size.
3010 * If the data transfer length exceeds the MDTS for this device, just
3011 * return 1 so a normal IEEE SGL will be built. F/W will break the I/O
3012 * up into multiple I/O's. [nvme_mdts = 0 means unlimited]
3014 for (i = 0; i < segs_left; i++)
3015 buff_len += htole32(segs[i].ds_len);
3016 if ((cm->cm_targ->MDTS > 0) && (buff_len > cm->cm_targ->MDTS))
3019 /* Create page_mask (to get offset within page) */
3020 page_mask = PAGE_SIZE - 1;
3023 * Check if the number of elements exceeds the max number that can be
3024 * put in the main message frame (H/W can only translate an SGL that
3025 * is contained entirely in the main message frame).
3027 sges_in_segment = (sc->reqframesz -
3028 offsetof(Mpi25SCSIIORequest_t, SGL)) / sizeof(MPI25_SGE_IO_UNION);
3029 if (segs_left > sges_in_segment)
3030 build_native_sgl = 1;
3034 * NVMe uses one PRP for each physical page (or part of physical
3036 * if 4 pages or less then IEEE is OK
3037 * if > 5 pages then we need to build a native SGL
3038 * if > 4 and <= 5 pages, then check the physical address of
3039 * the first SG entry, then if this first size in the page
3040 * is >= the residual beyond 4 pages then use IEEE,
3041 * otherwise use native SGL
3043 if (buff_len > (PAGE_SIZE * 5))
3044 build_native_sgl = 1;
3045 else if ((buff_len > (PAGE_SIZE * 4)) &&
3046 (buff_len <= (PAGE_SIZE * 5)) )
3048 msg_phys = (uint64_t *)(uintptr_t)segs[0].ds_addr;
3050 ((uint32_t)(uint64_t)(uintptr_t)msg_phys &
3052 first_page_data_size = PAGE_SIZE - first_page_offset;
3053 end_residual = buff_len % PAGE_SIZE;
3056 * If offset into first page pushes the end of the data
3057 * beyond end of the 5th page, we need the extra PRP
3060 if (first_page_data_size < end_residual)
3061 build_native_sgl = 1;
3064 * Check if first SG entry size is < residual beyond 4
3067 if (htole32(segs[0].ds_len) <
3068 (buff_len - (PAGE_SIZE * 4)))
3069 build_native_sgl = 1;
3073 /* check if native SGL is needed */
3074 if (!build_native_sgl)
3078 * Native SGL is needed.
3079 * Put a chain element in main message frame that points to the first
3082 * NOTE: The ChainOffset field must be 0 when using a chain pointer to
3086 /* Set main message chain element pointer */
3087 main_chain_element = (pMpi25IeeeSgeChain64_t)cm->cm_sge;
3090 * For NVMe the chain element needs to be the 2nd SGL entry in the main
3093 main_chain_element = (Mpi25IeeeSgeChain64_t *)
3094 ((uint8_t *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
3097 * For the PRP entries, use the specially allocated buffer of
3098 * contiguous memory. PRP Page allocation failures should not happen
3099 * because there should be enough PRP page buffers to account for the
3100 * possible NVMe QDepth.
3102 prp_page_info = mpr_alloc_prp_page(sc);
3103 KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
3104 "used for building a native NVMe SGL.\n", __func__));
3105 curr_buff = (uint32_t *)prp_page_info->prp_page;
3106 msg_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
3109 * Insert the allocated PRP page into the command's PRP page list. This
3110 * will be freed when the command is freed.
3112 TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
3115 * Check if we are within 1 entry of a page boundary we don't want our
3116 * first entry to be a PRP List entry.
3118 page_mask_result = (uintptr_t)((uint8_t *)curr_buff + prp_size) &
3120 if (!page_mask_result) {
3121 /* Bump up to next page boundary. */
3122 curr_buff = (uint32_t *)((uint8_t *)curr_buff + prp_size);
3123 msg_phys = (uint64_t *)((uint8_t *)msg_phys + prp_size);
3126 /* Fill in the chain element and make it an NVMe segment type. */
3127 main_chain_element->Address.High =
3128 htole32((uint32_t)((uint64_t)(uintptr_t)msg_phys >> 32));
3129 main_chain_element->Address.Low =
3130 htole32((uint32_t)(uintptr_t)msg_phys);
3131 main_chain_element->NextChainOffset = 0;
3132 main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3133 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3134 MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
3136 /* Set SGL pointer to start of contiguous PCIe buffer. */
3137 ptr_sgl = curr_buff;
3142 * NVMe has a very convoluted PRP format. One PRP is required for each
3143 * page or partial page. We need to split up OS SG entries if they are
3144 * longer than one page or cross a page boundary. We also have to insert
3145 * a PRP list pointer entry as the last entry in each physical page of
3148 * NOTE: The first PRP "entry" is actually placed in the first SGL entry
3149 * in the main message in IEEE 64 format. The 2nd entry in the main
3150 * message is the chain element, and the rest of the PRP entries are
3151 * built in the contiguous PCIe buffer.
3153 first_prp_entry = 1;
3154 ptr_first_sgl = (uint32_t *)cm->cm_sge;
3156 for (i = 0; i < segs_left; i++) {
3157 /* Get physical address and length of this SG entry. */
3158 paddr = segs[i].ds_addr;
3159 length = segs[i].ds_len;
3162 * Check whether a given SGE buffer lies on a non-PAGED
3163 * boundary if this is not the first page. If so, this is not
3164 * expected so have FW build the SGL.
3166 if ((i != 0) && (((uint32_t)paddr & page_mask) != 0)) {
3167 mpr_dprint(sc, MPR_ERROR, "Unaligned SGE while "
3168 "building NVMe PRPs, low address is 0x%x\n",
3173 /* Apart from last SGE, if any other SGE boundary is not page
3174 * aligned then it means that hole exists. Existence of hole
3175 * leads to data corruption. So fallback to IEEE SGEs.
3177 if (i != (segs_left - 1)) {
3178 if (((uint32_t)paddr + length) & page_mask) {
3179 mpr_dprint(sc, MPR_ERROR, "Unaligned SGE "
3180 "boundary while building NVMe PRPs, low "
3181 "address: 0x%x and length: %u\n",
3182 (uint32_t)paddr, length);
3187 /* Loop while the length is not zero. */
3190 * Check if we need to put a list pointer here if we are
3191 * at page boundary - prp_size.
3193 page_mask_result = (uintptr_t)((uint8_t *)ptr_sgl +
3194 prp_size) & page_mask;
3195 if (!page_mask_result) {
3197 * Need to put a PRP list pointer here.
3199 msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3201 *ptr_sgl = htole32((uintptr_t)msg_phys);
3202 *(ptr_sgl+1) = htole32((uint64_t)(uintptr_t)
3204 ptr_sgl += sge_dwords;
3208 /* Need to handle if entry will be part of a page. */
3209 offset = (uint32_t)paddr & page_mask;
3210 entry_len = PAGE_SIZE - offset;
3211 if (first_prp_entry) {
3213 * Put IEEE entry in first SGE in main message.
3214 * (Simple element, System addr, not end of
3217 *ptr_first_sgl = htole32((uint32_t)paddr);
3218 *(ptr_first_sgl + 1) =
3219 htole32((uint32_t)((uint64_t)paddr >> 32));
3220 *(ptr_first_sgl + 2) = htole32(entry_len);
3221 *(ptr_first_sgl + 3) = 0;
3223 /* No longer the first PRP entry. */
3224 first_prp_entry = 0;
3226 /* Put entry in list. */
3227 *ptr_sgl = htole32((uint32_t)paddr);
3229 htole32((uint32_t)((uint64_t)paddr >> 32));
3231 /* Bump ptr_sgl, msg_phys, and num_entries. */
3232 ptr_sgl += sge_dwords;
3233 msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3238 /* Bump the phys address by the entry_len. */
3241 /* Decrement length accounting for last partial page. */
3242 if (entry_len > length)
3245 length -= entry_len;
3249 /* Set chain element Length. */
3250 main_chain_element->Length = htole32(num_entries * prp_size);
3252 /* Return 0, indicating we built a native SGL. */
3257 * Add a chain element as the next SGE for the specified command.
3258 * Reset cm_sge and cm_sgesize to indicate all the available space. Chains are
3259 * only required for IEEE commands. Therefore there is no code for commands
3260 * that have the MPR_CM_FLAGS_SGE_SIMPLE flag set (and those commands
3261 * shouldn't be requesting chains).
3264 mpr_add_chain(struct mpr_command *cm, int segsleft)
3266 struct mpr_softc *sc = cm->cm_sc;
3267 MPI2_REQUEST_HEADER *req;
3268 MPI25_IEEE_SGE_CHAIN64 *ieee_sgc;
3269 struct mpr_chain *chain;
3270 int sgc_size, current_segs, rem_segs, segs_per_frame;
3271 uint8_t next_chain_offset = 0;
3274 * Fail if a command is requesting a chain for SIMPLE SGE's. For SAS3
3275 * only IEEE commands should be requesting chains. Return some error
3276 * code other than 0.
3278 if (cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE) {
3279 mpr_dprint(sc, MPR_ERROR, "A chain element cannot be added to "
3284 sgc_size = sizeof(MPI25_IEEE_SGE_CHAIN64);
3285 if (cm->cm_sglsize < sgc_size)
3286 panic("MPR: Need SGE Error Code\n");
3288 chain = mpr_alloc_chain(cm->cm_sc);
3293 * Note: a double-linked list is used to make it easier to walk for
3296 TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
3299 * Need to know if the number of frames left is more than 1 or not. If
3300 * more than 1 frame is required, NextChainOffset will need to be set,
3301 * which will just be the last segment of the frame.
3304 if (cm->cm_sglsize < (sgc_size * segsleft)) {
3306 * rem_segs is the number of segements remaining after the
3307 * segments that will go into the current frame. Since it is
3308 * known that at least one more frame is required, account for
3309 * the chain element. To know if more than one more frame is
3310 * required, just check if there will be a remainder after using
3311 * the current frame (with this chain) and the next frame. If
3312 * so the NextChainOffset must be the last element of the next
3315 current_segs = (cm->cm_sglsize / sgc_size) - 1;
3316 rem_segs = segsleft - current_segs;
3317 segs_per_frame = sc->chain_frame_size / sgc_size;
3318 if (rem_segs > segs_per_frame) {
3319 next_chain_offset = segs_per_frame - 1;
3322 ieee_sgc = &((MPI25_SGE_IO_UNION *)cm->cm_sge)->IeeeChain;
3323 ieee_sgc->Length = next_chain_offset ?
3324 htole32((uint32_t)sc->chain_frame_size) :
3325 htole32((uint32_t)rem_segs * (uint32_t)sgc_size);
3326 ieee_sgc->NextChainOffset = next_chain_offset;
3327 ieee_sgc->Flags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3328 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3329 ieee_sgc->Address.Low = htole32(chain->chain_busaddr);
3330 ieee_sgc->Address.High = htole32(chain->chain_busaddr >> 32);
3331 cm->cm_sge = &((MPI25_SGE_IO_UNION *)chain->chain)->IeeeSimple;
3332 req = (MPI2_REQUEST_HEADER *)cm->cm_req;
3333 req->ChainOffset = (sc->chain_frame_size - sgc_size) >> 4;
3335 cm->cm_sglsize = sc->chain_frame_size;
3340 * Add one scatter-gather element to the scatter-gather list for a command.
3341 * Maintain cm_sglsize and cm_sge as the remaining size and pointer to the
3342 * next SGE to fill in, respectively. In Gen3, the MPI SGL does not have a
3343 * chain, so don't consider any chain additions.
3346 mpr_push_sge(struct mpr_command *cm, MPI2_SGE_SIMPLE64 *sge, size_t len,
3349 uint32_t saved_buf_len, saved_address_low, saved_address_high;
3353 * case 1: >=1 more segment, no room for anything (error)
3354 * case 2: 1 more segment and enough room for it
3357 if (cm->cm_sglsize < (segsleft * sizeof(MPI2_SGE_SIMPLE64))) {
3358 mpr_dprint(cm->cm_sc, MPR_ERROR,
3359 "%s: warning: Not enough room for MPI SGL in frame.\n",
3364 KASSERT(segsleft == 1,
3365 ("segsleft cannot be more than 1 for an MPI SGL; segsleft = %d\n",
3369 * There is one more segment left to add for the MPI SGL and there is
3370 * enough room in the frame to add it. This is the normal case because
3371 * MPI SGL's don't have chains, otherwise something is wrong.
3373 * If this is a bi-directional request, need to account for that
3374 * here. Save the pre-filled sge values. These will be used
3375 * either for the 2nd SGL or for a single direction SGL. If
3376 * cm_out_len is non-zero, this is a bi-directional request, so
3377 * fill in the OUT SGL first, then the IN SGL, otherwise just
3378 * fill in the IN SGL. Note that at this time, when filling in
3379 * 2 SGL's for a bi-directional request, they both use the same
3380 * DMA buffer (same cm command).
3382 saved_buf_len = sge->FlagsLength & 0x00FFFFFF;
3383 saved_address_low = sge->Address.Low;
3384 saved_address_high = sge->Address.High;
3385 if (cm->cm_out_len) {
3386 sge->FlagsLength = cm->cm_out_len |
3387 ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3388 MPI2_SGE_FLAGS_END_OF_BUFFER |
3389 MPI2_SGE_FLAGS_HOST_TO_IOC |
3390 MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3391 MPI2_SGE_FLAGS_SHIFT);
3392 cm->cm_sglsize -= len;
3393 /* Endian Safe code */
3394 sge_flags = sge->FlagsLength;
3395 sge->FlagsLength = htole32(sge_flags);
3396 sge->Address.High = htole32(sge->Address.High);
3397 sge->Address.Low = htole32(sge->Address.Low);
3398 bcopy(sge, cm->cm_sge, len);
3399 cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3401 sge->FlagsLength = saved_buf_len |
3402 ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3403 MPI2_SGE_FLAGS_END_OF_BUFFER |
3404 MPI2_SGE_FLAGS_LAST_ELEMENT |
3405 MPI2_SGE_FLAGS_END_OF_LIST |
3406 MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3407 MPI2_SGE_FLAGS_SHIFT);
3408 if (cm->cm_flags & MPR_CM_FLAGS_DATAIN) {
3410 ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
3411 MPI2_SGE_FLAGS_SHIFT);
3414 ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
3415 MPI2_SGE_FLAGS_SHIFT);
3417 sge->Address.Low = saved_address_low;
3418 sge->Address.High = saved_address_high;
3420 cm->cm_sglsize -= len;
3421 /* Endian Safe code */
3422 sge_flags = sge->FlagsLength;
3423 sge->FlagsLength = htole32(sge_flags);
3424 sge->Address.High = htole32(sge->Address.High);
3425 sge->Address.Low = htole32(sge->Address.Low);
3426 bcopy(sge, cm->cm_sge, len);
3427 cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3432 * Add one IEEE scatter-gather element (chain or simple) to the IEEE scatter-
3433 * gather list for a command. Maintain cm_sglsize and cm_sge as the
3434 * remaining size and pointer to the next SGE to fill in, respectively.
3437 mpr_push_ieee_sge(struct mpr_command *cm, void *sgep, int segsleft)
3439 MPI2_IEEE_SGE_SIMPLE64 *sge = sgep;
3440 int error, ieee_sge_size = sizeof(MPI25_SGE_IO_UNION);
3441 uint32_t saved_buf_len, saved_address_low, saved_address_high;
3442 uint32_t sge_length;
3445 * case 1: No room for chain or segment (error).
3446 * case 2: Two or more segments left but only room for chain.
3447 * case 3: Last segment and room for it, so set flags.
3451 * There should be room for at least one element, or there is a big
3454 if (cm->cm_sglsize < ieee_sge_size)
3455 panic("MPR: Need SGE Error Code\n");
3457 if ((segsleft >= 2) && (cm->cm_sglsize < (ieee_sge_size * 2))) {
3458 if ((error = mpr_add_chain(cm, segsleft)) != 0)
3462 if (segsleft == 1) {
3464 * If this is a bi-directional request, need to account for that
3465 * here. Save the pre-filled sge values. These will be used
3466 * either for the 2nd SGL or for a single direction SGL. If
3467 * cm_out_len is non-zero, this is a bi-directional request, so
3468 * fill in the OUT SGL first, then the IN SGL, otherwise just
3469 * fill in the IN SGL. Note that at this time, when filling in
3470 * 2 SGL's for a bi-directional request, they both use the same
3471 * DMA buffer (same cm command).
3473 saved_buf_len = sge->Length;
3474 saved_address_low = sge->Address.Low;
3475 saved_address_high = sge->Address.High;
3476 if (cm->cm_out_len) {
3477 sge->Length = cm->cm_out_len;
3478 sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3479 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3480 cm->cm_sglsize -= ieee_sge_size;
3481 /* Endian Safe code */
3482 sge_length = sge->Length;
3483 sge->Length = htole32(sge_length);
3484 sge->Address.High = htole32(sge->Address.High);
3485 sge->Address.Low = htole32(sge->Address.Low);
3486 bcopy(sgep, cm->cm_sge, ieee_sge_size);
3488 (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3491 sge->Length = saved_buf_len;
3492 sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3493 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3494 MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
3495 sge->Address.Low = saved_address_low;
3496 sge->Address.High = saved_address_high;
3499 cm->cm_sglsize -= ieee_sge_size;
3500 /* Endian Safe code */
3501 sge_length = sge->Length;
3502 sge->Length = htole32(sge_length);
3503 sge->Address.High = htole32(sge->Address.High);
3504 sge->Address.Low = htole32(sge->Address.Low);
3505 bcopy(sgep, cm->cm_sge, ieee_sge_size);
3506 cm->cm_sge = (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3512 * Add one dma segment to the scatter-gather list for a command.
3515 mpr_add_dmaseg(struct mpr_command *cm, vm_paddr_t pa, size_t len, u_int flags,
3518 MPI2_SGE_SIMPLE64 sge;
3519 MPI2_IEEE_SGE_SIMPLE64 ieee_sge;
3521 if (!(cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE)) {
3522 ieee_sge.Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3523 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3524 ieee_sge.Length = len;
3525 mpr_from_u64(pa, &ieee_sge.Address);
3527 return (mpr_push_ieee_sge(cm, &ieee_sge, segsleft));
3530 * This driver always uses 64-bit address elements for
3533 flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3534 MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
3535 /* Set Endian safe macro in mpr_push_sge */
3536 sge.FlagsLength = len | (flags << MPI2_SGE_FLAGS_SHIFT);
3537 mpr_from_u64(pa, &sge.Address);
3539 return (mpr_push_sge(cm, &sge, sizeof sge, segsleft));
3544 mpr_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3546 struct mpr_softc *sc;
3547 struct mpr_command *cm;
3548 u_int i, dir, sflags;
3550 cm = (struct mpr_command *)arg;
3554 * In this case, just print out a warning and let the chip tell the
3555 * user they did the wrong thing.
3557 if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
3558 mpr_dprint(sc, MPR_ERROR, "%s: warning: busdma returned %d "
3559 "segments, more than the %d allowed\n", __func__, nsegs,
3564 * Set up DMA direction flags. Bi-directional requests are also handled
3565 * here. In that case, both direction flags will be set.
3568 if (cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) {
3570 * We have to add a special case for SMP passthrough, there
3571 * is no easy way to generically handle it. The first
3572 * S/G element is used for the command (therefore the
3573 * direction bit needs to be set). The second one is used
3574 * for the reply. We'll leave it to the caller to make
3575 * sure we only have two buffers.
3578 * Even though the busdma man page says it doesn't make
3579 * sense to have both direction flags, it does in this case.
3580 * We have one s/g element being accessed in each direction.
3582 dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
3585 * Set the direction flag on the first buffer in the SMP
3586 * passthrough request. We'll clear it for the second one.
3588 sflags |= MPI2_SGE_FLAGS_DIRECTION |
3589 MPI2_SGE_FLAGS_END_OF_BUFFER;
3590 } else if (cm->cm_flags & MPR_CM_FLAGS_DATAOUT) {
3591 sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
3592 dir = BUS_DMASYNC_PREWRITE;
3594 dir = BUS_DMASYNC_PREREAD;
3596 /* Check if a native SG list is needed for an NVMe PCIe device. */
3597 if (cm->cm_targ && cm->cm_targ->is_nvme &&
3598 mpr_check_pcie_native_sgl(sc, cm, segs, nsegs) == 0) {
3599 /* A native SG list was built, skip to end. */
3603 for (i = 0; i < nsegs; i++) {
3604 if ((cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) && (i != 0)) {
3605 sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
3607 error = mpr_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
3610 /* Resource shortage, roll back! */
3611 if (ratecheck(&sc->lastfail, &mpr_chainfail_interval))
3612 mpr_dprint(sc, MPR_INFO, "Out of chain frames, "
3613 "consider increasing hw.mpr.max_chains.\n");
3614 cm->cm_flags |= MPR_CM_FLAGS_CHAIN_FAILED;
3615 mpr_complete_command(sc, cm);
3621 bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
3622 mpr_enqueue_request(sc, cm);
3628 mpr_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
3631 mpr_data_cb(arg, segs, nsegs, error);
3635 * This is the routine to enqueue commands ansynchronously.
3636 * Note that the only error path here is from bus_dmamap_load(), which can
3637 * return EINPROGRESS if it is waiting for resources. Other than this, it's
3638 * assumed that if you have a command in-hand, then you have enough credits
3642 mpr_map_command(struct mpr_softc *sc, struct mpr_command *cm)
3646 if (cm->cm_flags & MPR_CM_FLAGS_USE_UIO) {
3647 error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
3648 &cm->cm_uio, mpr_data_cb2, cm, 0);
3649 } else if (cm->cm_flags & MPR_CM_FLAGS_USE_CCB) {
3650 error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
3651 cm->cm_data, mpr_data_cb, cm, 0);
3652 } else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
3653 error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
3654 cm->cm_data, cm->cm_length, mpr_data_cb, cm, 0);
3656 /* Add a zero-length element as needed */
3657 if (cm->cm_sge != NULL)
3658 mpr_add_dmaseg(cm, 0, 0, 0, 1);
3659 mpr_enqueue_request(sc, cm);
3666 * This is the routine to enqueue commands synchronously. An error of
3667 * EINPROGRESS from mpr_map_command() is ignored since the command will
3668 * be executed and enqueued automatically. Other errors come from msleep().
3671 mpr_wait_command(struct mpr_softc *sc, struct mpr_command **cmp, int timeout,
3675 struct timeval cur_time, start_time;
3676 struct mpr_command *cm = *cmp;
3678 if (sc->mpr_flags & MPR_FLAGS_DIAGRESET)
3681 cm->cm_complete = NULL;
3682 cm->cm_flags |= (MPR_CM_FLAGS_WAKEUP + MPR_CM_FLAGS_POLLED);
3683 error = mpr_map_command(sc, cm);
3684 if ((error != 0) && (error != EINPROGRESS))
3687 // Check for context and wait for 50 mSec at a time until time has
3688 // expired or the command has finished. If msleep can't be used, need
3690 #if __FreeBSD_version >= 1000029
3691 if (curthread->td_no_sleeping)
3692 #else //__FreeBSD_version < 1000029
3693 if (curthread->td_pflags & TDP_NOSLEEPING)
3694 #endif //__FreeBSD_version >= 1000029
3695 sleep_flag = NO_SLEEP;
3696 getmicrouptime(&start_time);
3697 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP) {
3698 error = msleep(cm, &sc->mpr_mtx, 0, "mprwait", timeout*hz);
3699 if (error == EWOULDBLOCK) {
3701 * Record the actual elapsed time in the case of a
3702 * timeout for the message below.
3704 getmicrouptime(&cur_time);
3705 timevalsub(&cur_time, &start_time);
3708 while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3709 mpr_intr_locked(sc);
3710 if (sleep_flag == CAN_SLEEP)
3711 pause("mprwait", hz/20);
3715 getmicrouptime(&cur_time);
3716 timevalsub(&cur_time, &start_time);
3717 if (cur_time.tv_sec > timeout) {
3718 error = EWOULDBLOCK;
3724 if (error == EWOULDBLOCK) {
3725 mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s, timeout=%d,"
3726 " elapsed=%jd\n", __func__, timeout,
3727 (intmax_t)cur_time.tv_sec);
3728 rc = mpr_reinit(sc);
3729 mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3731 if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3733 * Tell the caller that we freed the command in a
3744 * This is the routine to enqueue a command synchonously and poll for
3745 * completion. Its use should be rare.
3748 mpr_request_polled(struct mpr_softc *sc, struct mpr_command **cmp)
3751 struct timeval cur_time, start_time;
3752 struct mpr_command *cm = *cmp;
3756 cm->cm_flags |= MPR_CM_FLAGS_POLLED;
3757 cm->cm_complete = NULL;
3758 mpr_map_command(sc, cm);
3760 getmicrouptime(&start_time);
3761 while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3762 mpr_intr_locked(sc);
3764 if (mtx_owned(&sc->mpr_mtx))
3765 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
3768 pause("mprpoll", hz/20);
3771 * Check for real-time timeout and fail if more than 60 seconds.
3773 getmicrouptime(&cur_time);
3774 timevalsub(&cur_time, &start_time);
3775 if (cur_time.tv_sec > 60) {
3776 mpr_dprint(sc, MPR_FAULT, "polling failed\n");
3783 mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
3784 rc = mpr_reinit(sc);
3785 mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3788 if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3790 * Tell the caller that we freed the command in a
3800 * The MPT driver had a verbose interface for config pages. In this driver,
3801 * reduce it to much simpler terms, similar to the Linux driver.
3804 mpr_read_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3806 MPI2_CONFIG_REQUEST *req;
3807 struct mpr_command *cm;
3810 if (sc->mpr_flags & MPR_FLAGS_BUSY) {
3814 cm = mpr_alloc_command(sc);
3819 req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
3820 req->Function = MPI2_FUNCTION_CONFIG;
3821 req->Action = params->action;
3823 req->ChainOffset = 0;
3824 req->PageAddress = params->page_address;
3825 if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3826 MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
3828 hdr = ¶ms->hdr.Ext;
3829 req->ExtPageType = hdr->ExtPageType;
3830 req->ExtPageLength = hdr->ExtPageLength;
3831 req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
3832 req->Header.PageLength = 0; /* Must be set to zero */
3833 req->Header.PageNumber = hdr->PageNumber;
3834 req->Header.PageVersion = hdr->PageVersion;
3836 MPI2_CONFIG_PAGE_HEADER *hdr;
3838 hdr = ¶ms->hdr.Struct;
3839 req->Header.PageType = hdr->PageType;
3840 req->Header.PageNumber = hdr->PageNumber;
3841 req->Header.PageLength = hdr->PageLength;
3842 req->Header.PageVersion = hdr->PageVersion;
3845 cm->cm_data = params->buffer;
3846 cm->cm_length = params->length;
3847 if (cm->cm_data != NULL) {
3848 cm->cm_sge = &req->PageBufferSGE;
3849 cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
3850 cm->cm_flags = MPR_CM_FLAGS_SGE_SIMPLE | MPR_CM_FLAGS_DATAIN;
3853 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3855 cm->cm_complete_data = params;
3856 if (params->callback != NULL) {
3857 cm->cm_complete = mpr_config_complete;
3858 return (mpr_map_command(sc, cm));
3860 error = mpr_wait_command(sc, &cm, 0, CAN_SLEEP);
3862 mpr_dprint(sc, MPR_FAULT,
3863 "Error %d reading config page\n", error);
3865 mpr_free_command(sc, cm);
3868 mpr_config_complete(sc, cm);
3875 mpr_write_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3881 mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm)
3883 MPI2_CONFIG_REPLY *reply;
3884 struct mpr_config_params *params;
3887 params = cm->cm_complete_data;
3889 if (cm->cm_data != NULL) {
3890 bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
3891 BUS_DMASYNC_POSTREAD);
3892 bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
3896 * XXX KDM need to do more error recovery? This results in the
3897 * device in question not getting probed.
3899 if ((cm->cm_flags & MPR_CM_FLAGS_ERROR_MASK) != 0) {
3900 params->status = MPI2_IOCSTATUS_BUSY;
3904 reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
3905 if (reply == NULL) {
3906 params->status = MPI2_IOCSTATUS_BUSY;
3909 params->status = reply->IOCStatus;
3910 if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3911 params->hdr.Ext.ExtPageType = reply->ExtPageType;
3912 params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
3913 params->hdr.Ext.PageType = reply->Header.PageType;
3914 params->hdr.Ext.PageNumber = reply->Header.PageNumber;
3915 params->hdr.Ext.PageVersion = reply->Header.PageVersion;
3917 params->hdr.Struct.PageType = reply->Header.PageType;
3918 params->hdr.Struct.PageNumber = reply->Header.PageNumber;
3919 params->hdr.Struct.PageLength = reply->Header.PageLength;
3920 params->hdr.Struct.PageVersion = reply->Header.PageVersion;
3924 mpr_free_command(sc, cm);
3925 if (params->callback != NULL)
3926 params->callback(sc, params);