/*
 * Copyright (C) 2013 Sascha Hauer <s.hauer@pengutronix.de>
 * Copyright (C) 2015 Marc Kleine-Budde <mkl@pengutronix.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include <bootstate.h>
#include <driver.h>
#include <init.h>
#include <malloc.h>
#include <of.h>
#include <string.h>

#include <linux/err.h>

static int bootstate_probe(struct device_d *dev)
{
	struct device_node *np = dev->device_node;
	struct bootstate *bootstate;
	const char *alias;
	const char *backend_type = NULL;
	int ret;

	if (!np)
		return -EINVAL;

	alias = of_alias_get(np);
	if (!alias)
		alias = "bootstate";

	bootstate = bootstate_new_from_node(alias, np);
	if (IS_ERR(bootstate))
		return PTR_ERR(bootstate);

	of_property_read_string(np, "backend-type", &backend_type);
	if (!strcmp(backend_type, "state"))
		ret = bootstate_backend_state(bootstate, np);
	else if (!strcmp(backend_type, "nv"))
		ret = bootstate_backend_nv(bootstate);
	else
		return -EINVAL;

	return ret;
}

static __maybe_unused struct of_device_id bootstate_ids[] = {
	{
		.compatible = "barebox,bootstate",
	}, {
		/* sentinel */
	}
};

static struct driver_d bootstate_driver = {
	.name = "bootstate",
	.probe = bootstate_probe,
	.of_compatible = DRV_OF_COMPAT(bootstate_ids),
};
register_driver_macro(late,platform,bootstate_driver);
