Skip to content

Instantly share code, notes, and snippets.

@mattventura
Last active September 6, 2024 02:28
Show Gist options
  • Save mattventura/159a2a648996c2273ddff43e6b185c3f to your computer and use it in GitHub Desktop.
Save mattventura/159a2a648996c2273ddff43e6b185c3f to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
DRIVE=$1
OP=$2
# Prints usage message and exits with an error
usage() {
echo "Usage:"
echo " nvmeled.sh /dev/nvmeX <operation>"
echo " <operation> is (normal|locate|fail|eject|insert)"
exit 1
}
if [ -z "$DRIVE" ]; then
echo "No drive specified"
usage
fi
if [ -z "$OP" ]; then
echo "No operation specified"
usage
fi
# Check that the slot (as chosen by the current working directory) has the 'attention' file
check_attn() {
if [ ! -e "attention" ]; then
echo "Slot $slot does not have an 'attention' file - LED management not supported"
exit 11
fi
}
# Check that the slot (as chosen by the current working directory) has the 'power' file
check_power() {
if [ ! -e "power" ]; then
echo "Slot $slot does not have a 'power' file - insertion/removal not supported"
exit 12
fi
}
# Assuming the drive the user specified is /dev/nvme1, extract the 'nvme1' portion.
devname="${DRIVE##*/}"
cd /sys/class/nvme/${devname}/
# Find the PCI address of the drive
address=$(<address)
echo "Address: ${address}"
# move to the slots directory
cd /sys/bus/pci/slots/
# Find a slot that with a matching address
# The slot will not have the function number (e.g. drive might be 0000:16:02.00, slot will be 0000:16:02),
# so we only check that the device address starts with the slot address.
slot=""
for dir in */; do
if [ -f "${dir}address" ]; then
file_content=$(<"${dir}address")
if [[ "$address" == "$file_content"* ]]; then
slot="${dir%/}"
fi
fi
done
if [ -z "$slot" ]; then
echo "Did not find a slot corresponding to PCI address ${address}"
exit 2
fi
echo "Slot: $slot"
cd "$slot"
# Perform the operation
case "$OP" in
normal)
check_attn
echo 0 > attention
;;
fail)
check_attn
echo 1 > attention
;;
locate)
check_attn
echo 2 > attention
;;
eject)
check_power
echo 0 > power
;;
insert)
check_power
echo 1 > power
;;
*)
echo "Unknown operation: ${OP}"
usage
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment