1 /*
2  * Copyright (C) 2013 Samsung Electronics
3  * Piotr Wilczek <p.wilczek@samsung.com>
4  *
5  * SPDX-License-Identifier:	GPL-2.0+
6  */
7 
8 #include <common.h>
9 #include <power/pmic.h>
10 #include <power/max77693_pmic.h>
11 #include <i2c.h>
12 #include <errno.h>
13 
14 static int max77693_charger_state(struct pmic *p, int state, int current)
15 {
16 	unsigned int val;
17 
18 	if (pmic_probe(p))
19 		return -1;
20 
21 	/* unlock write capability */
22 	val = MAX77693_CHG_UNLOCK;
23 	pmic_reg_write(p, MAX77693_CHG_CNFG_06, val);
24 
25 	if (state == PMIC_CHARGER_DISABLE) {
26 		puts("Disable the charger.\n");
27 		pmic_reg_read(p, MAX77693_CHG_CNFG_00, &val);
28 		val &= ~0x01;
29 		pmic_reg_write(p, MAX77693_CHG_CNFG_00, val);
30 		return -1;
31 	}
32 
33 	if (current < CHARGER_MIN_CURRENT || current > CHARGER_MAX_CURRENT) {
34 		printf("%s: Wrong charge current: %d [mA]\n",
35 		       __func__, current);
36 		return -1;
37 	}
38 
39 	/* set charging current */
40 	pmic_reg_read(p, MAX77693_CHG_CNFG_02, &val);
41 	val &= ~MAX77693_CHG_CC;
42 	val |= current * 10 / 333;	/* 0.1A/3 steps */
43 	pmic_reg_write(p, MAX77693_CHG_CNFG_02, val);
44 
45 	/* enable charging */
46 	val = MAX77693_CHG_MODE_ON;
47 	pmic_reg_write(p, MAX77693_CHG_CNFG_00, val);
48 
49 	/* check charging current */
50 	pmic_reg_read(p, MAX77693_CHG_CNFG_02, &val);
51 	val &= 0x3f;
52 	printf("Enable the charger @ %d [mA]\n", val * 333 / 10);
53 
54 	return 0;
55 }
56 
57 static int max77693_charger_bat_present(struct pmic *p)
58 {
59 	unsigned int val;
60 
61 	if (pmic_probe(p))
62 		return -1;
63 
64 	pmic_reg_read(p, MAX77693_CHG_INT_OK, &val);
65 
66 	return !(val & MAX77693_CHG_DETBAT);
67 }
68 
69 static struct power_chrg power_chrg_pmic_ops = {
70 	.chrg_bat_present = max77693_charger_bat_present,
71 	.chrg_state = max77693_charger_state,
72 };
73 
74 int pmic_init_max77693(unsigned char bus)
75 {
76 	static const char name[] = "MAX77693_PMIC";
77 	struct pmic *p = pmic_alloc();
78 
79 	if (!p) {
80 		printf("%s: POWER allocation error!\n", __func__);
81 		return -ENOMEM;
82 	}
83 
84 	debug("Board PMIC init\n");
85 
86 	p->name = name;
87 	p->interface = PMIC_I2C;
88 	p->number_of_regs = PMIC_NUM_OF_REGS;
89 	p->hw.i2c.addr = MAX77693_PMIC_I2C_ADDR;
90 	p->hw.i2c.tx_num = 1;
91 	p->bus = bus;
92 
93 	p->chrg = &power_chrg_pmic_ops;
94 
95 	return 0;
96 }
97