1# Common shell utility functions 2 3# Check if PCI device is on PCI_WHITELIST and not on PCI_BLACKLIST 4# Env: 5# if PCI_WHITELIST is empty assume device is whitelistened 6# if PCI_BLACKLIST is empty assume device is NOT blacklistened 7# Params: 8# $1 - PCI BDF 9function pci_can_use() { 10 local i 11 12 # The '\ ' part is important 13 if [[ " $PCI_BLACKLIST " =~ \ $1\ ]] ; then 14 return 1 15 fi 16 17 if [[ -z "$PCI_WHITELIST" ]]; then 18 #no whitelist specified, bind all devices 19 return 0 20 fi 21 22 for i in $PCI_WHITELIST; do 23 if [ "$i" == "$1" ] ; then 24 return 0 25 fi 26 done 27 28 return 1 29} 30 31# This function will ignore PCI PCI_WHITELIST and PCI_BLACKLIST 32function iter_all_pci_class_code() { 33 local class 34 local subclass 35 local progif 36 class="$(printf %02x $((0x$1)))" 37 subclass="$(printf %02x $((0x$2)))" 38 progif="$(printf %02x $((0x$3)))" 39 40 if hash lspci &>/dev/null; then 41 if [ "$progif" != "00" ]; then 42 lspci -mm -n -D | \ 43 grep -i -- "-p${progif}" | \ 44 awk -v cc="\"${class}${subclass}\"" -F " " \ 45 '{if (cc ~ $2) print $1}' | tr -d '"' 46 else 47 lspci -mm -n -D | \ 48 awk -v cc="\"${class}${subclass}\"" -F " " \ 49 '{if (cc ~ $2) print $1}' | tr -d '"' 50 fi 51 elif hash pciconf &>/dev/null; then 52 local addr=($(pciconf -l | grep -i "class=0x${class}${subclass}${progif}" | \ 53 cut -d$'\t' -f1 | sed -e 's/^[a-zA-Z0-9_]*@pci//g' | tr ':' ' ')) 54 printf "%04x:%02x:%02x:%x\n" ${addr[0]} ${addr[1]} ${addr[2]} ${addr[3]} 55 else 56 echo "Missing PCI enumeration utility" 57 exit 1 58 fi 59} 60 61# This function will ignore PCI PCI_WHITELIST and PCI_BLACKLIST 62function iter_all_pci_dev_id() { 63 local ven_id 64 local dev_id 65 ven_id="$(printf %04x $((0x$1)))" 66 dev_id="$(printf %04x $((0x$2)))" 67 68 if hash lspci &>/dev/null; then 69 lspci -mm -n -D | awk -v ven="\"$ven_id\"" -v dev="\"${dev_id}\"" -F " " \ 70 '{if (ven ~ $3 && dev ~ $4) print $1}' | tr -d '"' 71 elif hash pciconf &>/dev/null; then 72 local addr=($(pciconf -l | grep -i "chip=0x${dev_id}${ven_id}" | \ 73 cut -d$'\t' -f1 | sed -e 's/^[a-zA-Z0-9_]*@pci//g' | tr ':' ' ')) 74 printf "%04x:%02x:%02x:%x\n" ${addr[0]} ${addr[1]} ${addr[2]} ${addr[3]} 75 else 76 echo "Missing PCI enumeration utility" 77 exit 1 78 fi 79} 80 81function iter_pci_dev_id() { 82 local bdf="" 83 84 for bdf in $(iter_all_pci_dev_id "$@"); do 85 if pci_can_use "$bdf"; then 86 echo "$bdf" 87 fi 88 done 89} 90 91# This function will filter out PCI devices using PCI_WHITELIST and PCI_BLACKLIST 92# See function pci_can_use() 93function iter_pci_class_code() { 94 local bdf="" 95 96 for bdf in $(iter_all_pci_class_code "$@"); do 97 if pci_can_use "$bdf"; then 98 echo "$bdf" 99 fi 100 done 101} 102