Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
234 changes: 234 additions & 0 deletions default/systemd/system-sleep/thunderbolt-remove-rescan
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
#!/bin/bash
# Keep Thunderbolt and USB-C working across S3 on the 2016-2017 MacBook Pros
# (MacBookPro13,x and 14,x, Intel Alpine Ridge).
#
# The platform firmware removes power from the Thunderbolt controllers in S3
# whatever the kernel asks. After that dirty loss the switch bridges come back
# with collapsed windows, the kernel cannot re-assign them at runtime ("bridge
# window ... can't assign; no space"), pciehp removes the Thunderbolt-side xHCI
# controllers, and USB-C is dead until a power cycle. Kernel-side levers
# (d3cold_allowed, pcie_port_pm=off, pcie_ports=compat) do not help; the rails
# are the platform's.
#
# What works: remove the Thunderbolt upstream ports cleanly before sleep, so the
# chipset root ports keep their windows, and rescan after resume, so the tree
# is re-enumerated with fresh assignment. Measured on a MacBookPro14,2 over
# about thirty suspend cycles: a sleep of a minute or more brings the whole
# tree back on the first rescan; a sleep of a few seconds hands back a
# controller that never finished powering down, and the tree stays dead until
# the next sleep of a few minutes (USB 2.0 keeps working meanwhile through the
# chipset's own xHCI). The tree returns on new bus numbers below the upstream
# ports, so nothing may key on addresses below them.
#
# Design:
# - Upstream ports are found from the NHIs bound to the thunderbolt driver
# (NHI -> downstream port -> upstream port), never from fixed addresses.
# - pre: a retry unit still running from the previous resume (see post) is
# stopped first. Otherwise its next rescan could bring back the tree that
# pre is about to remove, and that tree would then go into S3 live.
# - pre: sync first. A side with a mounted filesystem or active swap reached
# through its upstream port is NOT removed (it would be torn before the
# kernel's suspend sync) and gets the dead-until-later outcome instead of
# data loss.
# - pre: S3 wake is disabled on the PCIe root ports (they share one wake line;
# nothing on them needs to wake a laptop). Not restored: the sysfs flag only
# governs system sleep, runtime hot-plug keys on the wake capability, and a
# reboot resets it.
# - pre: wait until the root ports of the removed sides report
# runtime_status=suspended (milliseconds in practice; capped at 5 s). A side
# skipped for a mount keeps its devices, so its root port may never suspend
# and is not waited on.
# - post: one rescan; if the tree is not back within 2 s, retries go to a
# transient unit via systemd-run, because post hooks run while user.slice is
# frozen and a backgrounded subshell dies with the hook
# (systemd-suspend.service is Type=oneshot with KillMode=control-group).
# "Back" means XHCI_WANT below, less one for each side pre skipped.
# - Acts only on a plain suspend into S3: systemd-sleep must be about to
# write "mem" to /sys/power/state (see suspend_state below), and
# /sys/power/mem_sleep must select deep. systemd-sleep writes mem_sleep
# before the hooks run only when MemorySleepMode= is set, otherwise the
# kernel's own selection stands. In s2idle the firmware does not cut the
# controllers' power, so removing the tree there would only drop attached
# devices, and post acts only if pre did. suspend-then-hibernate is not
# covered (Omarchy does not configure it).
# - Every path exits 0, so it can never block sleep. Journal tag:
# thunderbolt-remove-rescan. Delete this file to undo.

STATE=/run/thunderbolt-remove-rescan.roots
ACTIVE=/run/thunderbolt-remove-rescan.active # pre acted; post should too
# xHCI controllers in a full tree: the chipset's own plus one per Alpine Ridge
# controller, so 2 on the two-port 13,1 and 14,1 and 3 on the four-port models.
# A fixed number rather than the count at sleep entry, because a short sleep
# can leave the tree dead going into the next one.
if [[ $(cat /sys/class/dmi/id/product_name 2>/dev/null) =~ ^MacBookPro1[34],1$ ]]; then
XHCI_WANT=2
else
XHCI_WANT=3
fi
log() { logger -t thunderbolt-remove-rescan -- "$*"; }
xhci() { ls /sys/bus/pci/drivers/xhci_hcd 2>/dev/null | grep -c '^0000'; }

# Print "<upstream port sysfs path> <root port sysfs path>" for every
# Thunderbolt controller whose NHI is currently bound.
thunderbolt_ports() {
local nhi d up
for nhi in /sys/bus/pci/drivers/thunderbolt/0000:*; do
[[ -e $nhi ]] || continue
d=$(readlink -f "$nhi") || continue
up=$(dirname "$(dirname "$d")")
[[ -e $up/remove ]] || continue
printf '%s %s\n' "$up" "$(dirname "$up")"
done | sort -u
}
roots_from_state() { [[ -f $STATE ]] && awk '{print $2}' "$STATE" | sort -u; }
links() {
local rp s
for rp in $(roots_from_state); do
s=$(cat "$rp/current_link_speed" 2>/dev/null); printf '%s=%s ' "$(basename "$rp")" "${s:-?}"
done
}
state() { echo "xhci=$(xhci) pci=$(ls /sys/bus/pci/devices | wc -l) links: $(links)"; }

