1#!/bin/sh
2# SPDX-License-Identifier: GPL-2.0-only
3
4pe_ok() {
5	local dev="$1"
6	local path="/sys/bus/pci/devices/$dev/eeh_pe_state"
7
8	if ! [ -e "$path" ] ; then
9		return 1;
10	fi
11
12	local fw_state="$(cut -d' ' -f1 < $path)"
13	local sw_state="$(cut -d' ' -f2 < $path)"
14
15	# If EEH_PE_ISOLATED or EEH_PE_RECOVERING are set then the PE is in an
16	# error state or being recovered. Either way, not ok.
17	if [ "$((sw_state & 0x3))" -ne 0 ] ; then
18		return 1
19	fi
20
21	# A functioning PE should have the EEH_STATE_MMIO_ACTIVE and
22	# EEH_STATE_DMA_ACTIVE flags set. For some goddamn stupid reason
23	# the platform backends set these when the PE is in reset. The
24	# RECOVERING check above should stop any false positives though.
25	if [ "$((fw_state & 0x18))" -ne "$((0x18))" ] ; then
26		return 1
27	fi
28
29	return 0;
30}
31
32eeh_supported() {
33	test -e /proc/powerpc/eeh && \
34	grep -q 'EEH Subsystem is enabled' /proc/powerpc/eeh
35}
36
37eeh_one_dev() {
38	local dev="$1"
39
40	# Using this function from the command line is sometimes useful for
41	# testing so check that the argument is a well-formed sysfs device
42	# name.
43	if ! test -e /sys/bus/pci/devices/$dev/ ; then
44		echo "Error: '$dev' must be a sysfs device name (DDDD:BB:DD.F)"
45		return 1;
46	fi
47
48	# Break it
49	echo $dev >/sys/kernel/debug/powerpc/eeh_dev_break
50
51	# Force an EEH device check. If the kernel has already
52	# noticed the EEH (due to a driver poll or whatever), this
53	# is a no-op.
54	echo $dev >/sys/kernel/debug/powerpc/eeh_dev_check
55
56	# Enforce a 30s timeout for recovery. Even the IPR, which is infamously
57	# slow to reset, should recover within 30s.
58	max_wait=30
59
60	for i in `seq 0 ${max_wait}` ; do
61		if pe_ok $dev ; then
62			break;
63		fi
64		echo "$dev, waited $i/${max_wait}"
65		sleep 1
66	done
67
68	if ! pe_ok $dev ; then
69		echo "$dev, Failed to recover!"
70		return 1;
71	fi
72
73	echo "$dev, Recovered after $i seconds"
74	return 0;
75}
76
77