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