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	# Default to a 60s timeout when waiting for a device to recover. This
57	# is an arbitrary default which can be overridden by setting the
58	# EEH_MAX_WAIT environmental variable when required.
59
60	# The current record holder for longest recovery time is:
61	#  "Adaptec Series 8 12G SAS/PCIe 3" at 39 seconds
62	max_wait=${EEH_MAX_WAIT:=60}
63
64	for i in `seq 0 ${max_wait}` ; do
65		if pe_ok $dev ; then
66			break;
67		fi
68		echo "$dev, waited $i/${max_wait}"
69		sleep 1
70	done
71
72	if ! pe_ok $dev ; then
73		echo "$dev, Failed to recover!"
74		return 1;
75	fi
76
77	echo "$dev, Recovered after $i seconds"
78	return 0;
79}
80
81