/*
 * Copyright 2023 Sony Corporation
 */
#include <linux/delay.h>
#include <time.h>
#include <dm/lists.h>
#include <dm/device.h>
#include <dm/uclass.h>
#include <mailbox.h>

#include <common.h>
#include <utility.h>
#include <dm.h>

#define MBOX_DEV_NAME "mailbox_to_cm4"
#define MBOX_CHAN_WAIT_PMU (0x10)
#define MBOX_DATA_NOTIFY_ACOFF (0x02)


static bool is_ac_off_detected;

/**
 * Check AC off notification.
 * if return true, that means AC off is detected and PMU start AC off sequence
 * return    true: AC off,   false: AC off is not occur
 */
bool check_ac_off_detected(void)
{
	struct mbox_chan chan;
	uint8_t data[64] = {0};
	int ret;
	struct ofnode_phandle_args args;

	if (is_ac_off_detected)
		return true;

	args.args[0] = MBOX_CHAN_WAIT_PMU;
	args.args_count = 1;
	ret = mbox_get_by_dev_name(MBOX_DEV_NAME, &args, &chan);
	if (ret) {
		printf("%s %d mbox_get_by_dev_name fail ret=%d\n", __func__, __LINE__, ret);
		return false;
	}

	printf("%s %d [%lu]\n", __func__, __LINE__, get_timer(0));
	ret = mbox_recv(&chan, data, 0);
	if (ret) {
		printf("%s %d ACoff is not occur\n", __func__, __LINE__);
		return false;
	}

	if (data[0] == MBOX_DATA_NOTIFY_ACOFF) {
		printf("AC off is detected!!\n");
		is_ac_off_detected = true;
		return true;
	}

	printf("%s %d receive incorrect data from PMU data=%d\n", __func__, __LINE__, data[0]);
	return false;
}

