1#!/bin/bash
2
3# shellcheck source=/dev/null
4source /usr/sbin/gpio-defs.sh
5
6# Usage of this utility
7function usage() {
8	echo "Usage:"
9	echo "  ampere_power_util.sh mb [status|shutdown_ack|force_reset|soft_off]";
10}
11
12power_status() {
13	st=$(busctl get-property xyz.openbmc_project.State.Chassis /xyz/openbmc_project/state/chassis0 xyz.openbmc_project.State.Chassis CurrentPowerState | cut -d"." -f6)
14	if [ "$st" == "On\"" ]; then
15		echo "on"
16	else
17		echo "off"
18	fi
19}
20
21shutdown_ack() {
22	if [ -f "/run/openbmc/host@0-softpoweroff" ]; then
23		echo "Receive shutdown ACK triggered after softportoff the host."
24		touch /run/openbmc/host@0-softpoweroff-shutdown-ack
25	else
26		echo "Receive shutdown ACK triggered"
27		sleep 3
28		systemctl start obmc-chassis-poweroff@0.target
29	fi
30}
31
32soft_off() {
33	# Trigger shutdown_req
34	touch /run/openbmc/host@0-softpoweroff
35	gpioset -l 0 "$S0_SHD_REQ_L"=1
36	sleep 1s
37	gpioset -l 0 "$S0_SHD_REQ_L"=0
38
39	# Wait for shutdown_ack from the host in 30 seconds
40	cnt=30
41	while [ $cnt -gt 0 ];
42	do
43		# Wait for SHUTDOWN_ACK and create the host@0-softpoweroff-shutdown-ack
44		if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
45			break
46		fi
47		sleep 1
48		cnt=$((cnt - 1))
49	done
50	# Softpoweroff is successed
51	sleep 2
52	rm -rf /run/openbmc/host@0-softpoweroff
53	if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
54		rm -rf /run/openbmc/host@0-softpoweroff-shutdown-ack
55	fi
56	echo 0
57}
58
59force_reset() {
60	if [ -f "/run/openbmc/host@0-softpoweroff" ]; then
61		# In graceful host reset, after trigger os shutdown,
62		# the phosphor-state-manager will call force-warm-reset
63		# in this case the force_reset should wait for shutdown_ack from host
64		cnt=30
65		while [ $cnt -gt 0 ];
66		do
67			if [ -f "/run/openbmc/host@0-softpoweroff-shutdown-ack" ]; then
68				break
69			fi
70			echo "Waiting for shutdown-ack count down $cnt"
71			sleep 1
72			cnt=$((cnt - 1))
73		done
74		# The host OS is failed to shutdown
75		if [ $cnt == 0 ]; then
76			echo "Shutdown-ack time out after 30s."
77			exit 0
78		fi
79	fi
80	echo "Triggering sysreset pin"
81	gpioset -l 0 "$S0_SYSRESET_L"=1
82	sleep 1
83	gpioset -l 0 "$S0_SYSRESET_L"=0
84}
85
86if [ $# -lt 2 ]; then
87	echo "Total number of parameter=$#"
88	echo "Insufficient parameter"
89	usage;
90	exit 0;
91fi
92
93if [ "$1" != "mb" ]; then
94	echo "Invalid parameter1=$1"
95	usage;
96	exit 0;
97fi
98
99mkdir -p /run/openbmc/
100
101if [ "$2" == "shutdown_ack" ]; then
102	shutdown_ack
103elif [ "$2" == "status" ]; then
104	power_status
105elif [ "$2" == "force_reset" ]; then
106	force_reset
107elif [ "$2" == "soft_off" ]; then
108	ret=$(soft_off)
109	if [ "$ret" == 0 ]; then
110		echo "The host is already softoff"
111	else
112		echo "Failed to softoff the host"
113	fi
114	exit "$ret";
115else
116	echo "Invalid parameter2=$2"
117	usage;
118fi
119
120exit 0;
121