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)
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_replies = MIN(sc->max_replyframes + sc->max_evtframes,
401 sc->facts->MaxReplyDescriptorPostQueueDepth) - 1;
404 * Figure out the number of MSIx-based queues. If the firmware or
405 * user has done something crazy and not allowed enough credit for
406 * the queues to be useful then don't enable multi-queue.
408 if (sc->facts->MaxMSIxVectors < 2)
411 if (sc->msi_msgs > 1) {
412 sc->msi_msgs = MIN(sc->msi_msgs, mp_ncpus);
413 sc->msi_msgs = MIN(sc->msi_msgs, sc->facts->MaxMSIxVectors);
414 if (sc->num_reqs / sc->msi_msgs < 2)
418 mpr_dprint(sc, MPR_INIT, "Sized queues to q=%d reqs=%d replies=%d\n",
419 sc->msi_msgs, sc->num_reqs, sc->num_replies);
423 * This is called during attach and when re-initializing due to a Diag Reset.
424 * IOC Facts is used to allocate many of the structures needed by the driver.
425 * If called from attach, de-allocation is not required because the driver has
426 * not allocated any structures yet, but if called from a Diag Reset, previously
427 * allocated structures based on IOC Facts will need to be freed and re-
428 * allocated bases on the latest IOC Facts.
431 mpr_iocfacts_allocate(struct mpr_softc *sc, uint8_t attaching)
434 Mpi2IOCFactsReply_t saved_facts;
435 uint8_t saved_mode, reallocating;
437 mpr_dprint(sc, MPR_INIT|MPR_TRACE, "%s entered\n", __func__);
439 /* Save old IOC Facts and then only reallocate if Facts have changed */
441 bcopy(sc->facts, &saved_facts, sizeof(MPI2_IOC_FACTS_REPLY));
445 * Get IOC Facts. In all cases throughout this function, panic if doing
446 * a re-initialization and only return the error if attaching so the OS
449 if ((error = mpr_get_iocfacts(sc, sc->facts)) != 0) {
451 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to get "
452 "IOC Facts with error %d, exit\n", error);
455 panic("%s failed to get IOC Facts with error %d\n",
460 MPR_DPRINT_PAGE(sc, MPR_XINFO, iocfacts, sc->facts);
462 snprintf(sc->fw_version, sizeof(sc->fw_version),
463 "%02d.%02d.%02d.%02d",
464 sc->facts->FWVersion.Struct.Major,
465 sc->facts->FWVersion.Struct.Minor,
466 sc->facts->FWVersion.Struct.Unit,
467 sc->facts->FWVersion.Struct.Dev);
469 mpr_dprint(sc, MPR_INFO, "Firmware: %s, Driver: %s\n", sc->fw_version,
471 mpr_dprint(sc, MPR_INFO,
472 "IOCCapabilities: %b\n", sc->facts->IOCCapabilities,
473 "\20" "\3ScsiTaskFull" "\4DiagTrace" "\5SnapBuf" "\6ExtBuf"
474 "\7EEDP" "\10BiDirTarg" "\11Multicast" "\14TransRetry" "\15IR"
475 "\16EventReplay" "\17RaidAccel" "\20MSIXIndex" "\21HostDisc"
476 "\22FastPath" "\23RDPQArray" "\24AtomicReqDesc" "\25PCIeSRIOV");
479 * If the chip doesn't support event replay then a hard reset will be
480 * required to trigger a full discovery. Do the reset here then
481 * retransition to Ready. A hard reset might have already been done,
482 * but it doesn't hurt to do it again. Only do this if attaching, not
485 if (attaching && ((sc->facts->IOCCapabilities &
486 MPI2_IOCFACTS_CAPABILITY_EVENT_REPLAY) == 0)) {
487 mpr_dprint(sc, MPR_INIT, "No event replay, resetting\n");
488 mpr_diag_reset(sc, NO_SLEEP);
489 if ((error = mpr_transition_ready(sc)) != 0) {
490 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
491 "transition to ready with error %d, exit\n",
498 * Set flag if IR Firmware is loaded. If the RAID Capability has
499 * changed from the previous IOC Facts, log a warning, but only if
500 * checking this after a Diag Reset and not during attach.
502 saved_mode = sc->ir_firmware;
503 if (sc->facts->IOCCapabilities &
504 MPI2_IOCFACTS_CAPABILITY_INTEGRATED_RAID)
507 if (sc->ir_firmware != saved_mode) {
508 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "new IR/IT mode "
509 "in IOC Facts does not match previous mode\n");
513 /* Only deallocate and reallocate if relevant IOC Facts have changed */
514 reallocating = FALSE;
515 sc->mpr_flags &= ~MPR_FLAGS_REALLOCATED;
518 ((saved_facts.MsgVersion != sc->facts->MsgVersion) ||
519 (saved_facts.HeaderVersion != sc->facts->HeaderVersion) ||
520 (saved_facts.MaxChainDepth != sc->facts->MaxChainDepth) ||
521 (saved_facts.RequestCredit != sc->facts->RequestCredit) ||
522 (saved_facts.ProductID != sc->facts->ProductID) ||
523 (saved_facts.IOCCapabilities != sc->facts->IOCCapabilities) ||
524 (saved_facts.IOCRequestFrameSize !=
525 sc->facts->IOCRequestFrameSize) ||
526 (saved_facts.IOCMaxChainSegmentSize !=
527 sc->facts->IOCMaxChainSegmentSize) ||
528 (saved_facts.MaxTargets != sc->facts->MaxTargets) ||
529 (saved_facts.MaxSasExpanders != sc->facts->MaxSasExpanders) ||
530 (saved_facts.MaxEnclosures != sc->facts->MaxEnclosures) ||
531 (saved_facts.HighPriorityCredit != sc->facts->HighPriorityCredit) ||
532 (saved_facts.MaxReplyDescriptorPostQueueDepth !=
533 sc->facts->MaxReplyDescriptorPostQueueDepth) ||
534 (saved_facts.ReplyFrameSize != sc->facts->ReplyFrameSize) ||
535 (saved_facts.MaxVolumes != sc->facts->MaxVolumes) ||
536 (saved_facts.MaxPersistentEntries !=
537 sc->facts->MaxPersistentEntries))) {
540 /* Record that we reallocated everything */
541 sc->mpr_flags |= MPR_FLAGS_REALLOCATED;
545 * Some things should be done if attaching or re-allocating after a Diag
546 * Reset, but are not needed after a Diag Reset if the FW has not
549 if (attaching || reallocating) {
551 * Check if controller supports FW diag buffers and set flag to
554 if (sc->facts->IOCCapabilities &
555 MPI2_IOCFACTS_CAPABILITY_DIAG_TRACE_BUFFER)
556 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_TRACE].
558 if (sc->facts->IOCCapabilities &
559 MPI2_IOCFACTS_CAPABILITY_SNAPSHOT_BUFFER)
560 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_SNAPSHOT].
562 if (sc->facts->IOCCapabilities &
563 MPI2_IOCFACTS_CAPABILITY_EXTENDED_BUFFER)
564 sc->fw_diag_buffer_list[MPI2_DIAG_BUF_TYPE_EXTENDED].
568 * Set flags for some supported items.
570 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_EEDP)
571 sc->eedp_enabled = TRUE;
572 if (sc->facts->IOCCapabilities & MPI2_IOCFACTS_CAPABILITY_TLR)
573 sc->control_TLR = TRUE;
574 if (sc->facts->IOCCapabilities &
575 MPI26_IOCFACTS_CAPABILITY_ATOMIC_REQ)
576 sc->atomic_desc_capable = TRUE;
578 mpr_resize_queues(sc);
581 * Initialize all Tail Queues
583 TAILQ_INIT(&sc->req_list);
584 TAILQ_INIT(&sc->high_priority_req_list);
585 TAILQ_INIT(&sc->chain_list);
586 TAILQ_INIT(&sc->prp_page_list);
587 TAILQ_INIT(&sc->tm_list);
591 * If doing a Diag Reset and the FW is significantly different
592 * (reallocating will be set above in IOC Facts comparison), then all
593 * buffers based on the IOC Facts will need to be freed before they are
597 mpr_iocfacts_free(sc);
598 mprsas_realloc_targets(sc, saved_facts.MaxTargets +
599 saved_facts.MaxVolumes);
603 * Any deallocation has been completed. Now start reallocating
604 * if needed. Will only need to reallocate if attaching or if the new
605 * IOC Facts are different from the previous IOC Facts after a Diag
606 * Reset. Targets have already been allocated above if needed.
609 while (attaching || reallocating) {
610 if ((error = mpr_alloc_hw_queues(sc)) != 0)
612 if ((error = mpr_alloc_replies(sc)) != 0)
614 if ((error = mpr_alloc_requests(sc)) != 0)
616 if ((error = mpr_alloc_queues(sc)) != 0)
621 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
622 "Failed to alloc queues with error %d\n", error);
627 /* Always initialize the queues */
628 bzero(sc->free_queue, sc->fqdepth * 4);
632 * Always get the chip out of the reset state, but only panic if not
633 * attaching. If attaching and there is an error, that is handled by
636 error = mpr_transition_operational(sc);
638 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "Failed to "
639 "transition to operational with error %d\n", error);
645 * Finish the queue initialization.
646 * These are set here instead of in mpr_init_queues() because the
647 * IOC resets these values during the state transition in
648 * mpr_transition_operational(). The free index is set to 1
649 * because the corresponding index in the IOC is set to 0, and the
650 * IOC treats the queues as full if both are set to the same value.
651 * Hence the reason that the queue can't hold all of the possible
654 sc->replypostindex = 0;
655 mpr_regwrite(sc, MPI2_REPLY_FREE_HOST_INDEX_OFFSET, sc->replyfreeindex);
656 mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET, 0);
659 * Attach the subsystems so they can prepare their event masks.
660 * XXX Should be dynamic so that IM/IR and user modules can attach
664 mpr_dprint(sc, MPR_INIT, "Attaching subsystems\n");
665 if ((error = mpr_attach_log(sc)) != 0)
667 if ((error = mpr_attach_sas(sc)) != 0)
669 if ((error = mpr_attach_user(sc)) != 0)
674 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
675 "Failed to attach all subsystems: error %d\n", error);
680 if ((error = mpr_pci_setup_interrupts(sc)) != 0) {
681 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
682 "Failed to setup interrupts\n");
691 * This is called if memory is being free (during detach for example) and when
692 * buffers need to be reallocated due to a Diag Reset.
695 mpr_iocfacts_free(struct mpr_softc *sc)
697 struct mpr_command *cm;
700 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
702 if (sc->free_busaddr != 0)
703 bus_dmamap_unload(sc->queues_dmat, sc->queues_map);
704 if (sc->free_queue != NULL)
705 bus_dmamem_free(sc->queues_dmat, sc->free_queue,
707 if (sc->queues_dmat != NULL)
708 bus_dma_tag_destroy(sc->queues_dmat);
710 if (sc->chain_busaddr != 0)
711 bus_dmamap_unload(sc->chain_dmat, sc->chain_map);
712 if (sc->chain_frames != NULL)
713 bus_dmamem_free(sc->chain_dmat, sc->chain_frames,
715 if (sc->chain_dmat != NULL)
716 bus_dma_tag_destroy(sc->chain_dmat);
718 if (sc->sense_busaddr != 0)
719 bus_dmamap_unload(sc->sense_dmat, sc->sense_map);
720 if (sc->sense_frames != NULL)
721 bus_dmamem_free(sc->sense_dmat, sc->sense_frames,
723 if (sc->sense_dmat != NULL)
724 bus_dma_tag_destroy(sc->sense_dmat);
726 if (sc->prp_page_busaddr != 0)
727 bus_dmamap_unload(sc->prp_page_dmat, sc->prp_page_map);
728 if (sc->prp_pages != NULL)
729 bus_dmamem_free(sc->prp_page_dmat, sc->prp_pages,
731 if (sc->prp_page_dmat != NULL)
732 bus_dma_tag_destroy(sc->prp_page_dmat);
734 if (sc->reply_busaddr != 0)
735 bus_dmamap_unload(sc->reply_dmat, sc->reply_map);
736 if (sc->reply_frames != NULL)
737 bus_dmamem_free(sc->reply_dmat, sc->reply_frames,
739 if (sc->reply_dmat != NULL)
740 bus_dma_tag_destroy(sc->reply_dmat);
742 if (sc->req_busaddr != 0)
743 bus_dmamap_unload(sc->req_dmat, sc->req_map);
744 if (sc->req_frames != NULL)
745 bus_dmamem_free(sc->req_dmat, sc->req_frames, sc->req_map);
746 if (sc->req_dmat != NULL)
747 bus_dma_tag_destroy(sc->req_dmat);
749 if (sc->chains != NULL)
750 free(sc->chains, M_MPR);
751 if (sc->prps != NULL)
752 free(sc->prps, M_MPR);
753 if (sc->commands != NULL) {
754 for (i = 1; i < sc->num_reqs; i++) {
755 cm = &sc->commands[i];
756 bus_dmamap_destroy(sc->buffer_dmat, cm->cm_dmamap);
758 free(sc->commands, M_MPR);
760 if (sc->buffer_dmat != NULL)
761 bus_dma_tag_destroy(sc->buffer_dmat);
763 mpr_pci_free_interrupts(sc);
764 free(sc->queues, M_MPR);
769 * The terms diag reset and hard reset are used interchangeably in the MPI
770 * docs to mean resetting the controller chip. In this code diag reset
771 * cleans everything up, and the hard reset function just sends the reset
772 * sequence to the chip. This should probably be refactored so that every
773 * subsystem gets a reset notification of some sort, and can clean up
777 mpr_reinit(struct mpr_softc *sc)
780 struct mprsas_softc *sassc;
786 mtx_assert(&sc->mpr_mtx, MA_OWNED);
788 mpr_dprint(sc, MPR_INIT|MPR_INFO, "Reinitializing controller\n");
789 if (sc->mpr_flags & MPR_FLAGS_DIAGRESET) {
790 mpr_dprint(sc, MPR_INIT, "Reset already in progress\n");
795 * Make sure the completion callbacks can recognize they're getting
796 * a NULL cm_reply due to a reset.
798 sc->mpr_flags |= MPR_FLAGS_DIAGRESET;
801 * Mask interrupts here.
803 mpr_dprint(sc, MPR_INIT, "Masking interrupts and resetting\n");
806 error = mpr_diag_reset(sc, CAN_SLEEP);
808 panic("%s hard reset failed with error %d\n", __func__, error);
811 /* Restore the PCI state, including the MSI-X registers */
814 /* Give the I/O subsystem special priority to get itself prepared */
815 mprsas_handle_reinit(sc);
818 * Get IOC Facts and allocate all structures based on this information.
819 * The attach function will also call mpr_iocfacts_allocate at startup.
820 * If relevant values have changed in IOC Facts, this function will free
821 * all of the memory based on IOC Facts and reallocate that memory.
823 if ((error = mpr_iocfacts_allocate(sc, FALSE)) != 0) {
824 panic("%s IOC Facts based allocation failed with error %d\n",
829 * Mapping structures will be re-allocated after getting IOC Page8, so
830 * free these structures here.
832 mpr_mapping_exit(sc);
835 * The static page function currently read is IOC Page8. Others can be
836 * added in future. It's possible that the values in IOC Page8 have
837 * changed after a Diag Reset due to user modification, so always read
838 * these. Interrupts are masked, so unmask them before getting config
842 sc->mpr_flags &= ~MPR_FLAGS_DIAGRESET;
843 mpr_base_static_config_pages(sc);
846 * Some mapping info is based in IOC Page8 data, so re-initialize the
849 mpr_mapping_initialize(sc);
852 * Restart will reload the event masks clobbered by the reset, and
853 * then enable the port.
855 mpr_reregister_events(sc);
857 /* the end of discovery will release the simq, so we're done. */
858 mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Finished sc %p post %u free %u\n",
859 sc, sc->replypostindex, sc->replyfreeindex);
860 mprsas_release_simq_reinit(sassc);
861 mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
866 /* Wait for the chip to ACK a word that we've put into its FIFO
867 * Wait for <timeout> seconds. In single loop wait for busy loop
868 * for 500 microseconds.
869 * Total is [ 0.5 * (2000 * <timeout>) ] in miliseconds.
872 mpr_wait_db_ack(struct mpr_softc *sc, int timeout, int sleep_flag)
879 cntdn = (sleep_flag == CAN_SLEEP) ? 1000*timeout : 2000*timeout;
881 int_status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
882 if (!(int_status & MPI2_HIS_SYS2IOC_DB_STATUS)) {
883 mpr_dprint(sc, MPR_TRACE, "%s: successful count(%d), "
884 "timeout(%d)\n", __func__, count, timeout);
886 } else if (int_status & MPI2_HIS_IOC2SYS_DB_STATUS) {
887 doorbell = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
888 if ((doorbell & MPI2_IOC_STATE_MASK) ==
889 MPI2_IOC_STATE_FAULT) {
890 mpr_dprint(sc, MPR_FAULT,
891 "fault_state(0x%04x)!\n", doorbell);
894 } else if (int_status == 0xFFFFFFFF)
898 * If it can sleep, sleep for 1 milisecond, else busy loop for
901 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP)
902 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0, "mprdba",
904 else if (sleep_flag == CAN_SLEEP)
905 pause("mprdba", hz/1000);
912 mpr_dprint(sc, MPR_FAULT, "%s: failed due to timeout count(%d), "
913 "int_status(%x)!\n", __func__, count, int_status);
917 /* Wait for the chip to signal that the next word in its FIFO can be fetched */
919 mpr_wait_db_int(struct mpr_softc *sc)
923 for (retry = 0; retry < MPR_DB_MAX_WAIT; retry++) {
924 if ((mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET) &
925 MPI2_HIS_IOC2SYS_DB_STATUS) != 0)
932 /* Step through the synchronous command state machine, i.e. "Doorbell mode" */
934 mpr_request_sync(struct mpr_softc *sc, void *req, MPI2_DEFAULT_REPLY *reply,
935 int req_sz, int reply_sz, int timeout)
939 int i, count, ioc_sz, residual;
940 int sleep_flags = CAN_SLEEP;
942 #if __FreeBSD_version >= 1000029
943 if (curthread->td_no_sleeping)
944 #else //__FreeBSD_version < 1000029
945 if (curthread->td_pflags & TDP_NOSLEEPING)
946 #endif //__FreeBSD_version >= 1000029
947 sleep_flags = NO_SLEEP;
950 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
953 if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
957 * Announce that a message is coming through the doorbell. Messages
958 * are pushed at 32bit words, so round up if needed.
960 count = (req_sz + 3) / 4;
961 mpr_regwrite(sc, MPI2_DOORBELL_OFFSET,
962 (MPI2_FUNCTION_HANDSHAKE << MPI2_DOORBELL_FUNCTION_SHIFT) |
963 (count << MPI2_DOORBELL_ADD_DWORDS_SHIFT));
966 if (mpr_wait_db_int(sc) ||
967 (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED) == 0) {
968 mpr_dprint(sc, MPR_FAULT, "Doorbell failed to activate\n");
971 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
972 if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
973 mpr_dprint(sc, MPR_FAULT, "Doorbell handshake failed\n");
978 /* Clock out the message data synchronously in 32-bit dwords*/
979 data32 = (uint32_t *)req;
980 for (i = 0; i < count; i++) {
981 mpr_regwrite(sc, MPI2_DOORBELL_OFFSET, htole32(data32[i]));
982 if (mpr_wait_db_ack(sc, 5, sleep_flags) != 0) {
983 mpr_dprint(sc, MPR_FAULT,
984 "Timeout while writing doorbell\n");
990 /* Clock in the reply in 16-bit words. The total length of the
991 * message is always in the 4th byte, so clock out the first 2 words
992 * manually, then loop the rest.
994 data16 = (uint16_t *)reply;
995 if (mpr_wait_db_int(sc) != 0) {
996 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 0\n");
1000 mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1001 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1002 if (mpr_wait_db_int(sc) != 0) {
1003 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell 1\n");
1007 mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_DATA_MASK;
1008 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1010 /* Number of 32bit words in the message */
1011 ioc_sz = reply->MsgLength;
1014 * Figure out how many 16bit words to clock in without overrunning.
1015 * The precision loss with dividing reply_sz can safely be
1016 * ignored because the messages can only be multiples of 32bits.
1019 count = MIN((reply_sz / 4), ioc_sz) * 2;
1020 if (count < ioc_sz * 2) {
1021 residual = ioc_sz * 2 - count;
1022 mpr_dprint(sc, MPR_ERROR, "Driver error, throwing away %d "
1023 "residual message words\n", residual);
1026 for (i = 2; i < count; i++) {
1027 if (mpr_wait_db_int(sc) != 0) {
1028 mpr_dprint(sc, MPR_FAULT,
1029 "Timeout reading doorbell %d\n", i);
1032 data16[i] = mpr_regread(sc, MPI2_DOORBELL_OFFSET) &
1033 MPI2_DOORBELL_DATA_MASK;
1034 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1038 * Pull out residual words that won't fit into the provided buffer.
1039 * This keeps the chip from hanging due to a driver programming
1042 while (residual--) {
1043 if (mpr_wait_db_int(sc) != 0) {
1044 mpr_dprint(sc, MPR_FAULT, "Timeout reading doorbell\n");
1047 (void)mpr_regread(sc, MPI2_DOORBELL_OFFSET);
1048 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1052 if (mpr_wait_db_int(sc) != 0) {
1053 mpr_dprint(sc, MPR_FAULT, "Timeout waiting to exit doorbell\n");
1056 if (mpr_regread(sc, MPI2_DOORBELL_OFFSET) & MPI2_DOORBELL_USED)
1057 mpr_dprint(sc, MPR_FAULT, "Warning, doorbell still active\n");
1058 mpr_regwrite(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET, 0x0);
1064 mpr_enqueue_request(struct mpr_softc *sc, struct mpr_command *cm)
1066 request_descriptor rd;
1069 mpr_dprint(sc, MPR_TRACE, "SMID %u cm %p ccb %p\n",
1070 cm->cm_desc.Default.SMID, cm, cm->cm_ccb);
1072 if (sc->mpr_flags & MPR_FLAGS_ATTACH_DONE && !(sc->mpr_flags &
1073 MPR_FLAGS_SHUTDOWN))
1074 mtx_assert(&sc->mpr_mtx, MA_OWNED);
1076 if (++sc->io_cmds_active > sc->io_cmds_highwater)
1077 sc->io_cmds_highwater++;
1079 if (sc->atomic_desc_capable) {
1080 rd.u.low = cm->cm_desc.Words.Low;
1081 mpr_regwrite(sc, MPI26_ATOMIC_REQUEST_DESCRIPTOR_POST_OFFSET,
1084 rd.u.low = cm->cm_desc.Words.Low;
1085 rd.u.high = cm->cm_desc.Words.High;
1086 rd.word = htole64(rd.word);
1087 mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_LOW_OFFSET,
1089 mpr_regwrite(sc, MPI2_REQUEST_DESCRIPTOR_POST_HIGH_OFFSET,
1095 * Just the FACTS, ma'am.
1098 mpr_get_iocfacts(struct mpr_softc *sc, MPI2_IOC_FACTS_REPLY *facts)
1100 MPI2_DEFAULT_REPLY *reply;
1101 MPI2_IOC_FACTS_REQUEST request;
1102 int error, req_sz, reply_sz;
1105 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1107 req_sz = sizeof(MPI2_IOC_FACTS_REQUEST);
1108 reply_sz = sizeof(MPI2_IOC_FACTS_REPLY);
1109 reply = (MPI2_DEFAULT_REPLY *)facts;
1111 bzero(&request, req_sz);
1112 request.Function = MPI2_FUNCTION_IOC_FACTS;
1113 error = mpr_request_sync(sc, &request, reply, req_sz, reply_sz, 5);
1115 mpr_dprint(sc, MPR_INIT, "%s exit, error= %d\n", __func__, error);
1120 mpr_send_iocinit(struct mpr_softc *sc)
1122 MPI2_IOC_INIT_REQUEST init;
1123 MPI2_DEFAULT_REPLY reply;
1124 int req_sz, reply_sz, error;
1126 uint64_t time_in_msec;
1129 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1131 req_sz = sizeof(MPI2_IOC_INIT_REQUEST);
1132 reply_sz = sizeof(MPI2_IOC_INIT_REPLY);
1133 bzero(&init, req_sz);
1134 bzero(&reply, reply_sz);
1137 * Fill in the init block. Note that most addresses are
1138 * deliberately in the lower 32bits of memory. This is a micro-
1139 * optimzation for PCI/PCIX, though it's not clear if it helps PCIe.
1141 init.Function = MPI2_FUNCTION_IOC_INIT;
1142 init.WhoInit = MPI2_WHOINIT_HOST_DRIVER;
1143 init.MsgVersion = htole16(MPI2_VERSION);
1144 init.HeaderVersion = htole16(MPI2_HEADER_VERSION);
1145 init.SystemRequestFrameSize = htole16(sc->facts->IOCRequestFrameSize);
1146 init.ReplyDescriptorPostQueueDepth = htole16(sc->pqdepth);
1147 init.ReplyFreeQueueDepth = htole16(sc->fqdepth);
1148 init.SenseBufferAddressHigh = 0;
1149 init.SystemReplyAddressHigh = 0;
1150 init.SystemRequestFrameBaseAddress.High = 0;
1151 init.SystemRequestFrameBaseAddress.Low =
1152 htole32((uint32_t)sc->req_busaddr);
1153 init.ReplyDescriptorPostQueueAddress.High = 0;
1154 init.ReplyDescriptorPostQueueAddress.Low =
1155 htole32((uint32_t)sc->post_busaddr);
1156 init.ReplyFreeQueueAddress.High = 0;
1157 init.ReplyFreeQueueAddress.Low = htole32((uint32_t)sc->free_busaddr);
1159 time_in_msec = (now.tv_sec * 1000 + now.tv_usec/1000);
1160 init.TimeStamp.High = htole32((time_in_msec >> 32) & 0xFFFFFFFF);
1161 init.TimeStamp.Low = htole32(time_in_msec & 0xFFFFFFFF);
1162 init.HostPageSize = HOST_PAGE_SIZE_4K;
1164 error = mpr_request_sync(sc, &init, &reply, req_sz, reply_sz, 5);
1165 if ((reply.IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
1168 mpr_dprint(sc, MPR_INIT, "IOCInit status= 0x%x\n", reply.IOCStatus);
1169 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
1174 mpr_memaddr_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1179 *addr = segs[0].ds_addr;
1183 mpr_alloc_queues(struct mpr_softc *sc)
1185 struct mpr_queue *q;
1189 mpr_dprint(sc, MPR_INIT|MPR_XINFO, "Allocating %d I/O queues\n", nq);
1191 sc->queues = malloc(sizeof(struct mpr_queue) * nq, M_MPR,
1193 if (sc->queues == NULL)
1196 for (i = 0; i < nq; i++) {
1198 mpr_dprint(sc, MPR_INIT, "Configuring queue %d %p\n", i, q);
1206 mpr_alloc_hw_queues(struct mpr_softc *sc)
1208 bus_addr_t queues_busaddr;
1210 int qsize, fqsize, pqsize;
1213 * The reply free queue contains 4 byte entries in multiples of 16 and
1214 * aligned on a 16 byte boundary. There must always be an unused entry.
1215 * This queue supplies fresh reply frames for the firmware to use.
1217 * The reply descriptor post queue contains 8 byte entries in
1218 * multiples of 16 and aligned on a 16 byte boundary. This queue
1219 * contains filled-in reply frames sent from the firmware to the host.
1221 * These two queues are allocated together for simplicity.
1223 sc->fqdepth = roundup2(sc->num_replies + 1, 16);
1224 sc->pqdepth = roundup2(sc->num_replies + 1, 16);
1225 fqsize= sc->fqdepth * 4;
1226 pqsize = sc->pqdepth * 8;
1227 qsize = fqsize + pqsize;
1229 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1230 16, 0, /* algnmnt, boundary */
1231 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1232 BUS_SPACE_MAXADDR, /* highaddr */
1233 NULL, NULL, /* filter, filterarg */
1234 qsize, /* maxsize */
1236 qsize, /* maxsegsize */
1238 NULL, NULL, /* lockfunc, lockarg */
1239 &sc->queues_dmat)) {
1240 mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues DMA tag\n");
1243 if (bus_dmamem_alloc(sc->queues_dmat, (void **)&queues, BUS_DMA_NOWAIT,
1245 mpr_dprint(sc, MPR_ERROR, "Cannot allocate queues memory\n");
1248 bzero(queues, qsize);
1249 bus_dmamap_load(sc->queues_dmat, sc->queues_map, queues, qsize,
1250 mpr_memaddr_cb, &queues_busaddr, 0);
1252 sc->free_queue = (uint32_t *)queues;
1253 sc->free_busaddr = queues_busaddr;
1254 sc->post_queue = (MPI2_REPLY_DESCRIPTORS_UNION *)(queues + fqsize);
1255 sc->post_busaddr = queues_busaddr + fqsize;
1261 mpr_alloc_replies(struct mpr_softc *sc)
1263 int rsize, num_replies;
1266 * sc->num_replies should be one less than sc->fqdepth. We need to
1267 * allocate space for sc->fqdepth replies, but only sc->num_replies
1268 * replies can be used at once.
1270 num_replies = max(sc->fqdepth, sc->num_replies);
1272 rsize = sc->facts->ReplyFrameSize * num_replies * 4;
1273 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1274 4, 0, /* algnmnt, boundary */
1275 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1276 BUS_SPACE_MAXADDR, /* highaddr */
1277 NULL, NULL, /* filter, filterarg */
1278 rsize, /* maxsize */
1280 rsize, /* maxsegsize */
1282 NULL, NULL, /* lockfunc, lockarg */
1284 mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies DMA tag\n");
1287 if (bus_dmamem_alloc(sc->reply_dmat, (void **)&sc->reply_frames,
1288 BUS_DMA_NOWAIT, &sc->reply_map)) {
1289 mpr_dprint(sc, MPR_ERROR, "Cannot allocate replies memory\n");
1292 bzero(sc->reply_frames, rsize);
1293 bus_dmamap_load(sc->reply_dmat, sc->reply_map, sc->reply_frames, rsize,
1294 mpr_memaddr_cb, &sc->reply_busaddr, 0);
1300 mpr_alloc_requests(struct mpr_softc *sc)
1302 struct mpr_command *cm;
1303 struct mpr_chain *chain;
1304 int i, rsize, nsegs;
1306 rsize = sc->facts->IOCRequestFrameSize * sc->num_reqs * 4;
1307 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1308 16, 0, /* algnmnt, boundary */
1309 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1310 BUS_SPACE_MAXADDR, /* highaddr */
1311 NULL, NULL, /* filter, filterarg */
1312 rsize, /* maxsize */
1314 rsize, /* maxsegsize */
1316 NULL, NULL, /* lockfunc, lockarg */
1318 mpr_dprint(sc, MPR_ERROR, "Cannot allocate request DMA tag\n");
1321 if (bus_dmamem_alloc(sc->req_dmat, (void **)&sc->req_frames,
1322 BUS_DMA_NOWAIT, &sc->req_map)) {
1323 mpr_dprint(sc, MPR_ERROR, "Cannot allocate request memory\n");
1326 bzero(sc->req_frames, rsize);
1327 bus_dmamap_load(sc->req_dmat, sc->req_map, sc->req_frames, rsize,
1328 mpr_memaddr_cb, &sc->req_busaddr, 0);
1331 * Gen3 and beyond uses the IOCMaxChainSegmentSize from IOC Facts to
1332 * get the size of a Chain Frame. Previous versions use the size as a
1333 * Request Frame for the Chain Frame size. If IOCMaxChainSegmentSize
1334 * is 0, use the default value. The IOCMaxChainSegmentSize is the
1335 * number of 16-byte elelements that can fit in a Chain Frame, which is
1336 * the size of an IEEE Simple SGE.
1338 if (sc->facts->MsgVersion >= MPI2_VERSION_02_05) {
1339 sc->chain_seg_size =
1340 htole16(sc->facts->IOCMaxChainSegmentSize);
1341 if (sc->chain_seg_size == 0) {
1342 sc->chain_frame_size = MPR_DEFAULT_CHAIN_SEG_SIZE *
1343 MPR_MAX_CHAIN_ELEMENT_SIZE;
1345 sc->chain_frame_size = sc->chain_seg_size *
1346 MPR_MAX_CHAIN_ELEMENT_SIZE;
1349 sc->chain_frame_size = sc->facts->IOCRequestFrameSize * 4;
1351 rsize = sc->chain_frame_size * sc->max_chains;
1352 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1353 16, 0, /* algnmnt, boundary */
1354 BUS_SPACE_MAXADDR, /* lowaddr */
1355 BUS_SPACE_MAXADDR, /* highaddr */
1356 NULL, NULL, /* filter, filterarg */
1357 rsize, /* maxsize */
1359 rsize, /* maxsegsize */
1361 NULL, NULL, /* lockfunc, lockarg */
1363 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain DMA tag\n");
1366 if (bus_dmamem_alloc(sc->chain_dmat, (void **)&sc->chain_frames,
1367 BUS_DMA_NOWAIT, &sc->chain_map)) {
1368 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1371 bzero(sc->chain_frames, rsize);
1372 bus_dmamap_load(sc->chain_dmat, sc->chain_map, sc->chain_frames, rsize,
1373 mpr_memaddr_cb, &sc->chain_busaddr, 0);
1375 rsize = MPR_SENSE_LEN * sc->num_reqs;
1376 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1377 1, 0, /* algnmnt, boundary */
1378 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1379 BUS_SPACE_MAXADDR, /* highaddr */
1380 NULL, NULL, /* filter, filterarg */
1381 rsize, /* maxsize */
1383 rsize, /* maxsegsize */
1385 NULL, NULL, /* lockfunc, lockarg */
1387 mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense DMA tag\n");
1390 if (bus_dmamem_alloc(sc->sense_dmat, (void **)&sc->sense_frames,
1391 BUS_DMA_NOWAIT, &sc->sense_map)) {
1392 mpr_dprint(sc, MPR_ERROR, "Cannot allocate sense memory\n");
1395 bzero(sc->sense_frames, rsize);
1396 bus_dmamap_load(sc->sense_dmat, sc->sense_map, sc->sense_frames, rsize,
1397 mpr_memaddr_cb, &sc->sense_busaddr, 0);
1399 sc->chains = malloc(sizeof(struct mpr_chain) * sc->max_chains, M_MPR,
1402 mpr_dprint(sc, MPR_ERROR, "Cannot allocate chain memory\n");
1405 for (i = 0; i < sc->max_chains; i++) {
1406 chain = &sc->chains[i];
1407 chain->chain = (MPI2_SGE_IO_UNION *)(sc->chain_frames +
1408 i * sc->chain_frame_size);
1409 chain->chain_busaddr = sc->chain_busaddr +
1410 i * sc->chain_frame_size;
1411 mpr_free_chain(sc, chain);
1412 sc->chain_free_lowwater++;
1416 * Allocate NVMe PRP Pages for NVMe SGL support only if the FW supports
1419 if ((sc->facts->MsgVersion >= MPI2_VERSION_02_06) &&
1420 (sc->facts->ProtocolFlags & MPI2_IOCFACTS_PROTOCOL_NVME_DEVICES)) {
1421 if (mpr_alloc_nvme_prp_pages(sc) == ENOMEM)
1425 /* XXX Need to pick a more precise value */
1426 nsegs = (MAXPHYS / PAGE_SIZE) + 1;
1427 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1428 1, 0, /* algnmnt, boundary */
1429 BUS_SPACE_MAXADDR, /* lowaddr */
1430 BUS_SPACE_MAXADDR, /* highaddr */
1431 NULL, NULL, /* filter, filterarg */
1432 BUS_SPACE_MAXSIZE_32BIT,/* maxsize */
1433 nsegs, /* nsegments */
1434 BUS_SPACE_MAXSIZE_32BIT,/* maxsegsize */
1435 BUS_DMA_ALLOCNOW, /* flags */
1436 busdma_lock_mutex, /* lockfunc */
1437 &sc->mpr_mtx, /* lockarg */
1438 &sc->buffer_dmat)) {
1439 mpr_dprint(sc, MPR_ERROR, "Cannot allocate buffer DMA tag\n");
1444 * SMID 0 cannot be used as a free command per the firmware spec.
1445 * Just drop that command instead of risking accounting bugs.
1447 sc->commands = malloc(sizeof(struct mpr_command) * sc->num_reqs,
1448 M_MPR, M_WAITOK | M_ZERO);
1449 if (!sc->commands) {
1450 mpr_dprint(sc, MPR_ERROR, "Cannot allocate command memory\n");
1453 for (i = 1; i < sc->num_reqs; i++) {
1454 cm = &sc->commands[i];
1455 cm->cm_req = sc->req_frames +
1456 i * sc->facts->IOCRequestFrameSize * 4;
1457 cm->cm_req_busaddr = sc->req_busaddr +
1458 i * sc->facts->IOCRequestFrameSize * 4;
1459 cm->cm_sense = &sc->sense_frames[i];
1460 cm->cm_sense_busaddr = sc->sense_busaddr + i * MPR_SENSE_LEN;
1461 cm->cm_desc.Default.SMID = i;
1463 TAILQ_INIT(&cm->cm_chain_list);
1464 TAILQ_INIT(&cm->cm_prp_page_list);
1465 callout_init_mtx(&cm->cm_callout, &sc->mpr_mtx, 0);
1467 /* XXX Is a failure here a critical problem? */
1468 if (bus_dmamap_create(sc->buffer_dmat, 0, &cm->cm_dmamap)
1470 if (i <= sc->facts->HighPriorityCredit)
1471 mpr_free_high_priority_command(sc, cm);
1473 mpr_free_command(sc, cm);
1475 panic("failed to allocate command %d\n", i);
1485 * Allocate contiguous buffers for PCIe NVMe devices for building native PRPs,
1486 * which are scatter/gather lists for NVMe devices.
1488 * This buffer must be contiguous due to the nature of how NVMe PRPs are built
1489 * and translated by FW.
1491 * returns ENOMEM if memory could not be allocated, otherwise returns 0.
1494 mpr_alloc_nvme_prp_pages(struct mpr_softc *sc)
1496 int PRPs_per_page, PRPs_required, pages_required;
1498 struct mpr_prp_page *prp_page;
1501 * Assuming a MAX_IO_SIZE of 1MB and a PAGE_SIZE of 4k, the max number
1502 * of PRPs (NVMe's Scatter/Gather Element) needed per I/O is:
1503 * MAX_IO_SIZE / PAGE_SIZE = 256
1505 * 1 PRP entry in main frame for PRP list pointer still leaves 255 PRPs
1506 * required for the remainder of the 1MB I/O. 512 PRPs can fit into one
1507 * page (4096 / 8 = 512), so only one page is required for each I/O.
1509 * Each of these buffers will need to be contiguous. For simplicity,
1510 * only one buffer is allocated here, which has all of the space
1511 * required for the NVMe Queue Depth. If there are problems allocating
1512 * this one buffer, this function will need to change to allocate
1513 * individual, contiguous NVME_QDEPTH buffers.
1515 * The real calculation will use the real max io size. Above is just an
1519 PRPs_required = sc->maxio / PAGE_SIZE;
1520 PRPs_per_page = (PAGE_SIZE / PRP_ENTRY_SIZE) - 1;
1521 pages_required = (PRPs_required / PRPs_per_page) + 1;
1523 sc->prp_buffer_size = PAGE_SIZE * pages_required;
1524 rsize = sc->prp_buffer_size * NVME_QDEPTH;
1525 if (bus_dma_tag_create( sc->mpr_parent_dmat, /* parent */
1526 4, 0, /* algnmnt, boundary */
1527 BUS_SPACE_MAXADDR_32BIT,/* lowaddr */
1528 BUS_SPACE_MAXADDR, /* highaddr */
1529 NULL, NULL, /* filter, filterarg */
1530 rsize, /* maxsize */
1532 rsize, /* maxsegsize */
1534 NULL, NULL, /* lockfunc, lockarg */
1535 &sc->prp_page_dmat)) {
1536 mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP DMA "
1540 if (bus_dmamem_alloc(sc->prp_page_dmat, (void **)&sc->prp_pages,
1541 BUS_DMA_NOWAIT, &sc->prp_page_map)) {
1542 mpr_dprint(sc, MPR_ERROR, "Cannot allocate NVMe PRP memory\n");
1545 bzero(sc->prp_pages, rsize);
1546 bus_dmamap_load(sc->prp_page_dmat, sc->prp_page_map, sc->prp_pages,
1547 rsize, mpr_memaddr_cb, &sc->prp_page_busaddr, 0);
1549 sc->prps = malloc(sizeof(struct mpr_prp_page) * NVME_QDEPTH, M_MPR,
1551 for (i = 0; i < NVME_QDEPTH; i++) {
1552 prp_page = &sc->prps[i];
1553 prp_page->prp_page = (uint64_t *)(sc->prp_pages +
1554 i * sc->prp_buffer_size);
1555 prp_page->prp_page_busaddr = (uint64_t)(sc->prp_page_busaddr +
1556 i * sc->prp_buffer_size);
1557 mpr_free_prp_page(sc, prp_page);
1558 sc->prp_pages_free_lowwater++;
1565 mpr_init_queues(struct mpr_softc *sc)
1569 memset((uint8_t *)sc->post_queue, 0xff, sc->pqdepth * 8);
1572 * According to the spec, we need to use one less reply than we
1573 * have space for on the queue. So sc->num_replies (the number we
1574 * use) should be less than sc->fqdepth (allocated size).
1576 if (sc->num_replies >= sc->fqdepth)
1580 * Initialize all of the free queue entries.
1582 for (i = 0; i < sc->fqdepth; i++) {
1583 sc->free_queue[i] = sc->reply_busaddr +
1584 (i * sc->facts->ReplyFrameSize * 4);
1586 sc->replyfreeindex = sc->num_replies;
1591 /* Get the driver parameter tunables. Lowest priority are the driver defaults.
1592 * Next are the global settings, if they exist. Highest are the per-unit
1593 * settings, if they exist.
1596 mpr_get_tunables(struct mpr_softc *sc)
1598 char tmpstr[80], mpr_debug[80];
1600 /* XXX default to some debugging for now */
1601 sc->mpr_debug = MPR_INFO | MPR_FAULT;
1602 sc->disable_msix = 0;
1603 sc->disable_msi = 0;
1604 sc->max_msix = MPR_MSIX_MAX;
1605 sc->max_chains = MPR_CHAIN_FRAMES;
1606 sc->max_io_pages = MPR_MAXIO_PAGES;
1607 sc->enable_ssu = MPR_SSU_ENABLE_SSD_DISABLE_HDD;
1608 sc->spinup_wait_time = DEFAULT_SPINUP_WAIT;
1610 sc->max_reqframes = MPR_REQ_FRAMES;
1611 sc->max_prireqframes = MPR_PRI_REQ_FRAMES;
1612 sc->max_replyframes = MPR_REPLY_FRAMES;
1613 sc->max_evtframes = MPR_EVT_REPLY_FRAMES;
1616 * Grab the global variables.
1618 bzero(mpr_debug, 80);
1619 if (TUNABLE_STR_FETCH("hw.mpr.debug_level", mpr_debug, 80) != 0)
1620 mpr_parse_debug(sc, mpr_debug);
1621 TUNABLE_INT_FETCH("hw.mpr.disable_msix", &sc->disable_msix);
1622 TUNABLE_INT_FETCH("hw.mpr.disable_msi", &sc->disable_msi);
1623 TUNABLE_INT_FETCH("hw.mpr.max_msix", &sc->max_msix);
1624 TUNABLE_INT_FETCH("hw.mpr.max_chains", &sc->max_chains);
1625 TUNABLE_INT_FETCH("hw.mpr.max_io_pages", &sc->max_io_pages);
1626 TUNABLE_INT_FETCH("hw.mpr.enable_ssu", &sc->enable_ssu);
1627 TUNABLE_INT_FETCH("hw.mpr.spinup_wait_time", &sc->spinup_wait_time);
1628 TUNABLE_INT_FETCH("hw.mpr.use_phy_num", &sc->use_phynum);
1629 TUNABLE_INT_FETCH("hw.mpr.max_reqframes", &sc->max_reqframes);
1630 TUNABLE_INT_FETCH("hw.mpr.max_prireqframes", &sc->max_prireqframes);
1631 TUNABLE_INT_FETCH("hw.mpr.max_replyframes", &sc->max_replyframes);
1632 TUNABLE_INT_FETCH("hw.mpr.max_evtframes", &sc->max_evtframes);
1634 /* Grab the unit-instance variables */
1635 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.debug_level",
1636 device_get_unit(sc->mpr_dev));
1637 bzero(mpr_debug, 80);
1638 if (TUNABLE_STR_FETCH(tmpstr, mpr_debug, 80) != 0)
1639 mpr_parse_debug(sc, mpr_debug);
1641 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msix",
1642 device_get_unit(sc->mpr_dev));
1643 TUNABLE_INT_FETCH(tmpstr, &sc->disable_msix);
1645 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.disable_msi",
1646 device_get_unit(sc->mpr_dev));
1647 TUNABLE_INT_FETCH(tmpstr, &sc->disable_msi);
1649 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_msix",
1650 device_get_unit(sc->mpr_dev));
1651 TUNABLE_INT_FETCH(tmpstr, &sc->max_msix);
1653 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_chains",
1654 device_get_unit(sc->mpr_dev));
1655 TUNABLE_INT_FETCH(tmpstr, &sc->max_chains);
1657 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_io_pages",
1658 device_get_unit(sc->mpr_dev));
1659 TUNABLE_INT_FETCH(tmpstr, &sc->max_io_pages);
1661 bzero(sc->exclude_ids, sizeof(sc->exclude_ids));
1662 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.exclude_ids",
1663 device_get_unit(sc->mpr_dev));
1664 TUNABLE_STR_FETCH(tmpstr, sc->exclude_ids, sizeof(sc->exclude_ids));
1666 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.enable_ssu",
1667 device_get_unit(sc->mpr_dev));
1668 TUNABLE_INT_FETCH(tmpstr, &sc->enable_ssu);
1670 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.spinup_wait_time",
1671 device_get_unit(sc->mpr_dev));
1672 TUNABLE_INT_FETCH(tmpstr, &sc->spinup_wait_time);
1674 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.use_phy_num",
1675 device_get_unit(sc->mpr_dev));
1676 TUNABLE_INT_FETCH(tmpstr, &sc->use_phynum);
1678 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_reqframes",
1679 device_get_unit(sc->mpr_dev));
1680 TUNABLE_INT_FETCH(tmpstr, &sc->max_reqframes);
1682 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_prireqframes",
1683 device_get_unit(sc->mpr_dev));
1684 TUNABLE_INT_FETCH(tmpstr, &sc->max_prireqframes);
1686 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_replyframes",
1687 device_get_unit(sc->mpr_dev));
1688 TUNABLE_INT_FETCH(tmpstr, &sc->max_replyframes);
1690 snprintf(tmpstr, sizeof(tmpstr), "dev.mpr.%d.max_evtframes",
1691 device_get_unit(sc->mpr_dev));
1692 TUNABLE_INT_FETCH(tmpstr, &sc->max_evtframes);
1696 mpr_setup_sysctl(struct mpr_softc *sc)
1698 struct sysctl_ctx_list *sysctl_ctx = NULL;
1699 struct sysctl_oid *sysctl_tree = NULL;
1700 char tmpstr[80], tmpstr2[80];
1703 * Setup the sysctl variable so the user can change the debug level
1706 snprintf(tmpstr, sizeof(tmpstr), "MPR controller %d",
1707 device_get_unit(sc->mpr_dev));
1708 snprintf(tmpstr2, sizeof(tmpstr2), "%d", device_get_unit(sc->mpr_dev));
1710 sysctl_ctx = device_get_sysctl_ctx(sc->mpr_dev);
1711 if (sysctl_ctx != NULL)
1712 sysctl_tree = device_get_sysctl_tree(sc->mpr_dev);
1714 if (sysctl_tree == NULL) {
1715 sysctl_ctx_init(&sc->sysctl_ctx);
1716 sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
1717 SYSCTL_STATIC_CHILDREN(_hw_mpr), OID_AUTO, tmpstr2,
1718 CTLFLAG_RD, 0, tmpstr);
1719 if (sc->sysctl_tree == NULL)
1721 sysctl_ctx = &sc->sysctl_ctx;
1722 sysctl_tree = sc->sysctl_tree;
1725 SYSCTL_ADD_PROC(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1726 OID_AUTO, "debug_level", CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE,
1727 sc, 0, mpr_debug_sysctl, "A", "mpr debug level");
1729 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1730 OID_AUTO, "disable_msix", CTLFLAG_RD, &sc->disable_msix, 0,
1731 "Disable the use of MSI-X interrupts");
1733 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1734 OID_AUTO, "max_msix", CTLFLAG_RD, &sc->max_msix, 0,
1735 "User-defined maximum number of MSIX queues");
1737 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1738 OID_AUTO, "msix_msgs", CTLFLAG_RD, &sc->msi_msgs, 0,
1739 "Negotiated number of MSIX queues");
1741 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1742 OID_AUTO, "max_reqframes", CTLFLAG_RD, &sc->max_reqframes, 0,
1743 "Total number of allocated request frames");
1745 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1746 OID_AUTO, "max_prireqframes", CTLFLAG_RD, &sc->max_prireqframes, 0,
1747 "Total number of allocated high priority request frames");
1749 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1750 OID_AUTO, "max_replyframes", CTLFLAG_RD, &sc->max_replyframes, 0,
1751 "Total number of allocated reply frames");
1753 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1754 OID_AUTO, "max_evtframes", CTLFLAG_RD, &sc->max_evtframes, 0,
1755 "Total number of event frames allocated");
1757 SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1758 OID_AUTO, "firmware_version", CTLFLAG_RW, sc->fw_version,
1759 strlen(sc->fw_version), "firmware version");
1761 SYSCTL_ADD_STRING(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1762 OID_AUTO, "driver_version", CTLFLAG_RW, MPR_DRIVER_VERSION,
1763 strlen(MPR_DRIVER_VERSION), "driver version");
1765 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1766 OID_AUTO, "io_cmds_active", CTLFLAG_RD,
1767 &sc->io_cmds_active, 0, "number of currently active commands");
1769 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1770 OID_AUTO, "io_cmds_highwater", CTLFLAG_RD,
1771 &sc->io_cmds_highwater, 0, "maximum active commands seen");
1773 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1774 OID_AUTO, "chain_free", CTLFLAG_RD,
1775 &sc->chain_free, 0, "number of free chain elements");
1777 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1778 OID_AUTO, "chain_free_lowwater", CTLFLAG_RD,
1779 &sc->chain_free_lowwater, 0,"lowest number of free chain elements");
1781 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1782 OID_AUTO, "max_chains", CTLFLAG_RD,
1783 &sc->max_chains, 0,"maximum chain frames that will be allocated");
1785 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1786 OID_AUTO, "max_io_pages", CTLFLAG_RD,
1787 &sc->max_io_pages, 0,"maximum pages to allow per I/O (if <1 use "
1790 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1791 OID_AUTO, "enable_ssu", CTLFLAG_RW, &sc->enable_ssu, 0,
1792 "enable SSU to SATA SSD/HDD at shutdown");
1794 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1795 OID_AUTO, "chain_alloc_fail", CTLFLAG_RD,
1796 &sc->chain_alloc_fail, "chain allocation failures");
1798 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1799 OID_AUTO, "spinup_wait_time", CTLFLAG_RD,
1800 &sc->spinup_wait_time, DEFAULT_SPINUP_WAIT, "seconds to wait for "
1801 "spinup after SATA ID error");
1803 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1804 OID_AUTO, "use_phy_num", CTLFLAG_RD, &sc->use_phynum, 0,
1805 "Use the phy number for enumeration");
1807 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1808 OID_AUTO, "prp_pages_free", CTLFLAG_RD,
1809 &sc->prp_pages_free, 0, "number of free PRP pages");
1811 SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1812 OID_AUTO, "prp_pages_free_lowwater", CTLFLAG_RD,
1813 &sc->prp_pages_free_lowwater, 0,"lowest number of free PRP pages");
1815 SYSCTL_ADD_UQUAD(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1816 OID_AUTO, "prp_page_alloc_fail", CTLFLAG_RD,
1817 &sc->prp_page_alloc_fail, "PRP page allocation failures");
1820 static struct mpr_debug_string {
1823 } mpr_debug_strings[] = {
1825 {"fault", MPR_FAULT},
1826 {"event", MPR_EVENT},
1828 {"recovery", MPR_RECOVERY},
1829 {"error", MPR_ERROR},
1831 {"xinfo", MPR_XINFO},
1833 {"mapping", MPR_MAPPING},
1834 {"trace", MPR_TRACE}
1837 enum mpr_debug_level_combiner {
1844 mpr_debug_sysctl(SYSCTL_HANDLER_ARGS)
1846 struct mpr_softc *sc;
1847 struct mpr_debug_string *string;
1851 int i, len, debug, error;
1853 sc = (struct mpr_softc *)arg1;
1855 error = sysctl_wire_old_buffer(req, 0);
1859 sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
1860 debug = sc->mpr_debug;
1862 sbuf_printf(sbuf, "%#x", debug);
1864 sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
1865 for (i = 0; i < sz; i++) {
1866 string = &mpr_debug_strings[i];
1867 if (debug & string->flag)
1868 sbuf_printf(sbuf, ",%s", string->name);
1871 error = sbuf_finish(sbuf);
1874 if (error || req->newptr == NULL)
1877 len = req->newlen - req->newidx;
1881 buffer = malloc(len, M_MPR, M_ZERO|M_WAITOK);
1882 error = SYSCTL_IN(req, buffer, len);
1884 mpr_parse_debug(sc, buffer);
1886 free(buffer, M_MPR);
1891 mpr_parse_debug(struct mpr_softc *sc, char *list)
1893 struct mpr_debug_string *string;
1894 enum mpr_debug_level_combiner op;
1895 char *token, *endtoken;
1899 if (list == NULL || *list == '\0')
1905 } else if (*list == '-') {
1914 sz = sizeof(mpr_debug_strings) / sizeof(mpr_debug_strings[0]);
1915 while ((token = strsep(&list, ":,")) != NULL) {
1917 /* Handle integer flags */
1918 flags |= strtol(token, &endtoken, 0);
1919 if (token != endtoken)
1922 /* Handle text flags */
1923 for (i = 0; i < sz; i++) {
1924 string = &mpr_debug_strings[i];
1925 if (strcasecmp(token, string->name) == 0) {
1926 flags |= string->flag;
1934 sc->mpr_debug = flags;
1937 sc->mpr_debug |= flags;
1940 sc->mpr_debug &= (~flags);
1947 mpr_attach(struct mpr_softc *sc)
1952 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
1954 mtx_init(&sc->mpr_mtx, "MPR lock", NULL, MTX_DEF);
1955 callout_init_mtx(&sc->periodic, &sc->mpr_mtx, 0);
1956 callout_init_mtx(&sc->device_check_callout, &sc->mpr_mtx, 0);
1957 TAILQ_INIT(&sc->event_list);
1958 timevalclear(&sc->lastfail);
1960 if ((error = mpr_transition_ready(sc)) != 0) {
1961 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
1962 "Failed to transition ready\n");
1966 sc->facts = malloc(sizeof(MPI2_IOC_FACTS_REPLY), M_MPR,
1969 mpr_dprint(sc, MPR_INIT|MPR_FAULT,
1970 "Cannot allocate memory, exit\n");
1975 * Get IOC Facts and allocate all structures based on this information.
1976 * A Diag Reset will also call mpr_iocfacts_allocate and re-read the IOC
1977 * Facts. If relevant values have changed in IOC Facts, this function
1978 * will free all of the memory based on IOC Facts and reallocate that
1979 * memory. If this fails, any allocated memory should already be freed.
1981 if ((error = mpr_iocfacts_allocate(sc, TRUE)) != 0) {
1982 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "IOC Facts allocation "
1983 "failed with error %d\n", error);
1987 /* Start the periodic watchdog check on the IOC Doorbell */
1991 * The portenable will kick off discovery events that will drive the
1992 * rest of the initialization process. The CAM/SAS module will
1993 * hold up the boot sequence until discovery is complete.
1995 sc->mpr_ich.ich_func = mpr_startup;
1996 sc->mpr_ich.ich_arg = sc;
1997 if (config_intrhook_establish(&sc->mpr_ich) != 0) {
1998 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
1999 "Cannot establish MPR config hook\n");
2004 * Allow IR to shutdown gracefully when shutdown occurs.
2006 sc->shutdown_eh = EVENTHANDLER_REGISTER(shutdown_final,
2007 mprsas_ir_shutdown, sc, SHUTDOWN_PRI_DEFAULT);
2009 if (sc->shutdown_eh == NULL)
2010 mpr_dprint(sc, MPR_INIT|MPR_ERROR,
2011 "shutdown event registration failed\n");
2013 mpr_setup_sysctl(sc);
2015 sc->mpr_flags |= MPR_FLAGS_ATTACH_DONE;
2016 mpr_dprint(sc, MPR_INIT, "%s exit error= %d\n", __func__, error);
2021 /* Run through any late-start handlers. */
2023 mpr_startup(void *arg)
2025 struct mpr_softc *sc;
2027 sc = (struct mpr_softc *)arg;
2028 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2031 mpr_unmask_intr(sc);
2033 /* initialize device mapping tables */
2034 mpr_base_static_config_pages(sc);
2035 mpr_mapping_initialize(sc);
2039 mpr_dprint(sc, MPR_INIT, "disestablish config intrhook\n");
2040 config_intrhook_disestablish(&sc->mpr_ich);
2041 sc->mpr_ich.ich_arg = NULL;
2043 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2046 /* Periodic watchdog. Is called with the driver lock already held. */
2048 mpr_periodic(void *arg)
2050 struct mpr_softc *sc;
2053 sc = (struct mpr_softc *)arg;
2054 if (sc->mpr_flags & MPR_FLAGS_SHUTDOWN)
2057 db = mpr_regread(sc, MPI2_DOORBELL_OFFSET);
2058 if ((db & MPI2_IOC_STATE_MASK) == MPI2_IOC_STATE_FAULT) {
2059 if ((db & MPI2_DOORBELL_FAULT_CODE_MASK) ==
2060 IFAULT_IOP_OVER_TEMP_THRESHOLD_EXCEEDED) {
2061 panic("TEMPERATURE FAULT: STOPPING.");
2063 mpr_dprint(sc, MPR_FAULT, "IOC Fault 0x%08x, Resetting\n", db);
2067 callout_reset(&sc->periodic, MPR_PERIODIC_DELAY * hz, mpr_periodic, sc);
2071 mpr_log_evt_handler(struct mpr_softc *sc, uintptr_t data,
2072 MPI2_EVENT_NOTIFICATION_REPLY *event)
2074 MPI2_EVENT_DATA_LOG_ENTRY_ADDED *entry;
2076 MPR_DPRINT_EVENT(sc, generic, event);
2078 switch (event->Event) {
2079 case MPI2_EVENT_LOG_DATA:
2080 mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_DATA:\n");
2081 if (sc->mpr_debug & MPR_EVENT)
2082 hexdump(event->EventData, event->EventDataLength, NULL,
2085 case MPI2_EVENT_LOG_ENTRY_ADDED:
2086 entry = (MPI2_EVENT_DATA_LOG_ENTRY_ADDED *)event->EventData;
2087 mpr_dprint(sc, MPR_EVENT, "MPI2_EVENT_LOG_ENTRY_ADDED event "
2088 "0x%x Sequence %d:\n", entry->LogEntryQualifier,
2089 entry->LogSequence);
2098 mpr_attach_log(struct mpr_softc *sc)
2103 setbit(events, MPI2_EVENT_LOG_DATA);
2104 setbit(events, MPI2_EVENT_LOG_ENTRY_ADDED);
2106 mpr_register_events(sc, events, mpr_log_evt_handler, NULL,
2113 mpr_detach_log(struct mpr_softc *sc)
2116 if (sc->mpr_log_eh != NULL)
2117 mpr_deregister_events(sc, sc->mpr_log_eh);
2122 * Free all of the driver resources and detach submodules. Should be called
2123 * without the lock held.
2126 mpr_free(struct mpr_softc *sc)
2130 mpr_dprint(sc, MPR_INIT, "%s entered\n", __func__);
2131 /* Turn off the watchdog */
2133 sc->mpr_flags |= MPR_FLAGS_SHUTDOWN;
2135 /* Lock must not be held for this */
2136 callout_drain(&sc->periodic);
2137 callout_drain(&sc->device_check_callout);
2139 if (((error = mpr_detach_log(sc)) != 0) ||
2140 ((error = mpr_detach_sas(sc)) != 0)) {
2141 mpr_dprint(sc, MPR_INIT|MPR_FAULT, "failed to detach "
2142 "subsystems, error= %d, exit\n", error);
2146 mpr_detach_user(sc);
2148 /* Put the IOC back in the READY state. */
2150 if ((error = mpr_transition_ready(sc)) != 0) {
2156 if (sc->facts != NULL)
2157 free(sc->facts, M_MPR);
2160 * Free all buffers that are based on IOC Facts. A Diag Reset may need
2161 * to free these buffers too.
2163 mpr_iocfacts_free(sc);
2165 if (sc->sysctl_tree != NULL)
2166 sysctl_ctx_free(&sc->sysctl_ctx);
2168 /* Deregister the shutdown function */
2169 if (sc->shutdown_eh != NULL)
2170 EVENTHANDLER_DEREGISTER(shutdown_final, sc->shutdown_eh);
2172 mtx_destroy(&sc->mpr_mtx);
2173 mpr_dprint(sc, MPR_INIT, "%s exit\n", __func__);
2178 static __inline void
2179 mpr_complete_command(struct mpr_softc *sc, struct mpr_command *cm)
2184 mpr_dprint(sc, MPR_ERROR, "Completing NULL command\n");
2188 if (cm->cm_flags & MPR_CM_FLAGS_POLLED)
2189 cm->cm_flags |= MPR_CM_FLAGS_COMPLETE;
2191 if (cm->cm_complete != NULL) {
2192 mpr_dprint(sc, MPR_TRACE,
2193 "%s cm %p calling cm_complete %p data %p reply %p\n",
2194 __func__, cm, cm->cm_complete, cm->cm_complete_data,
2196 cm->cm_complete(sc, cm);
2199 if (cm->cm_flags & MPR_CM_FLAGS_WAKEUP) {
2200 mpr_dprint(sc, MPR_TRACE, "waking up %p\n", cm);
2204 if (sc->io_cmds_active != 0) {
2205 sc->io_cmds_active--;
2207 mpr_dprint(sc, MPR_ERROR, "Warning: io_cmds_active is "
2208 "out of sync - resynching to 0\n");
2213 mpr_sas_log_info(struct mpr_softc *sc , u32 log_info)
2215 union loginfo_type {
2224 union loginfo_type sas_loginfo;
2225 char *originator_str = NULL;
2227 sas_loginfo.loginfo = log_info;
2228 if (sas_loginfo.dw.bus_type != 3 /*SAS*/)
2231 /* each nexus loss loginfo */
2232 if (log_info == 0x31170000)
2235 /* eat the loginfos associated with task aborts */
2236 if ((log_info == 30050000) || (log_info == 0x31140000) ||
2237 (log_info == 0x31130000))
2240 switch (sas_loginfo.dw.originator) {
2242 originator_str = "IOP";
2245 originator_str = "PL";
2248 originator_str = "IR";
2252 mpr_dprint(sc, MPR_LOG, "log_info(0x%08x): originator(%s), "
2253 "code(0x%02x), sub_code(0x%04x)\n", log_info, originator_str,
2254 sas_loginfo.dw.code, sas_loginfo.dw.subcode);
2258 mpr_display_reply_info(struct mpr_softc *sc, uint8_t *reply)
2260 MPI2DefaultReply_t *mpi_reply;
2263 mpi_reply = (MPI2DefaultReply_t*)reply;
2264 sc_status = le16toh(mpi_reply->IOCStatus);
2265 if (sc_status & MPI2_IOCSTATUS_FLAG_LOG_INFO_AVAILABLE)
2266 mpr_sas_log_info(sc, le32toh(mpi_reply->IOCLogInfo));
2270 mpr_intr(void *data)
2272 struct mpr_softc *sc;
2275 sc = (struct mpr_softc *)data;
2276 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2279 * Check interrupt status register to flush the bus. This is
2280 * needed for both INTx interrupts and driver-driven polling
2282 status = mpr_regread(sc, MPI2_HOST_INTERRUPT_STATUS_OFFSET);
2283 if ((status & MPI2_HIS_REPLY_DESCRIPTOR_INTERRUPT) == 0)
2287 mpr_intr_locked(data);
2293 * In theory, MSI/MSIX interrupts shouldn't need to read any registers on the
2294 * chip. Hopefully this theory is correct.
2297 mpr_intr_msi(void *data)
2299 struct mpr_softc *sc;
2301 sc = (struct mpr_softc *)data;
2302 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2304 mpr_intr_locked(data);
2310 * The locking is overly broad and simplistic, but easy to deal with for now.
2313 mpr_intr_locked(void *data)
2315 MPI2_REPLY_DESCRIPTORS_UNION *desc;
2316 struct mpr_softc *sc;
2317 struct mpr_command *cm = NULL;
2320 MPI2_DIAG_RELEASE_REPLY *rel_rep;
2321 mpr_fw_diagnostic_buffer_t *pBuffer;
2323 sc = (struct mpr_softc *)data;
2325 pq = sc->replypostindex;
2326 mpr_dprint(sc, MPR_TRACE,
2327 "%s sc %p starting with replypostindex %u\n",
2328 __func__, sc, sc->replypostindex);
2332 desc = &sc->post_queue[sc->replypostindex];
2333 flags = desc->Default.ReplyFlags &
2334 MPI2_RPY_DESCRIPT_FLAGS_TYPE_MASK;
2335 if ((flags == MPI2_RPY_DESCRIPT_FLAGS_UNUSED) ||
2336 (le32toh(desc->Words.High) == 0xffffffff))
2339 /* increment the replypostindex now, so that event handlers
2340 * and cm completion handlers which decide to do a diag
2341 * reset can zero it without it getting incremented again
2342 * afterwards, and we break out of this loop on the next
2343 * iteration since the reply post queue has been cleared to
2344 * 0xFF and all descriptors look unused (which they are).
2346 if (++sc->replypostindex >= sc->pqdepth)
2347 sc->replypostindex = 0;
2350 case MPI2_RPY_DESCRIPT_FLAGS_SCSI_IO_SUCCESS:
2351 case MPI25_RPY_DESCRIPT_FLAGS_FAST_PATH_SCSI_IO_SUCCESS:
2352 case MPI26_RPY_DESCRIPT_FLAGS_PCIE_ENCAPSULATED_SUCCESS:
2353 cm = &sc->commands[le16toh(desc->SCSIIOSuccess.SMID)];
2354 cm->cm_reply = NULL;
2356 case MPI2_RPY_DESCRIPT_FLAGS_ADDRESS_REPLY:
2362 * Re-compose the reply address from the address
2363 * sent back from the chip. The ReplyFrameAddress
2364 * is the lower 32 bits of the physical address of
2365 * particular reply frame. Convert that address to
2366 * host format, and then use that to provide the
2367 * offset against the virtual address base
2368 * (sc->reply_frames).
2370 baddr = le32toh(desc->AddressReply.ReplyFrameAddress);
2371 reply = sc->reply_frames +
2372 (baddr - ((uint32_t)sc->reply_busaddr));
2374 * Make sure the reply we got back is in a valid
2375 * range. If not, go ahead and panic here, since
2376 * we'll probably panic as soon as we deference the
2377 * reply pointer anyway.
2379 if ((reply < sc->reply_frames)
2380 || (reply > (sc->reply_frames +
2381 (sc->fqdepth * sc->facts->ReplyFrameSize * 4)))) {
2382 printf("%s: WARNING: reply %p out of range!\n",
2384 printf("%s: reply_frames %p, fqdepth %d, "
2385 "frame size %d\n", __func__,
2386 sc->reply_frames, sc->fqdepth,
2387 sc->facts->ReplyFrameSize * 4);
2388 printf("%s: baddr %#x,\n", __func__, baddr);
2389 /* LSI-TODO. See Linux Code for Graceful exit */
2390 panic("Reply address out of range");
2392 if (le16toh(desc->AddressReply.SMID) == 0) {
2393 if (((MPI2_DEFAULT_REPLY *)reply)->Function ==
2394 MPI2_FUNCTION_DIAG_BUFFER_POST) {
2396 * If SMID is 0 for Diag Buffer Post,
2397 * this implies that the reply is due to
2398 * a release function with a status that
2399 * the buffer has been released. Set
2400 * the buffer flags accordingly.
2403 (MPI2_DIAG_RELEASE_REPLY *)reply;
2404 if ((le16toh(rel_rep->IOCStatus) &
2405 MPI2_IOCSTATUS_MASK) ==
2406 MPI2_IOCSTATUS_DIAGNOSTIC_RELEASED)
2409 &sc->fw_diag_buffer_list[
2410 rel_rep->BufferType];
2411 pBuffer->valid_data = TRUE;
2412 pBuffer->owned_by_firmware =
2414 pBuffer->immediate = FALSE;
2417 mpr_dispatch_event(sc, baddr,
2418 (MPI2_EVENT_NOTIFICATION_REPLY *)
2422 le16toh(desc->AddressReply.SMID)];
2423 cm->cm_reply = reply;
2425 le32toh(desc->AddressReply.
2430 case MPI2_RPY_DESCRIPT_FLAGS_TARGETASSIST_SUCCESS:
2431 case MPI2_RPY_DESCRIPT_FLAGS_TARGET_COMMAND_BUFFER:
2432 case MPI2_RPY_DESCRIPT_FLAGS_RAID_ACCELERATOR_SUCCESS:
2435 mpr_dprint(sc, MPR_ERROR, "Unhandled reply 0x%x\n",
2436 desc->Default.ReplyFlags);
2442 // Print Error reply frame
2444 mpr_display_reply_info(sc,cm->cm_reply);
2445 mpr_complete_command(sc, cm);
2448 desc->Words.Low = 0xffffffff;
2449 desc->Words.High = 0xffffffff;
2452 if (pq != sc->replypostindex) {
2453 mpr_dprint(sc, MPR_TRACE,
2454 "%s sc %p writing postindex %d\n",
2455 __func__, sc, sc->replypostindex);
2456 mpr_regwrite(sc, MPI2_REPLY_POST_HOST_INDEX_OFFSET,
2457 sc->replypostindex);
2464 mpr_dispatch_event(struct mpr_softc *sc, uintptr_t data,
2465 MPI2_EVENT_NOTIFICATION_REPLY *reply)
2467 struct mpr_event_handle *eh;
2468 int event, handled = 0;
2470 event = le16toh(reply->Event);
2471 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2472 if (isset(eh->mask, event)) {
2473 eh->callback(sc, data, reply);
2479 mpr_dprint(sc, MPR_EVENT, "Unhandled event 0x%x\n",
2483 * This is the only place that the event/reply should be freed.
2484 * Anything wanting to hold onto the event data should have
2485 * already copied it into their own storage.
2487 mpr_free_reply(sc, data);
2491 mpr_reregister_events_complete(struct mpr_softc *sc, struct mpr_command *cm)
2493 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2496 MPR_DPRINT_EVENT(sc, generic,
2497 (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply);
2499 mpr_free_command(sc, cm);
2501 /* next, send a port enable */
2506 * For both register_events and update_events, the caller supplies a bitmap
2507 * of events that it _wants_. These functions then turn that into a bitmask
2508 * suitable for the controller.
2511 mpr_register_events(struct mpr_softc *sc, uint8_t *mask,
2512 mpr_evt_callback_t *cb, void *data, struct mpr_event_handle **handle)
2514 struct mpr_event_handle *eh;
2517 eh = malloc(sizeof(struct mpr_event_handle), M_MPR, M_WAITOK|M_ZERO);
2519 mpr_dprint(sc, MPR_EVENT|MPR_ERROR,
2520 "Cannot allocate event memory\n");
2525 TAILQ_INSERT_TAIL(&sc->event_list, eh, eh_list);
2527 error = mpr_update_events(sc, eh, mask);
2534 mpr_update_events(struct mpr_softc *sc, struct mpr_event_handle *handle,
2537 MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2538 MPI2_EVENT_NOTIFICATION_REPLY *reply = NULL;
2539 struct mpr_command *cm = NULL;
2540 struct mpr_event_handle *eh;
2543 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2545 if ((mask != NULL) && (handle != NULL))
2546 bcopy(mask, &handle->mask[0], 16);
2547 memset(sc->event_mask, 0xff, 16);
2549 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2550 for (i = 0; i < 16; i++)
2551 sc->event_mask[i] &= ~eh->mask[i];
2554 if ((cm = mpr_alloc_command(sc)) == NULL)
2556 evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2557 evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2558 evtreq->MsgFlags = 0;
2559 evtreq->SASBroadcastPrimitiveMasks = 0;
2560 #ifdef MPR_DEBUG_ALL_EVENTS
2562 u_char fullmask[16];
2563 memset(fullmask, 0x00, 16);
2564 bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2567 bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2569 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2572 error = mpr_request_polled(sc, &cm);
2574 reply = (MPI2_EVENT_NOTIFICATION_REPLY *)cm->cm_reply;
2575 if ((reply == NULL) ||
2576 (reply->IOCStatus & MPI2_IOCSTATUS_MASK) != MPI2_IOCSTATUS_SUCCESS)
2580 MPR_DPRINT_EVENT(sc, generic, reply);
2582 mpr_dprint(sc, MPR_TRACE, "%s finished error %d\n", __func__, error);
2585 mpr_free_command(sc, cm);
2590 mpr_reregister_events(struct mpr_softc *sc)
2592 MPI2_EVENT_NOTIFICATION_REQUEST *evtreq;
2593 struct mpr_command *cm;
2594 struct mpr_event_handle *eh;
2597 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2599 /* first, reregister events */
2601 memset(sc->event_mask, 0xff, 16);
2603 TAILQ_FOREACH(eh, &sc->event_list, eh_list) {
2604 for (i = 0; i < 16; i++)
2605 sc->event_mask[i] &= ~eh->mask[i];
2608 if ((cm = mpr_alloc_command(sc)) == NULL)
2610 evtreq = (MPI2_EVENT_NOTIFICATION_REQUEST *)cm->cm_req;
2611 evtreq->Function = MPI2_FUNCTION_EVENT_NOTIFICATION;
2612 evtreq->MsgFlags = 0;
2613 evtreq->SASBroadcastPrimitiveMasks = 0;
2614 #ifdef MPR_DEBUG_ALL_EVENTS
2616 u_char fullmask[16];
2617 memset(fullmask, 0x00, 16);
2618 bcopy(fullmask, (uint8_t *)&evtreq->EventMasks, 16);
2621 bcopy(sc->event_mask, (uint8_t *)&evtreq->EventMasks, 16);
2623 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
2625 cm->cm_complete = mpr_reregister_events_complete;
2627 error = mpr_map_command(sc, cm);
2629 mpr_dprint(sc, MPR_TRACE, "%s finished with error %d\n", __func__,
2635 mpr_deregister_events(struct mpr_softc *sc, struct mpr_event_handle *handle)
2638 TAILQ_REMOVE(&sc->event_list, handle, eh_list);
2639 free(handle, M_MPR);
2640 return (mpr_update_events(sc, NULL, NULL));
2644 * mpr_build_nvme_prp - This function is called for NVMe end devices to build a
2645 * native SGL (NVMe PRP). The native SGL is built starting in the first PRP entry
2646 * of the NVMe message (PRP1). If the data buffer is small enough to be described
2647 * entirely using PRP1, then PRP2 is not used. If needed, PRP2 is used to
2648 * describe a larger data buffer. If the data buffer is too large to describe
2649 * using the two PRP entriess inside the NVMe message, then PRP1 describes the
2650 * first data memory segment, and PRP2 contains a pointer to a PRP list located
2651 * elsewhere in memory to describe the remaining data memory segments. The PRP
2652 * list will be contiguous.
2654 * The native SGL for NVMe devices is a Physical Region Page (PRP). A PRP
2655 * consists of a list of PRP entries to describe a number of noncontigous
2656 * physical memory segments as a single memory buffer, just as a SGL does. Note
2657 * however, that this function is only used by the IOCTL call, so the memory
2658 * given will be guaranteed to be contiguous. There is no need to translate
2659 * non-contiguous SGL into a PRP in this case. All PRPs will describe contiguous
2660 * space that is one page size each.
2662 * Each NVMe message contains two PRP entries. The first (PRP1) either contains
2663 * a PRP list pointer or a PRP element, depending upon the command. PRP2 contains
2664 * the second PRP element if the memory being described fits within 2 PRP
2665 * entries, or a PRP list pointer if the PRP spans more than two entries.
2667 * A PRP list pointer contains the address of a PRP list, structured as a linear
2668 * array of PRP entries. Each PRP entry in this list describes a segment of
2671 * Each 64-bit PRP entry comprises an address and an offset field. The address
2672 * always points to the beginning of a PAGE_SIZE physical memory page, and the
2673 * offset describes where within that page the memory segment begins. Only the
2674 * first element in a PRP list may contain a non-zero offest, implying that all
2675 * memory segments following the first begin at the start of a PAGE_SIZE page.
2677 * Each PRP element normally describes a chunck of PAGE_SIZE physical memory,
2678 * with exceptions for the first and last elements in the list. If the memory
2679 * being described by the list begins at a non-zero offset within the first page,
2680 * then the first PRP element will contain a non-zero offset indicating where the
2681 * region begins within the page. The last memory segment may end before the end
2682 * of the PAGE_SIZE segment, depending upon the overall size of the memory being
2683 * described by the PRP list.
2685 * Since PRP entries lack any indication of size, the overall data buffer length
2686 * is used to determine where the end of the data memory buffer is located, and
2687 * how many PRP entries are required to describe it.
2692 mpr_build_nvme_prp(struct mpr_softc *sc, struct mpr_command *cm,
2693 Mpi26NVMeEncapsulatedRequest_t *nvme_encap_request, void *data,
2694 uint32_t data_in_sz, uint32_t data_out_sz)
2696 int prp_size = PRP_ENTRY_SIZE;
2697 uint64_t *prp_entry, *prp1_entry, *prp2_entry;
2698 uint64_t *prp_entry_phys, *prp_page, *prp_page_phys;
2699 uint32_t offset, entry_len, page_mask_result, page_mask;
2702 struct mpr_prp_page *prp_page_info = NULL;
2705 * Not all commands require a data transfer. If no data, just return
2706 * without constructing any PRP.
2708 if (!data_in_sz && !data_out_sz)
2712 * Set pointers to PRP1 and PRP2, which are in the NVMe command. PRP1 is
2713 * located at a 24 byte offset from the start of the NVMe command. Then
2714 * set the current PRP entry pointer to PRP1.
2716 prp1_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2717 NVME_CMD_PRP1_OFFSET);
2718 prp2_entry = (uint64_t *)(nvme_encap_request->NVMe_Command +
2719 NVME_CMD_PRP2_OFFSET);
2720 prp_entry = prp1_entry;
2723 * For the PRP entries, use the specially allocated buffer of
2724 * contiguous memory. PRP Page allocation failures should not happen
2725 * because there should be enough PRP page buffers to account for the
2726 * possible NVMe QDepth.
2728 prp_page_info = mpr_alloc_prp_page(sc);
2729 KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
2730 "used for building a native NVMe SGL.\n", __func__));
2731 prp_page = (uint64_t *)prp_page_info->prp_page;
2732 prp_page_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
2735 * Insert the allocated PRP page into the command's PRP page list. This
2736 * will be freed when the command is freed.
2738 TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
2741 * Check if we are within 1 entry of a page boundary we don't want our
2742 * first entry to be a PRP List entry.
2744 page_mask = PAGE_SIZE - 1;
2745 page_mask_result = (uintptr_t)((uint8_t *)prp_page + prp_size) &
2747 if (!page_mask_result)
2749 /* Bump up to next page boundary. */
2750 prp_page = (uint64_t *)((uint8_t *)prp_page + prp_size);
2751 prp_page_phys = (uint64_t *)((uint8_t *)prp_page_phys +
2756 * Set PRP physical pointer, which initially points to the current PRP
2759 prp_entry_phys = prp_page_phys;
2761 /* Get physical address and length of the data buffer. */
2762 paddr = (bus_addr_t)data;
2764 length = data_in_sz;
2766 length = data_out_sz;
2768 /* Loop while the length is not zero. */
2772 * Check if we need to put a list pointer here if we are at page
2773 * boundary - prp_size (8 bytes).
2775 page_mask_result = (uintptr_t)((uint8_t *)prp_entry_phys +
2776 prp_size) & page_mask;
2777 if (!page_mask_result)
2780 * This is the last entry in a PRP List, so we need to
2781 * put a PRP list pointer here. What this does is:
2782 * - bump the current memory pointer to the next
2783 * address, which will be the next full page.
2784 * - set the PRP Entry to point to that page. This is
2785 * now the PRP List pointer.
2786 * - bump the PRP Entry pointer the start of the next
2787 * page. Since all of this PRP memory is contiguous,
2788 * no need to get a new page - it's just the next
2793 htole64((uint64_t)(uintptr_t)prp_entry_phys);
2797 /* Need to handle if entry will be part of a page. */
2798 offset = (uint32_t)paddr & page_mask;
2799 entry_len = PAGE_SIZE - offset;
2801 if (prp_entry == prp1_entry)
2804 * Must fill in the first PRP pointer (PRP1) before
2807 *prp1_entry = htole64((uint64_t)paddr);
2810 * Now point to the second PRP entry within the
2813 prp_entry = prp2_entry;
2815 else if (prp_entry == prp2_entry)
2818 * Should the PRP2 entry be a PRP List pointer or just a
2819 * regular PRP pointer? If there is more than one more
2820 * page of data, must use a PRP List pointer.
2822 if (length > PAGE_SIZE)
2825 * PRP2 will contain a PRP List pointer because
2826 * more PRP's are needed with this command. The
2827 * list will start at the beginning of the
2828 * contiguous buffer.
2832 (uint64_t)(uintptr_t)prp_entry_phys);
2835 * The next PRP Entry will be the start of the
2838 prp_entry = prp_page;
2843 * After this, the PRP Entries are complete.
2844 * This command uses 2 PRP's and no PRP list.
2846 *prp2_entry = htole64((uint64_t)paddr);
2852 * Put entry in list and bump the addresses.
2854 * After PRP1 and PRP2 are filled in, this will fill in
2855 * all remaining PRP entries in a PRP List, one per each
2856 * time through the loop.
2858 *prp_entry = htole64((uint64_t)paddr);
2864 * Bump the phys address of the command's data buffer by the
2869 /* Decrement length accounting for last partial page. */
2870 if (entry_len > length)
2873 length -= entry_len;
2878 * mpr_check_pcie_native_sgl - This function is called for PCIe end devices to
2879 * determine if the driver needs to build a native SGL. If so, that native SGL
2880 * is built in the contiguous buffers allocated especially for PCIe SGL
2881 * creation. If the driver will not build a native SGL, return TRUE and a
2882 * normal IEEE SGL will be built. Currently this routine supports NVMe devices
2885 * Returns FALSE (0) if native SGL was built, TRUE (1) if no SGL was built.
2888 mpr_check_pcie_native_sgl(struct mpr_softc *sc, struct mpr_command *cm,
2889 bus_dma_segment_t *segs, int segs_left)
2891 uint32_t i, sge_dwords, length, offset, entry_len;
2892 uint32_t num_entries, buff_len = 0, sges_in_segment;
2893 uint32_t page_mask, page_mask_result, *curr_buff;
2894 uint32_t *ptr_sgl, *ptr_first_sgl, first_page_offset;
2895 uint32_t first_page_data_size, end_residual;
2898 int build_native_sgl = 0, first_prp_entry;
2899 int prp_size = PRP_ENTRY_SIZE;
2900 Mpi25IeeeSgeChain64_t *main_chain_element = NULL;
2901 struct mpr_prp_page *prp_page_info = NULL;
2903 mpr_dprint(sc, MPR_TRACE, "%s\n", __func__);
2906 * Add up the sizes of each segment length to get the total transfer
2907 * size, which will be checked against the Maximum Data Transfer Size.
2908 * If the data transfer length exceeds the MDTS for this device, just
2909 * return 1 so a normal IEEE SGL will be built. F/W will break the I/O
2910 * up into multiple I/O's. [nvme_mdts = 0 means unlimited]
2912 for (i = 0; i < segs_left; i++)
2913 buff_len += htole32(segs[i].ds_len);
2914 if ((cm->cm_targ->MDTS > 0) && (buff_len > cm->cm_targ->MDTS))
2917 /* Create page_mask (to get offset within page) */
2918 page_mask = PAGE_SIZE - 1;
2921 * Check if the number of elements exceeds the max number that can be
2922 * put in the main message frame (H/W can only translate an SGL that
2923 * is contained entirely in the main message frame).
2925 sges_in_segment = (sc->facts->IOCRequestFrameSize -
2926 offsetof(Mpi25SCSIIORequest_t, SGL)) / sizeof(MPI25_SGE_IO_UNION);
2927 if (segs_left > sges_in_segment)
2928 build_native_sgl = 1;
2932 * NVMe uses one PRP for each physical page (or part of physical
2934 * if 4 pages or less then IEEE is OK
2935 * if > 5 pages then we need to build a native SGL
2936 * if > 4 and <= 5 pages, then check the physical address of
2937 * the first SG entry, then if this first size in the page
2938 * is >= the residual beyond 4 pages then use IEEE,
2939 * otherwise use native SGL
2941 if (buff_len > (PAGE_SIZE * 5))
2942 build_native_sgl = 1;
2943 else if ((buff_len > (PAGE_SIZE * 4)) &&
2944 (buff_len <= (PAGE_SIZE * 5)) )
2946 msg_phys = (uint64_t *)segs[0].ds_addr;
2948 ((uint32_t)(uint64_t)(uintptr_t)msg_phys &
2950 first_page_data_size = PAGE_SIZE - first_page_offset;
2951 end_residual = buff_len % PAGE_SIZE;
2954 * If offset into first page pushes the end of the data
2955 * beyond end of the 5th page, we need the extra PRP
2958 if (first_page_data_size < end_residual)
2959 build_native_sgl = 1;
2962 * Check if first SG entry size is < residual beyond 4
2965 if (htole32(segs[0].ds_len) <
2966 (buff_len - (PAGE_SIZE * 4)))
2967 build_native_sgl = 1;
2971 /* check if native SGL is needed */
2972 if (!build_native_sgl)
2976 * Native SGL is needed.
2977 * Put a chain element in main message frame that points to the first
2980 * NOTE: The ChainOffset field must be 0 when using a chain pointer to
2984 /* Set main message chain element pointer */
2985 main_chain_element = (pMpi25IeeeSgeChain64_t)cm->cm_sge;
2988 * For NVMe the chain element needs to be the 2nd SGL entry in the main
2991 main_chain_element = (Mpi25IeeeSgeChain64_t *)
2992 ((uint8_t *)main_chain_element + sizeof(MPI25_IEEE_SGE_CHAIN64));
2995 * For the PRP entries, use the specially allocated buffer of
2996 * contiguous memory. PRP Page allocation failures should not happen
2997 * because there should be enough PRP page buffers to account for the
2998 * possible NVMe QDepth.
3000 prp_page_info = mpr_alloc_prp_page(sc);
3001 KASSERT(prp_page_info != NULL, ("%s: There are no PRP Pages left to be "
3002 "used for building a native NVMe SGL.\n", __func__));
3003 curr_buff = (uint32_t *)prp_page_info->prp_page;
3004 msg_phys = (uint64_t *)(uintptr_t)prp_page_info->prp_page_busaddr;
3007 * Insert the allocated PRP page into the command's PRP page list. This
3008 * will be freed when the command is freed.
3010 TAILQ_INSERT_TAIL(&cm->cm_prp_page_list, prp_page_info, prp_page_link);
3013 * Check if we are within 1 entry of a page boundary we don't want our
3014 * first entry to be a PRP List entry.
3016 page_mask_result = (uintptr_t)((uint8_t *)curr_buff + prp_size) &
3018 if (!page_mask_result) {
3019 /* Bump up to next page boundary. */
3020 curr_buff = (uint32_t *)((uint8_t *)curr_buff + prp_size);
3021 msg_phys = (uint64_t *)((uint8_t *)msg_phys + prp_size);
3024 /* Fill in the chain element and make it an NVMe segment type. */
3025 main_chain_element->Address.High =
3026 htole32((uint32_t)((uint64_t)(uintptr_t)msg_phys >> 32));
3027 main_chain_element->Address.Low =
3028 htole32((uint32_t)(uintptr_t)msg_phys);
3029 main_chain_element->NextChainOffset = 0;
3030 main_chain_element->Flags = MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3031 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3032 MPI26_IEEE_SGE_FLAGS_NSF_NVME_PRP;
3034 /* Set SGL pointer to start of contiguous PCIe buffer. */
3035 ptr_sgl = curr_buff;
3040 * NVMe has a very convoluted PRP format. One PRP is required for each
3041 * page or partial page. We need to split up OS SG entries if they are
3042 * longer than one page or cross a page boundary. We also have to insert
3043 * a PRP list pointer entry as the last entry in each physical page of
3046 * NOTE: The first PRP "entry" is actually placed in the first SGL entry
3047 * in the main message in IEEE 64 format. The 2nd entry in the main
3048 * message is the chain element, and the rest of the PRP entries are
3049 * built in the contiguous PCIe buffer.
3051 first_prp_entry = 1;
3052 ptr_first_sgl = (uint32_t *)cm->cm_sge;
3054 for (i = 0; i < segs_left; i++) {
3055 /* Get physical address and length of this SG entry. */
3056 paddr = segs[i].ds_addr;
3057 length = segs[i].ds_len;
3060 * Check whether a given SGE buffer lies on a non-PAGED
3061 * boundary if this is not the first page. If so, this is not
3062 * expected so have FW build the SGL.
3064 if ((i != 0) && (((uint32_t)paddr & page_mask) != 0)) {
3065 mpr_dprint(sc, MPR_ERROR, "Unaligned SGE while "
3066 "building NVMe PRPs, low address is 0x%x\n",
3071 /* Apart from last SGE, if any other SGE boundary is not page
3072 * aligned then it means that hole exists. Existence of hole
3073 * leads to data corruption. So fallback to IEEE SGEs.
3075 if (i != (segs_left - 1)) {
3076 if (((uint32_t)paddr + length) & page_mask) {
3077 mpr_dprint(sc, MPR_ERROR, "Unaligned SGE "
3078 "boundary while building NVMe PRPs, low "
3079 "address: 0x%x and length: %u\n",
3080 (uint32_t)paddr, length);
3085 /* Loop while the length is not zero. */
3088 * Check if we need to put a list pointer here if we are
3089 * at page boundary - prp_size.
3091 page_mask_result = (uintptr_t)((uint8_t *)ptr_sgl +
3092 prp_size) & page_mask;
3093 if (!page_mask_result) {
3095 * Need to put a PRP list pointer here.
3097 msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3099 *ptr_sgl = htole32((uintptr_t)msg_phys);
3100 *(ptr_sgl+1) = htole32((uint64_t)(uintptr_t)
3102 ptr_sgl += sge_dwords;
3106 /* Need to handle if entry will be part of a page. */
3107 offset = (uint32_t)paddr & page_mask;
3108 entry_len = PAGE_SIZE - offset;
3109 if (first_prp_entry) {
3111 * Put IEEE entry in first SGE in main message.
3112 * (Simple element, System addr, not end of
3115 *ptr_first_sgl = htole32((uint32_t)paddr);
3116 *(ptr_first_sgl + 1) =
3117 htole32((uint32_t)((uint64_t)paddr >> 32));
3118 *(ptr_first_sgl + 2) = htole32(entry_len);
3119 *(ptr_first_sgl + 3) = 0;
3121 /* No longer the first PRP entry. */
3122 first_prp_entry = 0;
3124 /* Put entry in list. */
3125 *ptr_sgl = htole32((uint32_t)paddr);
3127 htole32((uint32_t)((uint64_t)paddr >> 32));
3129 /* Bump ptr_sgl, msg_phys, and num_entries. */
3130 ptr_sgl += sge_dwords;
3131 msg_phys = (uint64_t *)((uint8_t *)msg_phys +
3136 /* Bump the phys address by the entry_len. */
3139 /* Decrement length accounting for last partial page. */
3140 if (entry_len > length)
3143 length -= entry_len;
3147 /* Set chain element Length. */
3148 main_chain_element->Length = htole32(num_entries * prp_size);
3150 /* Return 0, indicating we built a native SGL. */
3155 * Add a chain element as the next SGE for the specified command.
3156 * Reset cm_sge and cm_sgesize to indicate all the available space. Chains are
3157 * only required for IEEE commands. Therefore there is no code for commands
3158 * that have the MPR_CM_FLAGS_SGE_SIMPLE flag set (and those commands
3159 * shouldn't be requesting chains).
3162 mpr_add_chain(struct mpr_command *cm, int segsleft)
3164 struct mpr_softc *sc = cm->cm_sc;
3165 MPI2_REQUEST_HEADER *req;
3166 MPI25_IEEE_SGE_CHAIN64 *ieee_sgc;
3167 struct mpr_chain *chain;
3168 int sgc_size, current_segs, rem_segs, segs_per_frame;
3169 uint8_t next_chain_offset = 0;
3172 * Fail if a command is requesting a chain for SIMPLE SGE's. For SAS3
3173 * only IEEE commands should be requesting chains. Return some error
3174 * code other than 0.
3176 if (cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE) {
3177 mpr_dprint(sc, MPR_ERROR, "A chain element cannot be added to "
3182 sgc_size = sizeof(MPI25_IEEE_SGE_CHAIN64);
3183 if (cm->cm_sglsize < sgc_size)
3184 panic("MPR: Need SGE Error Code\n");
3186 chain = mpr_alloc_chain(cm->cm_sc);
3191 * Note: a double-linked list is used to make it easier to walk for
3194 TAILQ_INSERT_TAIL(&cm->cm_chain_list, chain, chain_link);
3197 * Need to know if the number of frames left is more than 1 or not. If
3198 * more than 1 frame is required, NextChainOffset will need to be set,
3199 * which will just be the last segment of the frame.
3202 if (cm->cm_sglsize < (sgc_size * segsleft)) {
3204 * rem_segs is the number of segements remaining after the
3205 * segments that will go into the current frame. Since it is
3206 * known that at least one more frame is required, account for
3207 * the chain element. To know if more than one more frame is
3208 * required, just check if there will be a remainder after using
3209 * the current frame (with this chain) and the next frame. If
3210 * so the NextChainOffset must be the last element of the next
3213 current_segs = (cm->cm_sglsize / sgc_size) - 1;
3214 rem_segs = segsleft - current_segs;
3215 segs_per_frame = sc->chain_frame_size / sgc_size;
3216 if (rem_segs > segs_per_frame) {
3217 next_chain_offset = segs_per_frame - 1;
3220 ieee_sgc = &((MPI25_SGE_IO_UNION *)cm->cm_sge)->IeeeChain;
3221 ieee_sgc->Length = next_chain_offset ?
3222 htole32((uint32_t)sc->chain_frame_size) :
3223 htole32((uint32_t)rem_segs * (uint32_t)sgc_size);
3224 ieee_sgc->NextChainOffset = next_chain_offset;
3225 ieee_sgc->Flags = (MPI2_IEEE_SGE_FLAGS_CHAIN_ELEMENT |
3226 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3227 ieee_sgc->Address.Low = htole32(chain->chain_busaddr);
3228 ieee_sgc->Address.High = htole32(chain->chain_busaddr >> 32);
3229 cm->cm_sge = &((MPI25_SGE_IO_UNION *)chain->chain)->IeeeSimple;
3230 req = (MPI2_REQUEST_HEADER *)cm->cm_req;
3231 req->ChainOffset = (sc->chain_frame_size - sgc_size) >> 4;
3233 cm->cm_sglsize = sc->chain_frame_size;
3238 * Add one scatter-gather element to the scatter-gather list for a command.
3239 * Maintain cm_sglsize and cm_sge as the remaining size and pointer to the
3240 * next SGE to fill in, respectively. In Gen3, the MPI SGL does not have a
3241 * chain, so don't consider any chain additions.
3244 mpr_push_sge(struct mpr_command *cm, MPI2_SGE_SIMPLE64 *sge, size_t len,
3247 uint32_t saved_buf_len, saved_address_low, saved_address_high;
3251 * case 1: >=1 more segment, no room for anything (error)
3252 * case 2: 1 more segment and enough room for it
3255 if (cm->cm_sglsize < (segsleft * sizeof(MPI2_SGE_SIMPLE64))) {
3256 mpr_dprint(cm->cm_sc, MPR_ERROR,
3257 "%s: warning: Not enough room for MPI SGL in frame.\n",
3262 KASSERT(segsleft == 1,
3263 ("segsleft cannot be more than 1 for an MPI SGL; segsleft = %d\n",
3267 * There is one more segment left to add for the MPI SGL and there is
3268 * enough room in the frame to add it. This is the normal case because
3269 * MPI SGL's don't have chains, otherwise something is wrong.
3271 * If this is a bi-directional request, need to account for that
3272 * here. Save the pre-filled sge values. These will be used
3273 * either for the 2nd SGL or for a single direction SGL. If
3274 * cm_out_len is non-zero, this is a bi-directional request, so
3275 * fill in the OUT SGL first, then the IN SGL, otherwise just
3276 * fill in the IN SGL. Note that at this time, when filling in
3277 * 2 SGL's for a bi-directional request, they both use the same
3278 * DMA buffer (same cm command).
3280 saved_buf_len = sge->FlagsLength & 0x00FFFFFF;
3281 saved_address_low = sge->Address.Low;
3282 saved_address_high = sge->Address.High;
3283 if (cm->cm_out_len) {
3284 sge->FlagsLength = cm->cm_out_len |
3285 ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3286 MPI2_SGE_FLAGS_END_OF_BUFFER |
3287 MPI2_SGE_FLAGS_HOST_TO_IOC |
3288 MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3289 MPI2_SGE_FLAGS_SHIFT);
3290 cm->cm_sglsize -= len;
3291 /* Endian Safe code */
3292 sge_flags = sge->FlagsLength;
3293 sge->FlagsLength = htole32(sge_flags);
3294 sge->Address.High = htole32(sge->Address.High);
3295 sge->Address.Low = htole32(sge->Address.Low);
3296 bcopy(sge, cm->cm_sge, len);
3297 cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3299 sge->FlagsLength = saved_buf_len |
3300 ((uint32_t)(MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3301 MPI2_SGE_FLAGS_END_OF_BUFFER |
3302 MPI2_SGE_FLAGS_LAST_ELEMENT |
3303 MPI2_SGE_FLAGS_END_OF_LIST |
3304 MPI2_SGE_FLAGS_64_BIT_ADDRESSING) <<
3305 MPI2_SGE_FLAGS_SHIFT);
3306 if (cm->cm_flags & MPR_CM_FLAGS_DATAIN) {
3308 ((uint32_t)(MPI2_SGE_FLAGS_IOC_TO_HOST) <<
3309 MPI2_SGE_FLAGS_SHIFT);
3312 ((uint32_t)(MPI2_SGE_FLAGS_HOST_TO_IOC) <<
3313 MPI2_SGE_FLAGS_SHIFT);
3315 sge->Address.Low = saved_address_low;
3316 sge->Address.High = saved_address_high;
3318 cm->cm_sglsize -= len;
3319 /* Endian Safe code */
3320 sge_flags = sge->FlagsLength;
3321 sge->FlagsLength = htole32(sge_flags);
3322 sge->Address.High = htole32(sge->Address.High);
3323 sge->Address.Low = htole32(sge->Address.Low);
3324 bcopy(sge, cm->cm_sge, len);
3325 cm->cm_sge = (MPI2_SGE_IO_UNION *)((uintptr_t)cm->cm_sge + len);
3330 * Add one IEEE scatter-gather element (chain or simple) to the IEEE scatter-
3331 * gather list for a command. Maintain cm_sglsize and cm_sge as the
3332 * remaining size and pointer to the next SGE to fill in, respectively.
3335 mpr_push_ieee_sge(struct mpr_command *cm, void *sgep, int segsleft)
3337 MPI2_IEEE_SGE_SIMPLE64 *sge = sgep;
3338 int error, ieee_sge_size = sizeof(MPI25_SGE_IO_UNION);
3339 uint32_t saved_buf_len, saved_address_low, saved_address_high;
3340 uint32_t sge_length;
3343 * case 1: No room for chain or segment (error).
3344 * case 2: Two or more segments left but only room for chain.
3345 * case 3: Last segment and room for it, so set flags.
3349 * There should be room for at least one element, or there is a big
3352 if (cm->cm_sglsize < ieee_sge_size)
3353 panic("MPR: Need SGE Error Code\n");
3355 if ((segsleft >= 2) && (cm->cm_sglsize < (ieee_sge_size * 2))) {
3356 if ((error = mpr_add_chain(cm, segsleft)) != 0)
3360 if (segsleft == 1) {
3362 * If this is a bi-directional request, need to account for that
3363 * here. Save the pre-filled sge values. These will be used
3364 * either for the 2nd SGL or for a single direction SGL. If
3365 * cm_out_len is non-zero, this is a bi-directional request, so
3366 * fill in the OUT SGL first, then the IN SGL, otherwise just
3367 * fill in the IN SGL. Note that at this time, when filling in
3368 * 2 SGL's for a bi-directional request, they both use the same
3369 * DMA buffer (same cm command).
3371 saved_buf_len = sge->Length;
3372 saved_address_low = sge->Address.Low;
3373 saved_address_high = sge->Address.High;
3374 if (cm->cm_out_len) {
3375 sge->Length = cm->cm_out_len;
3376 sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3377 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3378 cm->cm_sglsize -= ieee_sge_size;
3379 /* Endian Safe code */
3380 sge_length = sge->Length;
3381 sge->Length = htole32(sge_length);
3382 sge->Address.High = htole32(sge->Address.High);
3383 sge->Address.Low = htole32(sge->Address.Low);
3384 bcopy(sgep, cm->cm_sge, ieee_sge_size);
3386 (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3389 sge->Length = saved_buf_len;
3390 sge->Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3391 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR |
3392 MPI25_IEEE_SGE_FLAGS_END_OF_LIST);
3393 sge->Address.Low = saved_address_low;
3394 sge->Address.High = saved_address_high;
3397 cm->cm_sglsize -= ieee_sge_size;
3398 /* Endian Safe code */
3399 sge_length = sge->Length;
3400 sge->Length = htole32(sge_length);
3401 sge->Address.High = htole32(sge->Address.High);
3402 sge->Address.Low = htole32(sge->Address.Low);
3403 bcopy(sgep, cm->cm_sge, ieee_sge_size);
3404 cm->cm_sge = (MPI25_SGE_IO_UNION *)((uintptr_t)cm->cm_sge +
3410 * Add one dma segment to the scatter-gather list for a command.
3413 mpr_add_dmaseg(struct mpr_command *cm, vm_paddr_t pa, size_t len, u_int flags,
3416 MPI2_SGE_SIMPLE64 sge;
3417 MPI2_IEEE_SGE_SIMPLE64 ieee_sge;
3419 if (!(cm->cm_flags & MPR_CM_FLAGS_SGE_SIMPLE)) {
3420 ieee_sge.Flags = (MPI2_IEEE_SGE_FLAGS_SIMPLE_ELEMENT |
3421 MPI2_IEEE_SGE_FLAGS_SYSTEM_ADDR);
3422 ieee_sge.Length = len;
3423 mpr_from_u64(pa, &ieee_sge.Address);
3425 return (mpr_push_ieee_sge(cm, &ieee_sge, segsleft));
3428 * This driver always uses 64-bit address elements for
3431 flags |= MPI2_SGE_FLAGS_SIMPLE_ELEMENT |
3432 MPI2_SGE_FLAGS_64_BIT_ADDRESSING;
3433 /* Set Endian safe macro in mpr_push_sge */
3434 sge.FlagsLength = len | (flags << MPI2_SGE_FLAGS_SHIFT);
3435 mpr_from_u64(pa, &sge.Address);
3437 return (mpr_push_sge(cm, &sge, sizeof sge, segsleft));
3442 mpr_data_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3444 struct mpr_softc *sc;
3445 struct mpr_command *cm;
3446 u_int i, dir, sflags;
3448 cm = (struct mpr_command *)arg;
3452 * In this case, just print out a warning and let the chip tell the
3453 * user they did the wrong thing.
3455 if ((cm->cm_max_segs != 0) && (nsegs > cm->cm_max_segs)) {
3456 mpr_dprint(sc, MPR_ERROR, "%s: warning: busdma returned %d "
3457 "segments, more than the %d allowed\n", __func__, nsegs,
3462 * Set up DMA direction flags. Bi-directional requests are also handled
3463 * here. In that case, both direction flags will be set.
3466 if (cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) {
3468 * We have to add a special case for SMP passthrough, there
3469 * is no easy way to generically handle it. The first
3470 * S/G element is used for the command (therefore the
3471 * direction bit needs to be set). The second one is used
3472 * for the reply. We'll leave it to the caller to make
3473 * sure we only have two buffers.
3476 * Even though the busdma man page says it doesn't make
3477 * sense to have both direction flags, it does in this case.
3478 * We have one s/g element being accessed in each direction.
3480 dir = BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD;
3483 * Set the direction flag on the first buffer in the SMP
3484 * passthrough request. We'll clear it for the second one.
3486 sflags |= MPI2_SGE_FLAGS_DIRECTION |
3487 MPI2_SGE_FLAGS_END_OF_BUFFER;
3488 } else if (cm->cm_flags & MPR_CM_FLAGS_DATAOUT) {
3489 sflags |= MPI2_SGE_FLAGS_HOST_TO_IOC;
3490 dir = BUS_DMASYNC_PREWRITE;
3492 dir = BUS_DMASYNC_PREREAD;
3494 /* Check if a native SG list is needed for an NVMe PCIe device. */
3495 if (cm->cm_targ && cm->cm_targ->is_nvme &&
3496 mpr_check_pcie_native_sgl(sc, cm, segs, nsegs) == 0) {
3497 /* A native SG list was built, skip to end. */
3501 for (i = 0; i < nsegs; i++) {
3502 if ((cm->cm_flags & MPR_CM_FLAGS_SMP_PASS) && (i != 0)) {
3503 sflags &= ~MPI2_SGE_FLAGS_DIRECTION;
3505 error = mpr_add_dmaseg(cm, segs[i].ds_addr, segs[i].ds_len,
3508 /* Resource shortage, roll back! */
3509 if (ratecheck(&sc->lastfail, &mpr_chainfail_interval))
3510 mpr_dprint(sc, MPR_INFO, "Out of chain frames, "
3511 "consider increasing hw.mpr.max_chains.\n");
3512 cm->cm_flags |= MPR_CM_FLAGS_CHAIN_FAILED;
3513 mpr_complete_command(sc, cm);
3519 bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap, dir);
3520 mpr_enqueue_request(sc, cm);
3526 mpr_data_cb2(void *arg, bus_dma_segment_t *segs, int nsegs, bus_size_t mapsize,
3529 mpr_data_cb(arg, segs, nsegs, error);
3533 * This is the routine to enqueue commands ansynchronously.
3534 * Note that the only error path here is from bus_dmamap_load(), which can
3535 * return EINPROGRESS if it is waiting for resources. Other than this, it's
3536 * assumed that if you have a command in-hand, then you have enough credits
3540 mpr_map_command(struct mpr_softc *sc, struct mpr_command *cm)
3544 if (cm->cm_flags & MPR_CM_FLAGS_USE_UIO) {
3545 error = bus_dmamap_load_uio(sc->buffer_dmat, cm->cm_dmamap,
3546 &cm->cm_uio, mpr_data_cb2, cm, 0);
3547 } else if (cm->cm_flags & MPR_CM_FLAGS_USE_CCB) {
3548 error = bus_dmamap_load_ccb(sc->buffer_dmat, cm->cm_dmamap,
3549 cm->cm_data, mpr_data_cb, cm, 0);
3550 } else if ((cm->cm_data != NULL) && (cm->cm_length != 0)) {
3551 error = bus_dmamap_load(sc->buffer_dmat, cm->cm_dmamap,
3552 cm->cm_data, cm->cm_length, mpr_data_cb, cm, 0);
3554 /* Add a zero-length element as needed */
3555 if (cm->cm_sge != NULL)
3556 mpr_add_dmaseg(cm, 0, 0, 0, 1);
3557 mpr_enqueue_request(sc, cm);
3564 * This is the routine to enqueue commands synchronously. An error of
3565 * EINPROGRESS from mpr_map_command() is ignored since the command will
3566 * be executed and enqueued automatically. Other errors come from msleep().
3569 mpr_wait_command(struct mpr_softc *sc, struct mpr_command **cmp, int timeout,
3573 struct timeval cur_time, start_time;
3574 struct mpr_command *cm = *cmp;
3576 if (sc->mpr_flags & MPR_FLAGS_DIAGRESET)
3579 cm->cm_complete = NULL;
3580 cm->cm_flags |= (MPR_CM_FLAGS_WAKEUP + MPR_CM_FLAGS_POLLED);
3581 error = mpr_map_command(sc, cm);
3582 if ((error != 0) && (error != EINPROGRESS))
3585 // Check for context and wait for 50 mSec at a time until time has
3586 // expired or the command has finished. If msleep can't be used, need
3588 #if __FreeBSD_version >= 1000029
3589 if (curthread->td_no_sleeping)
3590 #else //__FreeBSD_version < 1000029
3591 if (curthread->td_pflags & TDP_NOSLEEPING)
3592 #endif //__FreeBSD_version >= 1000029
3593 sleep_flag = NO_SLEEP;
3594 getmicrouptime(&start_time);
3595 if (mtx_owned(&sc->mpr_mtx) && sleep_flag == CAN_SLEEP) {
3596 error = msleep(cm, &sc->mpr_mtx, 0, "mprwait", timeout*hz);
3597 if (error == EWOULDBLOCK) {
3599 * Record the actual elapsed time in the case of a
3600 * timeout for the message below.
3602 getmicrouptime(&cur_time);
3603 timevalsub(&cur_time, &start_time);
3606 while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3607 mpr_intr_locked(sc);
3608 if (sleep_flag == CAN_SLEEP)
3609 pause("mprwait", hz/20);
3613 getmicrouptime(&cur_time);
3614 timevalsub(&cur_time, &start_time);
3615 if (cur_time.tv_sec > timeout) {
3616 error = EWOULDBLOCK;
3622 if (error == EWOULDBLOCK) {
3623 mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s, timeout=%d,"
3624 " elapsed=%jd\n", __func__, timeout,
3625 (intmax_t)cur_time.tv_sec);
3626 rc = mpr_reinit(sc);
3627 mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3629 if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3631 * Tell the caller that we freed the command in a
3642 * This is the routine to enqueue a command synchonously and poll for
3643 * completion. Its use should be rare.
3646 mpr_request_polled(struct mpr_softc *sc, struct mpr_command **cmp)
3649 struct timeval cur_time, start_time;
3650 struct mpr_command *cm = *cmp;
3654 cm->cm_flags |= MPR_CM_FLAGS_POLLED;
3655 cm->cm_complete = NULL;
3656 mpr_map_command(sc, cm);
3658 getmicrouptime(&start_time);
3659 while ((cm->cm_flags & MPR_CM_FLAGS_COMPLETE) == 0) {
3660 mpr_intr_locked(sc);
3662 if (mtx_owned(&sc->mpr_mtx))
3663 msleep(&sc->msleep_fake_chan, &sc->mpr_mtx, 0,
3666 pause("mprpoll", hz/20);
3669 * Check for real-time timeout and fail if more than 60 seconds.
3671 getmicrouptime(&cur_time);
3672 timevalsub(&cur_time, &start_time);
3673 if (cur_time.tv_sec > 60) {
3674 mpr_dprint(sc, MPR_FAULT, "polling failed\n");
3681 mpr_dprint(sc, MPR_FAULT, "Calling Reinit from %s\n", __func__);
3682 rc = mpr_reinit(sc);
3683 mpr_dprint(sc, MPR_FAULT, "Reinit %s\n", (rc == 0) ? "success" :
3686 if (sc->mpr_flags & MPR_FLAGS_REALLOCATED) {
3688 * Tell the caller that we freed the command in a
3698 * The MPT driver had a verbose interface for config pages. In this driver,
3699 * reduce it to much simpler terms, similar to the Linux driver.
3702 mpr_read_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3704 MPI2_CONFIG_REQUEST *req;
3705 struct mpr_command *cm;
3708 if (sc->mpr_flags & MPR_FLAGS_BUSY) {
3712 cm = mpr_alloc_command(sc);
3717 req = (MPI2_CONFIG_REQUEST *)cm->cm_req;
3718 req->Function = MPI2_FUNCTION_CONFIG;
3719 req->Action = params->action;
3721 req->ChainOffset = 0;
3722 req->PageAddress = params->page_address;
3723 if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3724 MPI2_CONFIG_EXTENDED_PAGE_HEADER *hdr;
3726 hdr = ¶ms->hdr.Ext;
3727 req->ExtPageType = hdr->ExtPageType;
3728 req->ExtPageLength = hdr->ExtPageLength;
3729 req->Header.PageType = MPI2_CONFIG_PAGETYPE_EXTENDED;
3730 req->Header.PageLength = 0; /* Must be set to zero */
3731 req->Header.PageNumber = hdr->PageNumber;
3732 req->Header.PageVersion = hdr->PageVersion;
3734 MPI2_CONFIG_PAGE_HEADER *hdr;
3736 hdr = ¶ms->hdr.Struct;
3737 req->Header.PageType = hdr->PageType;
3738 req->Header.PageNumber = hdr->PageNumber;
3739 req->Header.PageLength = hdr->PageLength;
3740 req->Header.PageVersion = hdr->PageVersion;
3743 cm->cm_data = params->buffer;
3744 cm->cm_length = params->length;
3745 if (cm->cm_data != NULL) {
3746 cm->cm_sge = &req->PageBufferSGE;
3747 cm->cm_sglsize = sizeof(MPI2_SGE_IO_UNION);
3748 cm->cm_flags = MPR_CM_FLAGS_SGE_SIMPLE | MPR_CM_FLAGS_DATAIN;
3751 cm->cm_desc.Default.RequestFlags = MPI2_REQ_DESCRIPT_FLAGS_DEFAULT_TYPE;
3753 cm->cm_complete_data = params;
3754 if (params->callback != NULL) {
3755 cm->cm_complete = mpr_config_complete;
3756 return (mpr_map_command(sc, cm));
3758 error = mpr_wait_command(sc, &cm, 0, CAN_SLEEP);
3760 mpr_dprint(sc, MPR_FAULT,
3761 "Error %d reading config page\n", error);
3763 mpr_free_command(sc, cm);
3766 mpr_config_complete(sc, cm);
3773 mpr_write_config_page(struct mpr_softc *sc, struct mpr_config_params *params)
3779 mpr_config_complete(struct mpr_softc *sc, struct mpr_command *cm)
3781 MPI2_CONFIG_REPLY *reply;
3782 struct mpr_config_params *params;
3785 params = cm->cm_complete_data;
3787 if (cm->cm_data != NULL) {
3788 bus_dmamap_sync(sc->buffer_dmat, cm->cm_dmamap,
3789 BUS_DMASYNC_POSTREAD);
3790 bus_dmamap_unload(sc->buffer_dmat, cm->cm_dmamap);
3794 * XXX KDM need to do more error recovery? This results in the
3795 * device in question not getting probed.
3797 if ((cm->cm_flags & MPR_CM_FLAGS_ERROR_MASK) != 0) {
3798 params->status = MPI2_IOCSTATUS_BUSY;
3802 reply = (MPI2_CONFIG_REPLY *)cm->cm_reply;
3803 if (reply == NULL) {
3804 params->status = MPI2_IOCSTATUS_BUSY;
3807 params->status = reply->IOCStatus;
3808 if (params->hdr.Struct.PageType == MPI2_CONFIG_PAGETYPE_EXTENDED) {
3809 params->hdr.Ext.ExtPageType = reply->ExtPageType;
3810 params->hdr.Ext.ExtPageLength = reply->ExtPageLength;
3811 params->hdr.Ext.PageType = reply->Header.PageType;
3812 params->hdr.Ext.PageNumber = reply->Header.PageNumber;
3813 params->hdr.Ext.PageVersion = reply->Header.PageVersion;
3815 params->hdr.Struct.PageType = reply->Header.PageType;
3816 params->hdr.Struct.PageNumber = reply->Header.PageNumber;
3817 params->hdr.Struct.PageLength = reply->Header.PageLength;
3818 params->hdr.Struct.PageVersion = reply->Header.PageVersion;
3822 mpr_free_command(sc, cm);
3823 if (params->callback != NULL)
3824 params->callback(sc, params);