periphdriver_unregister() shifts the remaining entries down over the one
being removed, then writes the NULL terminator to periph_drivers[n + 1]
rather than periph_drivers[n], so the last slot is never cleared. The store
stays within the allocation, which is two entries wider than the count; what
is left behind is a stale pointer, not an overwrite. Removing the entry that
happens to be last leaves the unregistered driver there, and removing any
other one leaves a duplicate. Consumers walk the array until the NULL, not
up to nperiph_drivers.
PERIPHDRIVER_DECLARE() unregisters from MOD_UNLOAD, so any periph driver
built as a module is affected; ctl(4) is the one anybody unloads. A module
loaded at runtime is always last, so "kldload ctl; kldunload ctl; camcontrol
devlist" faults in xptplistpdrvfunc() reading the unit list head of
ctlfe_driver, which the unload has unmapped. Only that case is reachable
from userland, and that is what the test covers.
Nothing here serialises the readers. xptpdrvtraverse() and
xptplistperiphfunc() still walk periph_drivers[] with no lock while
periphdriver_register() frees the old array, and xptperiphlistmatch() still
keeps a pointer into the array as an XPT_DEV_MATCH resume cookie. That is
D62323, and it is not needed for this one.
The not-found path is left alone. Without INVARIANTS the search falls out
with n == nperiph_drivers, nothing shifts, and the count ends up disagreeing
with the array. That wants an error return, which is a different change.
tests/sys/cam/ needs PACKAGE now that it installs a file of its own.
Fixes: 94173c3c9b84 ("Add mechanism to unload CAM periph drivers.")
MFC after: 1 week
Sponsored by: Advanced Micro Devices, Inc.