1 /*
2  * Copyright (c) 2017-2019, ARM Limited and Contributors. All rights reserved.
3  * Copyright (c) 2018, Icenowy Zheng <icenowy@aosc.io>
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  */
7 
8 #include <errno.h>
9 
10 #include <common/debug.h>
11 #include <drivers/allwinner/axp.h>
12 #include <drivers/allwinner/sunxi_rsb.h>
13 #include <lib/mmio.h>
14 
15 #include <sunxi_cpucfg.h>
16 #include <sunxi_def.h>
17 #include <sunxi_mmap.h>
18 #include <sunxi_private.h>
19 
20 #define AXP805_HW_ADDR	0x745
21 #define AXP805_RT_ADDR	0x3a
22 
23 static enum pmic_type {
24 	UNKNOWN,
25 	AXP805,
26 } pmic;
27 
axp_read(uint8_t reg)28 int axp_read(uint8_t reg)
29 {
30 	return rsb_read(AXP805_RT_ADDR, reg);
31 }
32 
axp_write(uint8_t reg,uint8_t val)33 int axp_write(uint8_t reg, uint8_t val)
34 {
35 	return rsb_write(AXP805_RT_ADDR, reg, val);
36 }
37 
rsb_init(void)38 static int rsb_init(void)
39 {
40 	int ret;
41 
42 	ret = rsb_init_controller();
43 	if (ret)
44 		return ret;
45 
46 	/* Switch to the recommended 3 MHz bus clock. */
47 	ret = rsb_set_bus_speed(SUNXI_OSC24M_CLK_IN_HZ, 3000000);
48 	if (ret)
49 		return ret;
50 
51 	/* Initiate an I2C transaction to switch the PMIC to RSB mode. */
52 	ret = rsb_set_device_mode(AXP20X_MODE_RSB << 16 | AXP20X_MODE_REG << 8);
53 	if (ret)
54 		return ret;
55 
56 	/* Associate the 8-bit runtime address with the 12-bit bus address. */
57 	ret = rsb_assign_runtime_address(AXP805_HW_ADDR, AXP805_RT_ADDR);
58 	if (ret)
59 		return ret;
60 
61 	return axp_check_id();
62 }
63 
sunxi_pmic_setup(uint16_t socid,const void * fdt)64 int sunxi_pmic_setup(uint16_t socid, const void *fdt)
65 {
66 	int ret;
67 
68 	INFO("PMIC: Probing AXP805 on RSB\n");
69 
70 	ret = sunxi_init_platform_r_twi(socid, true);
71 	if (ret)
72 		return ret;
73 
74 	ret = rsb_init();
75 	if (ret)
76 		return ret;
77 
78 	/* Switch the AXP805 to master/single-PMIC mode. */
79 	ret = axp_write(0xff, 0x0);
80 	if (ret)
81 		return ret;
82 
83 	pmic = AXP805;
84 	axp_setup_regulators(fdt);
85 
86 	/* Switch the PMIC back to I2C mode. */
87 	ret = axp_write(AXP20X_MODE_REG, AXP20X_MODE_I2C);
88 	if (ret)
89 		return ret;
90 
91 	return 0;
92 }
93 
sunxi_power_down(void)94 void sunxi_power_down(void)
95 {
96 	switch (pmic) {
97 	case AXP805:
98 		/* (Re-)init RSB in case the rich OS has disabled it. */
99 		sunxi_init_platform_r_twi(SUNXI_SOC_H6, true);
100 		rsb_init();
101 		axp_power_off();
102 		break;
103 	default:
104 		break;
105 	}
106 }
107 
sunxi_cpu_power_off_self(void)108 void sunxi_cpu_power_off_self(void)
109 {
110 	u_register_t mpidr = read_mpidr();
111 	unsigned int core  = MPIDR_AFFLVL0_VAL(mpidr);
112 
113 	/* Enable the CPUIDLE hardware (only really needs to be done once). */
114 	mmio_write_32(SUNXI_CPUIDLE_EN_REG, 0x16aa0000);
115 	mmio_write_32(SUNXI_CPUIDLE_EN_REG, 0xaa160001);
116 
117 	/* Trigger power off for this core. */
118 	mmio_write_32(SUNXI_CORE_CLOSE_REG, BIT_32(core));
119 }
120