# Is block device $1 (a name under /sys/class/block) reached through PCI device
# $2 (a sysfs path)? Follows dm/md slaves, so LUKS or RAID on a USB-C disk counts.
under_port() {
local p s
p=$(readlink -f "/sys/class/block/$1" 2>/dev/null) || return 1
[[ $p == "$2"/* ]] && return 0
for s in "/sys/class/block/$1"/slaves/*; do
[[ -e $s ]] && under_port "${s##*/}" "$2" && return 0
done
return 1
}
# Print the first mounted or swap device reached through PCI device $1, if any.
mounted_under() {
local dev b
while read -r dev _; do
[[ $dev == /dev/* ]] || continue
b=$(readlink -f "$dev" 2>/dev/null) || continue
under_port "${b##*/}" "$1" && { echo "$dev"; return 0; }
done < <(cat /proc/mounts /proc/swaps 2>/dev/null)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
# /proc/mounts names one member of a multi-device btrfs; sysfs lists them all.
for b in /sys/fs/btrfs/*/devices/*; do
[[ -e $b ]] && under_port "${b##*/}" "$1" && { echo "/dev/${b##*/}"; return 0; }
done
return 1
}

# Print the state systemd-sleep will write to /sys/power/state for a suspend:
# the first SuspendState= entry the kernel supports. As in systemd's parser,
# entries accumulate across sleep.conf and its drop-ins, an empty assignment
# resets the list, and an unset list means "mem standby freeze". Only "mem"
# honors /sys/power/mem_sleep, so "freeze" is s2idle whatever mem_sleep shows.
suspend_state() {
local want s
want=$(systemd-analyze cat-config systemd/sleep.conf 2>/dev/null | awk '
/^[[:space:]]*SuspendState[[:space:]]*=/ {
v = $0; sub(/^[^=]*=[[:space:]]*/, "", v); gsub(/"/, "", v)
if (v ~ /^[[:space:]]*$/) s = ""; else s = s " " v
}
END { print s }')
for s in ${want:-mem standby freeze}; do
[[ " $(cat /sys/power/state 2>/dev/null) " == *" $s "* ]] && { echo "$s"; return 0; }
done
return 1
}

if [[ $1 != retry ]]; then
[[ $2 == suspend ]] || exit 0
case "$1" in
pre)
rm -f "$ACTIVE"
sleep_state=$(suspend_state)
mode=$(cat /sys/power/mem_sleep 2>/dev/null)
if [[ $sleep_state != mem || $mode != *'[deep]'* ]]; then
log "pre/$2: not S3 (state: ${sleep_state:-?}, mem_sleep: ${mode:-?}) - nothing to do"
exit 0
fi
;;
post)
[[ -f $ACTIVE ]] || exit 0
;;
esac
fi

case "$1" in
pre)
touch "$ACTIVE"
# A retry left from the last resume would rescan the tree back in after
# the removal below, so stop it first (see the header).
for unit in $(systemctl list-units --no-legend --plain 'thunderbolt-remove-rescan-retry-*' 2>/dev/null | awk '{print $1}'); do
if timeout 5 systemctl stop "$unit" 2>/dev/null; then
log "pre/$2: stopped pending retry $unit"
else
log "pre/$2: WARNING could not stop pending retry $unit"
fi
done
sync
thunderbolt_ports >"$STATE"
n=0; skipped=0; removed_roots=""
while read -r up rp; do
[[ -n $up ]] || continue
if m=$(mounted_under "$up"); then
log "pre/$2: WARNING $m is mounted or swapped on through $(basename "$up") - NOT removing it (USB-C on that side stays down until a later sleep; no torn filesystem)"
skipped=$((skipped + 1)); continue
fi
if echo 1 > "$up/remove" 2>/dev/null; then
n=$((n + 1)); removed_roots="$removed_roots $rp"
log "pre/$2: removed $(basename "$up") (under $(basename "$rp"))"
else
log "pre/$2: WARNING could not remove $(basename "$up")"
fi
done <"$STATE"
log "pre/$2: removed $n upstream port(s), skipped $skipped; $(state)"
echo "$skipped" > "$ACTIVE" # post counts a skipped side as not coming back
# S3 wake off on every PCIe root port (see the header); not restored.
w=""
for rp in /sys/devices/pci0000:00/0000:*; do
[[ $(cat "$rp/class" 2>/dev/null) == 0x0604* ]] || continue
echo disabled > "$rp/power/wakeup" 2>/dev/null
w="$w$(basename "$rp")=$(cat "$rp/power/wakeup" 2>/dev/null) "
done
log "pre/$2: S3 wake: $w"
# Settle: wait for the root ports of the removed sides (now childless) to
# runtime-suspend, cap 5 s. A skipped side may not suspend under its devices.
roots=$removed_roots
if [[ -n $roots ]]; then
t0=$(date +%s%N)
for ((i = 0; i < 50; i++)); do
ok=1
for rp in $roots; do [[ $(cat "$rp/power/runtime_status" 2>/dev/null) == suspended ]] || ok=0; done
(( ok )) && break
sleep 0.1
done
ms=$(( ($(date +%s%N) - t0) / 1000000 ))
if (( ok )); then log "pre/$2: settled in ${ms} ms"; else log "pre/$2: WARNING settle cap hit after ${ms} ms - continuing"; fi
fi
;;
post)
skipped=$(cat "$ACTIVE" 2>/dev/null); [[ $skipped =~ ^[0-9]+$ ]] || skipped=0
rm -f "$ACTIVE"
want=$((XHCI_WANT - skipped))
echo 1 > /sys/bus/pci/rescan 2>/dev/null || log "post/$2: WARNING rescan write failed"
for ((i = 0; i < 4; i++)); do (( $(xhci) >= want )) && break; sleep 0.5; done
if (( $(xhci) >= want )); then
log "post/$2: tree back after attempt 1 (~$((i * 500)) ms): $(state)"
else
log "post/$2: attempt 1 short after 2 s: $(state) - retrying in a transient unit"
systemd-run --quiet --no-block --collect --unit="thunderbolt-remove-rescan-retry-$(date +%s)" \
"$0" retry "$2" "$want" || log "post/$2: WARNING systemd-run failed; no further attempts"
fi
;;
retry)
want=${3:-$XHCI_WANT}
for ((a = 2; a <= 6; a++)); do
sleep 2
echo 1 > /sys/bus/pci/rescan 2>/dev/null
sleep 0.5
if (( $(xhci) >= want )); then log "post/$2: tree back after attempt $a: $(state)"; exit 0; fi
log "post/$2: attempt $a short: $(state)"
done
log "post/$2: WARNING tree NOT back after 6 attempts: $(state) - it returns after the next sleep of a few minutes"
;;
esac
exit 0
1 change: 1 addition & 0 deletions install/hardware/all.sh
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ run_logged "$OMARCHY_INSTALL/hardware/apple/fix-spi-keyboard.sh"
run_logged "$OMARCHY_INSTALL/hardware/apple/fix-suspend-nvme.sh"
run_logged "$OMARCHY_INSTALL/hardware/apple/fix-t2.sh"
run_logged "$OMARCHY_INSTALL/hardware/apple/fix-brcmfmac-supplicant.sh"
run_logged "$OMARCHY_INSTALL/hardware/apple/fix-t1-suspend.sh"

