1 /*
2  * (C) Copyright 2011-2013
3  * Texas Instruments, <www.ti.com>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 #include <common.h>
9 #include <i2c.h>
10 #include <power/tps65218.h>
11 
12 /**
13  *  tps65218_reg_write() - Generic function that can write a TPS65218 PMIC
14  *			   register or bit field regardless of protection
15  *			   level.
16  *
17  *  @prot_level:	   Register password protection.  Use
18  *			   TPS65218_PROT_LEVEL_NONE,
19  *			   TPS65218_PROT_LEVEL_1 or TPS65218_PROT_LEVEL_2
20  *  @dest_reg:		   Register address to write.
21  *  @dest_val:		   Value to write.
22  *  @mask:		   Bit mask (8 bits) to be applied.  Function will only
23  *			   change bits that are set in the bit mask.
24  *
25  *  @return:		   0 for success, not 0 on failure, as per the i2c API
26  */
27 int tps65218_reg_write(uchar prot_level, uchar dest_reg, uchar dest_val,
28 		       uchar mask)
29 {
30 	uchar read_val;
31 	uchar xor_reg;
32 	int ret;
33 
34 	/*
35 	 * If we are affecting only a bit field, read dest_reg and apply the
36 	 * mask
37 	 */
38 	if (mask != TPS65218_MASK_ALL_BITS) {
39 		ret = i2c_read(TPS65218_CHIP_PM, dest_reg, 1, &read_val, 1);
40 		if (ret)
41 			return ret;
42 		read_val &= (~mask);
43 		read_val |= (dest_val & mask);
44 		dest_val = read_val;
45 	}
46 
47 	if (prot_level > 0) {
48 		xor_reg = dest_reg ^ TPS65218_PASSWORD_UNLOCK;
49 		ret = i2c_write(TPS65218_CHIP_PM, TPS65218_PASSWORD, 1,
50 				&xor_reg, 1);
51 		if (ret)
52 			return ret;
53 	}
54 
55 	ret = i2c_write(TPS65218_CHIP_PM, dest_reg, 1, &dest_val, 1);
56 	if (ret)
57 		return ret;
58 
59 	if (prot_level == TPS65218_PROT_LEVEL_2) {
60 		ret = i2c_write(TPS65218_CHIP_PM, TPS65218_PASSWORD, 1,
61 				&xor_reg, 1);
62 		if (ret)
63 			return ret;
64 
65 		ret = i2c_write(TPS65218_CHIP_PM, dest_reg, 1, &dest_val, 1);
66 		if (ret)
67 			return ret;
68 	}
69 
70 	return 0;
71 }
72 
73 /**
74  * tps65218_voltage_update() - Function to change a voltage level, as this
75  *			       is a multi-step process.
76  * @dc_cntrl_reg:	       DC voltage control register to change.
77  * @volt_sel:		       New value for the voltage register
78  * @return:		       0 for success, not 0 on failure.
79  */
80 int tps65218_voltage_update(uchar dc_cntrl_reg, uchar volt_sel)
81 {
82 	if ((dc_cntrl_reg != TPS65218_DCDC1) &&
83 	    (dc_cntrl_reg != TPS65218_DCDC2))
84 		return 1;
85 
86 	/* set voltage level */
87 	if (tps65218_reg_write(TPS65218_PROT_LEVEL_2, dc_cntrl_reg, volt_sel,
88 			       TPS65218_MASK_ALL_BITS))
89 		return 1;
90 
91 	/* set GO bit to initiate voltage transition */
92 	if (tps65218_reg_write(TPS65218_PROT_LEVEL_2, TPS65218_SLEW,
93 			       TPS65218_DCDC_GO, TPS65218_DCDC_GO))
94 		return 1;
95 
96 	return 0;
97 }
98