powerpc: use the register validity flags in the vector ptrace requests
PT_SETVRREGS and PT_SETVSRREGS set PCB_VEC and PCB_VSX, which say the
thread owns the unit, instead of PCB_VECREGS and PCB_FPREGS, which say
the saved registers are valid. Ownership should only come from the
unavailable trap or cpu_switchin(), and the trap asserts it isn't set
yet, so setting the VSX registers of a traced child that hasn't used
the FPU panics an INVARIANTS kernel on the child's first VSX
instruction. Tracing your own child is enough, no privilege needed.
The getters had the matching problem: they returned the saved
registers only while the thread owned the unit, so a thread stopped
with valid but unloaded registers showed the debugger zeroes.
The thread is stopped, so the PCB is what counts. Set and test the
validity flags instead.
Reviewed by: jhibbits
MFC after: 1 week
Differential Revision: https://reviews.freebsd.org/D62035
mpi3mr: Fix HostTag conversion in timestamp sync
In mpi3mr_timestamp_sync(), HostTag is a 16-bit field (U16) in
Mpi3IoUnitControlRequest_t. It was incorrectly initialized using
htole64(MPI3MR_HOSTTAG_INITCMDS) instead of htole16().
On little-endian architectures (amd64, arm64), htole64(1) leaves the
value as 1, which fits into a 16-bit integer without value truncation.
However, on big-endian architectures (such as powerpc64), htole64(1)
byte-swaps the 64-bit value to 0x0100000000000000 (72057594037927936).
Assigning this to a U16 causes truncation to 0 and triggers a fatal
compiler build failure under -Werror=constant-conversion:
implicit conversion from 'unsigned long' to 'U16' (aka 'unsigned short')
changes value from 72057594037927936 to 0 [-Wconstant-conversion]
Fix this by using htole16(), consistent with all other HostTag
initializations in the driver.
[2 lines not shown]
mpi3mr: Validate event bounds and tighten error handling
Validate firmware event payload lengths in top-half and bottom-half
event handlers for device status change, prepare-for-reset, energy pack
change, cable management, and device info change events to prevent
buffer over-reads on truncated or malformed firmware packets. Propagate
validation status from the device status top-half handler to prevent
scheduling bottom-half worker processing for invalid packets.
In addition, unlock the admin request spinlock when rejecting
submissions on unrecoverable controllers to avoid deadlocks. Synchronize
event queue teardown with the dedicated firmware event lock rather than
the main driver mutex to match worker queue locking, and add null checks
for memory allocations in CAM attach and bitmap scanning routines.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60344
mpi3mr: Validate event payload sizes before deferred event processing
When processing asynchronous firmware events deferred to bottom-half
workers, the driver previously cast and dereferenced event payload
buffers directly into target structures - specifically device status
change and device configuration page structures - without verifying
whether the received payload was large enough to contain the expected
structure.
If a truncated, corrupted, or zero-length event was queued by top-half
processing, accessing these fields caused out-of-bounds memory reads
beyond the allocated event payload buffer. In addition, persistent
target identifiers in device addition events were extracted without
converting from little-endian format to host endianness.
Validate that event payload sizes are at least as large as the target
event structures before dereferencing fields, and ensure persistent
device identifiers are properly converted from little-endian to host
byte order.
[3 lines not shown]
mpi3mr: Enforce runtime bounds on SGL segments and CDB lengths
Several runtime boundary checks in the I/O submission path previously
relied only on debug assertions or lacked complete validation:
1. When preparing scatter-gather lists for DMA, segment count validation
relied only on a debug assertion that is omitted in production
builds. If a command exceeded the controller's maximum supported
segment count, the driver proceeded to build the scatter-gather list
past allocated descriptor memory.
2. In the filter for unsupported SATA commands, the target structure's
type-specific union was dereferenced without first checking the
device form factor, risking type confusion on NVMe or Virtual Disk
targets. In addition, CDB bytes were read only from the inline array,
ignoring pointer-based commands.
3. In the SCSI command submission path, incoming command lengths were
not checked against the 32-byte capacity of the hardware request
frame, risking frame overflow.
[7 lines not shown]
mpi3mr: Update driver version to 8.20.0.4.0
Update the driver version to 8.20.0.4.0.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60346
mpi3mr: Use sx lock for IOCTL serialization
Holding a non-sleepable mutex across IOCTL processing violates
locking invariants, as copying data to and from user space can
page fault and firmware completion waits sleep via pause().
Replace the mutex with a sleepable sx (shared/exclusive) lock to
serialize driver and MPT IOCTL execution across sleepable boundaries.
Initialize the sx lock during controller setup and release it during
driver teardown.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60345
mpi3mr: Fix management command timeouts and teardown ordering during detach
During driver unload under active I/O, the driver resets the controller
via Message Unit Reset (MUR). Firmware sends completion events during
the reset, but the driver was discarding them because the shutdown flag
was set. Dropping these completions caused pending management IOCTLs to
time out, leaving the controller in a faulted state that prevented clean
re-initialization on subsequent driver reloads.
In addition, userland character device nodes were detached after the
hardware reset, allowing new IOCTLs to arrive while hardware cleanup was
underway.
Fix these issues by:
1. Removing the shutdown check in event processing so in-flight
completions finish normally instead of timing out.
2. Detaching userland device nodes before tearing down hardware
resources to prevent new IOCTLs from arriving during unload.
[3 lines not shown]
mpi3mr: Validate request queue ID and consumer index bounds in completions
When processing command completions, the driver receives completion
descriptors containing the request queue ID and the updated request
queue consumer index. Previously, the driver trusted these values
without bounds checking.
If an invalid queue ID was reported for an operational completion, using
it to index the operational queue array caused an out-of-bounds access.
In addition, if a consumer index exceeded the queue capacity (in either
an admin or operational completion), the driver stored an out-of-bounds
index into its internal tracking.
Validate that the operational request queue ID is within the range of
allocated queues before indexing, and verify that the consumer index is
within queue depth for both admin and operational queues before updating
tracking.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60339
mpi3mr: Validate entry counts against payload length in topology events
When the controller notifies the driver of SAS or PCIe topology changes,
the firmware event notification includes a payload length and an entry
count indicating the number of PHY or port descriptors attached to the
event. Previously, the top-half event handlers iterated over the entry
count without verifying whether the payload buffer was actually large
enough to contain all reported entries. A malformed event with an entry
count exceeding the buffer length would result in reading memory beyond
the event descriptor.
Validate that the reported event length covers the base topology header
and compute the maximum number of entries that fit within the payload.
If the entry count exceeds the available buffer, reject the event and
skip scheduling deferred bottom-half processing.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60336
mpi3mr: Bound event payload and log data copies to allocated buffer sizes
When processing asynchronous event notifications from controller
firmware, the driver trusted the firmware-reported event data length
without verifying whether it fit within the physical reply buffer frame.
If an event reported a length exceeding the reply frame size, copying
the payload into bottom-half event queues or saving diagnostic log data
caused memory reads beyond the reply buffer boundaries.
In addition, when saving log data into the driver's circular logging
buffer, the copy size was bounded against the total slot size rather
than the payload capacity, failing to account for the entry header and
causing writes to overflow into adjacent buffer slots.
Clamp all event data copy lengths to the maximum capacity of the reply
buffer frame, and account for entry header overhead when saving log data
to prevent buffer overflows.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60337
mpi3mr: Enforce frame alignment and bounds checks on reply and sense buffers
When the controller posts command completions or sense data, firmware
provides physical DMA addresses that the driver translates into virtual
addresses within its pre-allocated reply and sense buffer pools.
Previously, these address translation helpers lacked complete
validation:
1. The reply buffer lookup checked only the starting physical address
without verifying that the full frame size fit within the pool,
and did not check whether the address aligned to the fixed reply
frame stride.
2. The sense buffer lookup performed no bounds checking whatsoever,
blindly computing an offset from the pool base.
If firmware reported a corrupted address or an unaligned offset,
the driver computed an invalid virtual pointer, leading to memory
access outside the allocated buffer pools.
[8 lines not shown]
mpi3mr: Re-resolve target handle during error recovery and flush
When an I/O request encounters a timeout or requires error recovery
(such as aborts or target resets), the recovery routines previously
dereferenced the cached target structure pointer stored in the command.
If the target device was detached or removed from the system while the
timed-out request was pending, the target structure had already been
freed, causing error recovery and I/O flush routines to dereference
freed memory.
Store the target device's hardware handle in the command structure at
submission time, and re-resolve the target by handle from the active
device list during error recovery, task management, and I/O flushing. If
the target no longer exists in the active list, recovery routines skip
the command safely without dereferencing freed pointers.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60340
mpi3mr: Validate user buffer length against SGE overhead in RAID management
For RAID management passthrough commands, the driver embeds the
scatter-gather list directly inside the kernel DMA buffer immediately
following the user data payload. Previously, the driver did not verify
that the kernel buffer had sufficient room to hold both the user data
and the required scatter-gather element.
If a userland request supplied a buffer length that left less space than
a single scatter-gather element, unsigned subtraction underflowed the
available descriptor calculation. This bypassed subsequent bounds checks
and resulted in memory corruption when constructing the scatter-gather
list past the end of the allocated buffer.
Validate that the user buffer length leaves sufficient space for the
scatter-gather element overhead, safely rejecting oversized requests
before constructing the scatter-gather list.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60334
mpi3mr: Validate buffer entry sizes and descriptor counts in MPT IOCTLs
In the MPI passthrough IOCTL handler, the userland buffer entry list was
parsed without verifying whether the user-supplied buffer size was large
enough to hold the claimed number of entries. A malformed or malicious
request specifying a large entry count with a small buffer size could
cause the driver to read past user-allocated memory during copy
operations. In addition, the scatter-gather descriptor counter was
defined as an 8-bit integer, risking truncation when processing large
data transfers requiring more than 255 descriptors.
Validate that the user-provided buffer size accommodates the header and
all requested buffer entries before parsing, widen descriptor counting
to 16 bits, and use exact structure member offsets when computing target
device information lengths.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60333
mpi3mr: Fix firmware package version reporting from active flash partition
During controller initialization and post-reset, the driver retrieves
and logs the firmware package version. Previously, the component image
upload request used incorrect offset and signature parameters,
preventing the driver from reading the complete package manifest.
In addition, after online firmware updates or when booting in dual-image
environments, the controller can execute from either the primary or
secondary flash partition. The driver previously queried only the
primary partition without evaluating the active boot status in the
controller exceptions flags, resulting in reporting stale firmware
package versions.
Update the upload request to properly fetch the manifest structure from
the currently active boot partition (primary or secondary) based on
controller boot status flags, and format the complete package version
into the log.
[2 lines not shown]
mpi3mr: Safely re-validate target before unblocking I/O in IOCTL error path
When issuing task management or configuration commands to a target
device via userland IOCTL, the driver temporarily blocks host I/O to
that target. If the command fails or times out, the error unwinding path
decremented the I/O blocking counter using the originally resolved
target pointer.
However, management command timeouts can be lengthy. If the target
device was removed or deleted while the IOCTL was waiting for
completion, the original target structure could have been freed before
the command timed out. Decrementing the counter through the stale
pointer resulted in a use-after-free.
Safely re-lookup the target device by its hardware handle from the
active device list before modifying the counter. If the device was
already removed, the stale pointer dereference is safely skipped.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60335
mpi3mr: Wait for pending IOCTLs to drain completely on driver unload
During driver unload or module detach, the driver previously waited for
pending management IOCTLs to complete but capped the wait loop to a
fixed 180-second timeout. If a long-running management command (such as
firmware flashing, diagnostic dump collection, or secure erase) took
longer than 180 seconds, the detach sequence proceeded while the IOCTL
was still actively executing. This led to tearing down hardware
resources, destroying mutexes, and freeing driver memory structures
while userland was still using them, causing memory corruption.
Remove the arbitrary 180-second timeout and wait until all pending
IOCTLs have fully completed before proceeding with resource teardown.
Because all IOCTL commands have individual hardware timeouts, they are
guaranteed to complete or time out deterministically.
Reviewed by: ssaxena
Differential Revision: https://reviews.freebsd.org/D60331
mpi3mr: Fix CDB printing and reject lengths exceeding 32 bytes
The driver's CDB printing helper did not handle pointer-based CDBs
and lacked a bounds check on the command length. This caused garbage
bytes to be printed for pointer-based commands and risked buffer
over-reads if an invalid command length was supplied.
Access CDB bytes using the standard pointer helper, and reject printing
any CDB whose length exceeds 32 bytes to prevent buffer over-reads.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60330
mpi3mr: Consolidate operational queue cleanup and fix rollback leaks
Operational queue creation and deletion routines duplicated cleanup
logic across multiple error paths. This open-coded cleanup resulted in
leaked queue spinlocks, unfreed DMA memory, and leaked DMA tags without
clearing dangling pointers. In addition, when re-creating queues after a
controller reset, a failure during queue setup rolled back only the
newly attempted queues, leaving any existing queues beyond the failure
point untouched and leaked when queue arrays were freed.
Consolidate queue teardown into a common helper that unloads DMA maps,
frees allocated DMA memory, destroys and nullifies DMA tags, and
destroys queue locks cleanly. Use this helper across queue creation
error paths, queue deletion, and the overall queue configuration
rollback loop.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60328
mpi3mr: Reject changes to maximum outstanding requests across reset
The maximum number of outstanding host I/O requests is derived from the
controller's IOC facts data and is used to allocate fixed memory arrays
(such as command descriptor tables and chain SGL tracking) once during
initial driver attach. These arrays are fixed in size and are not
reallocated during controller resets.
When re-querying IOC facts after a reset or online firmware update, the
driver previously accepted the newly reported request limit without
verifying whether it matched the initial configuration. If the firmware
reported a higher request limit after a reset, subsequent command
tracking could index beyond the bounds of the pre-allocated arrays,
leading to memory corruption and kernel crashes.
Verify that the maximum host request limit remains consistent across
controller resets, rejecting the re-initialization if a mismatch is
detected.
[2 lines not shown]
mpi3mr: Fix mutex and DMA tag leaks in operational queue creation
When creating operational request and reply queues, the driver
initializes a queue spinlock before allocating the DMA tag and DMA
memory. If either the DMA tag creation or DMA memory allocation failed,
the functions returned error immediately without destroying the
initialized spinlock, and memory allocation failures also leaked the
previously created DMA tag. Furthermore, queue deletion error paths
freed DMA memory but omitted destroying the queue lock and left dangling
tag pointers.
Ensure that the queue lock is destroyed and any created DMA tag is
cleanly released on all queue creation error paths, and destroy the lock
and clear tag pointers on queue deletion.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60327
mpi3mr: Atomically initialize adapter state before publishing device node
When registering the management character device node (/dev/mpi3mrN),
the driver previously created the device node first and then assigned
its internal adapter soft state pointer. Because creating the node
publishes it immediately to devfs, userland applications or monitoring
daemons could open and poll the device before the pointer was set,
resulting in a null pointer dereference.
Use make_dev_s() to atomically attach the driver's private state to the
device node before it is published to devfs. This eliminates the race
condition and ensures the driver state is always valid when opened.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60324
mpi3mr: Replace static management adapter array with dynamic list
The driver previously tracked controller instances for management
IOCTL routing using a static array limited to 8 adapters, indexed
by a global counter. This design presented several limitations and
security issues:
1. Systems with more than 8 controllers (or multi-PF controllers where
each adapter exposes multiple Physical Functions) exceeded the fixed
array bounds, causing out-of-bounds indexing or attach failures.
2. If controllers were detached out of order, decrements to the global
counter corrupted the index mapping, resulting in subsequent IOCTLs
routing to the wrong controller or dereferencing NULL pointers.
3. The lookup lacked synchronization against concurrent detach
operations, creating a race condition where a controller could be
detached and freed while an IOCTL was actively in flight, leading to
a use-after-free.
Replace the static array with a dynamic TAILQ list protected by a
[6 lines not shown]
mpi3mr: Clear queue DMA physical address to prevent double unload
In the operational queue cleanup helper, the physical address tracking
the queue's DMA buffer was passed by value rather than by reference.
Because the caller's actual address field was never cleared after
unloading the mapping, the field retained a stale non-zero value.
If an error rollback subsequently revisited a queue that was already
torn down, the stale non-zero address caused the cleanup helper to
attempt unloading the DMA map a second time against an
already-destroyed, NULL DMA tag.
Pass the physical address field by reference and zero it immediately
upon unloading the DMA mapping, and verify that the DMA tag is valid
before initiating the unload. This prevents double-unload attempts and
ensures idempotent queue teardown during error recovery.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60329
mpi3mr: Validate command length before parsing UNMAP parameter fields
When validating SCSI UNMAP requests, the driver inspected the parameter
list length by reading byte offsets 7 and 8 of the command descriptor
block (CDB) and, depending on the controller revision, could modify and
write back aligned values into those offsets. If a malformed or
passthrough command was issued with a CDB length shorter than 10 bytes,
accessing these offsets resulted in out-of-bounds memory reads and
potential memory corruption on writes.
Validate that the command descriptor block length is at least 10 bytes
before accessing parameter length fields. Malformed commands shorter
than 10 bytes are rejected immediately with CHECK CONDITION and sense
key ILLEGAL REQUEST.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60318
mpi3mr: Prevent DMA memory leak on NVMe passthrough command timeouts
When processing userland NVMe passthrough commands, the driver allocates
DMA memory and tags for the Physical Region Page (PRP) list. Previously,
these DMA resources were only freed upon normal command completion. If a
passthrough command timed out, the PRP list remained allocated.
Subsequent NVMe commands overwritten the tracked pointers, permanently
leaking DMA memory buffers and DMA tags. Furthermore, freeing the buffer
immediately on timeout is unsafe because hardware DMA may still be
active while an asynchronous reset is pending.
Safely reclaim stale PRP list allocations on the next command invocation
once any pending controller reset has completed, and clean up any
remaining PRP DMA resources during driver unload.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60320
mpi3mr: Fix null pointer dereference during chain buffer allocation failure
During driver initialization, if memory allocation for the chain SGL
list failed, the local error cleanup path attempted to iterate over the
list and access each array element. Because the list pointer was NULL,
this error unwinding resulted in a null pointer dereference. In
addition, the driver's top-level attach failure path already handles
complete driver memory cleanup centrally.
Return failure immediately if memory allocation fails rather than
jumping to the redundant local unwinding logic, allowing the central
attach cleanup path to safely release allocated resources.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60319
mpi3mr: Add runtime bounds check for inline SCSI command buffers
When a command provides an inline CDB in a fixed 16-byte buffer, the
driver previously relied only on a debug assert to verify the CDB
length. In production kernels where debug asserts are disabled, an
inline CDB longer than 16 bytes could read past the buffer.
Add an explicit runtime check to reject any inline CDB exceeding 16
bytes. This prevents buffer over-reads in all kernel builds.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60322
mpi3mr: Unmap and free command DMA resources on driver unload
During driver unload or module detach, the driver previously failed to
destroy per-command DMA maps and the parent buffer DMA tag, leaking
busdma resources across driver reload cycles. Furthermore, active DMA
maps cannot be destroyed while loaded. Because interrupts are disabled
before memory cleanup runs, any command left outstanding retained its
loaded DMA mapping and was never returned to CAM.
Flush all outstanding I/O commands during driver detach to unload active
DMA maps and return pending requests cleanly to CAM. Then destroy each
command's DMA map and the buffer DMA tag during memory teardown,
ensuring all busdma resources are fully released.
Reviewed by: imp
Differential Revision: https://reviews.freebsd.org/D60323