/*
 * Driver for the RTC in Marvell SoCs.
 *
 * Based on Linux Kernel driver.
 *
 * This file is licensed under the terms of the GNU General Public
 * License version 2.  This program is licensed "as is" without any
 * warranty of any kind, whether express or implied.
 */

#include <common.h>
#include <command.h>
#include <rtc.h>
#include <bcd.h>
#include <asm/arch/kirkwood.h>

#if defined(CONFIG_CMD_DATE)

#define RTC_TIME_REG_OFFS       0
#define RTC_SECONDS_OFFS        0
#define RTC_MINUTES_OFFS        8
#define RTC_HOURS_OFFS          16
#define RTC_WDAY_OFFS           24
#define RTC_HOURS_12H_MODE      (1 << 22) /* 12 hours mode */

#define RTC_DATE_REG_OFFS       4
#define RTC_MDAY_OFFS           0
#define RTC_MONTH_OFFS          8
#define RTC_YEAR_OFFS           16
#define KIRKWOOD_YEAR_BASE      2000

int rtc_set(struct rtc_time *tmp)
{
	ulong	rtc_reg;

	GregorianDay (tmp);

	rtc_reg = (bin2bcd(tmp->tm_sec) << RTC_SECONDS_OFFS) |
	          (bin2bcd(tmp->tm_min) << RTC_MINUTES_OFFS) |
	          (bin2bcd(tmp->tm_hour) << RTC_HOURS_OFFS) |
	          (bin2bcd(tmp->tm_wday) << RTC_WDAY_OFFS);
	writel(rtc_reg, KW_RTC_TIME);

	rtc_reg = (bin2bcd(tmp->tm_mday) << RTC_MDAY_OFFS) |
	          (bin2bcd(tmp->tm_mon) << RTC_MONTH_OFFS) |
	          (bin2bcd(tmp->tm_year - KIRKWOOD_YEAR_BASE) << RTC_YEAR_OFFS);
	writel(rtc_reg, KW_RTC_DATE);

	return 0;
}

int rtc_get(struct rtc_time *tmp)
{
	ulong	rtc_time, rtc_date;

	rtc_time = readl(KW_RTC_TIME);
	rtc_date = readl(KW_RTC_DATE);

	tmp->tm_sec = bcd2bin(rtc_time & 0x7f);
	tmp->tm_min = bcd2bin((rtc_time >> RTC_MINUTES_OFFS) & 0x7f);
	tmp->tm_hour = bcd2bin((rtc_time >> RTC_HOURS_OFFS) & 0x3f); /* assume 24 hours mode */
	tmp->tm_mday = bcd2bin(rtc_date & 0x3f);
	tmp->tm_wday = bcd2bin((rtc_time >> RTC_WDAY_OFFS) & 0x7);
	tmp->tm_mon = bcd2bin((rtc_date >> RTC_MONTH_OFFS) & 0x3f);
	/* hw counts from year 2000, but tm_year is relative to 0 */
	tmp->tm_year = bcd2bin((rtc_date >> RTC_YEAR_OFFS) & 0xff) + KIRKWOOD_YEAR_BASE;

	return 0;
}

void rtc_reset(void)
{
	return;
}

#endif /* CONFIG_CMD_DATE */