run_logged "$OMARCHY_INSTALL/hardware/lenovo/fix-yoga-pro7-bass-speakers.sh"

Expand Down
18 changes: 18 additions & 0 deletions install/hardware/apple/fix-t1-suspend.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Keep USB-C working across suspend on the 2016-2017 MacBook Pros
# (MacBookPro13,x and 14,x, Alpine Ridge Thunderbolt).
#
# One system-sleep hook, measured on a MacBookPro14,2: the firmware powers the
# Thunderbolt controllers off in S3, the kernel cannot re-allocate their bridge
# windows on resume, and USB-C is dead until a power cycle. Removing the
# upstream ports before sleep and rescanning after brings the tree back. See
# thunderbolt-remove-rescan for the details and the measured limits.
product_name="$(cat /sys/class/dmi/id/product_name 2>/dev/null || true)"

if [[ $product_name =~ MacBookPro13,[123]|MacBookPro14,[123] ]]; then
echo "Detected $product_name; installing the suspend hook for USB-C"

sudo mkdir -p /usr/lib/systemd/system-sleep
sudo install -m 0755 -o root -g root -T \
"${OMARCHY_PATH:-/usr/share/omarchy}/default/systemd/system-sleep/thunderbolt-remove-rescan" \
/usr/lib/systemd/system-sleep/thunderbolt-remove-rescan
fi
15 changes: 15 additions & 0 deletions migrations/1789242220.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
echo "Keep USB-C working across suspend on 2016-2017 MacBook Pros"

# The install-time fix only reaches machines set up after it shipped. See
# install/hardware/apple/fix-t1-suspend.sh and the hook it installs.
OMARCHY_PATH="${OMARCHY_PATH:-/usr/share/omarchy}"
product_name="$(cat /sys/class/dmi/id/product_name 2>/dev/null || true)"
[[ $product_name =~ MacBookPro13,[123]|MacBookPro14,[123] ]] || exit 0

# Installed unconditionally, so a copy the user carries is also reset to
# root:root 0755 (see 1788662350.sh for why that matters here).
sudo mkdir -p /usr/lib/systemd/system-sleep
sudo install -m 0755 -o root -g root -T \
"$OMARCHY_PATH/default/systemd/system-sleep/thunderbolt-remove-rescan" \
/usr/lib/systemd/system-sleep/thunderbolt-remove-rescan
# The hook takes effect at the next suspend; nothing to restart.