1 /*
2  * Copyright (c) 2019, MediaTek Inc. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <common/debug.h>
8 #include <drivers/delay_timer.h>
9 
10 #include <pmic_wrap_init.h>
11 #include <rtc.h>
12 
13 /* RTC busy status polling interval and retry count */
14 enum {
15 	RTC_WRTGR_POLLING_DELAY_MS	= 10,
16 	RTC_WRTGR_POLLING_CNT		= 100
17 };
18 
RTC_Read(uint32_t addr)19 uint16_t RTC_Read(uint32_t addr)
20 {
21 	uint32_t rdata = 0;
22 
23 	pwrap_read((uint32_t)addr, &rdata);
24 	return (uint16_t)rdata;
25 }
26 
RTC_Write(uint32_t addr,uint16_t data)27 void RTC_Write(uint32_t addr, uint16_t data)
28 {
29 	pwrap_write((uint32_t)addr, (uint32_t)data);
30 }
31 
rtc_busy_wait(void)32 int32_t rtc_busy_wait(void)
33 {
34 	uint64_t retry = RTC_WRTGR_POLLING_CNT;
35 
36 	do {
37 		mdelay(RTC_WRTGR_POLLING_DELAY_MS);
38 		if (!(RTC_Read(RTC_BBPU) & RTC_BBPU_CBUSY))
39 			return 1;
40 		retry--;
41 	} while (retry);
42 
43 	ERROR("[RTC] rtc cbusy time out!\n");
44 	return 0;
45 }
46 
RTC_Write_Trigger(void)47 int32_t RTC_Write_Trigger(void)
48 {
49 	RTC_Write(RTC_WRTGR, 1);
50 	return rtc_busy_wait();
51 }
52 
Writeif_unlock(void)53 int32_t Writeif_unlock(void)
54 {
55 	RTC_Write(RTC_PROT, RTC_PROT_UNLOCK1);
56 	if (!RTC_Write_Trigger())
57 		return 0;
58 	RTC_Write(RTC_PROT, RTC_PROT_UNLOCK2);
59 	if (!RTC_Write_Trigger())
60 		return 0;
61 
62 	return 1;
63 }
64 
65