#!/sbin/openrc-run
# Copyright (c) 2021 Atmark Techno,Inc.

name="emmc self-refresh initiator"
description="Data retention feature for Micron's eMMC device"

: "${use_system_time:=${USE_SYSTEM_TIME:-NO}}"

depend() {
	if yesno "$use_system_time"; then
		need localmount chronyd
	else
		need localmount
	fi
	after bootmisc
}

workaround_ax2_mmc() {
        # older firmware for Armadillo X2/IoT G4 can brick the MMC if power is lost
        # while writing to boot partitions with >= 16KB blocks: limit to 8KB if required.
        [ "$(cat "/sys/class/block/mmcblk2/device/name" 2>/dev/null)" = G1M15L ] || return
        # affected version: ECQT00HS
        [ "$(cat "/sys/class/block/mmcblk2/device/fwrev")" = 0x4543515430304853 ] || return

        echo 8 > "/sys/class/block/mmcblk2boot0/queue/max_sectors_kb"
        echo 8 > "/sys/class/block/mmcblk2boot1/queue/max_sectors_kb"
}

start() {
	if ! yesno "$use_system_time"; then
		use_system_time=""
	fi

	einfo "Starting micron-emmc-reten${use_system_time:+ with system time}"

	workaround_ax2_mmc

	local time_opt=""
	if yesno "$use_system_time"; then
		time_opt="-t"
	fi
	grep -l MMC /sys/class/block/*/device/type | awk -F/ '{print "/dev/" $5}' \
		| xargs -r emmc-sref $time_opt

	eend $? "emmc-reten service failed"
}

