1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * Gas Gauge driver for SBS Compliant Batteries
4 *
5 * Copyright (c) 2010, NVIDIA Corporation.
6 */
7
8#include <linux/bits.h>
9#include <linux/delay.h>
10#include <linux/err.h>
11#include <linux/gpio/consumer.h>
12#include <linux/i2c.h>
13#include <linux/init.h>
14#include <linux/interrupt.h>
15#include <linux/kernel.h>
16#include <linux/module.h>
17#include <linux/property.h>
18#include <linux/of_device.h>
19#include <linux/power/sbs-battery.h>
20#include <linux/power_supply.h>
21#include <linux/slab.h>
22#include <linux/stat.h>
23
24enum {
25	REG_MANUFACTURER_DATA,
26	REG_BATTERY_MODE,
27	REG_TEMPERATURE,
28	REG_VOLTAGE,
29	REG_CURRENT_NOW,
30	REG_CURRENT_AVG,
31	REG_MAX_ERR,
32	REG_CAPACITY,
33	REG_TIME_TO_EMPTY,
34	REG_TIME_TO_FULL,
35	REG_STATUS,
36	REG_CAPACITY_LEVEL,
37	REG_CYCLE_COUNT,
38	REG_SERIAL_NUMBER,
39	REG_REMAINING_CAPACITY,
40	REG_REMAINING_CAPACITY_CHARGE,
41	REG_FULL_CHARGE_CAPACITY,
42	REG_FULL_CHARGE_CAPACITY_CHARGE,
43	REG_DESIGN_CAPACITY,
44	REG_DESIGN_CAPACITY_CHARGE,
45	REG_DESIGN_VOLTAGE_MIN,
46	REG_DESIGN_VOLTAGE_MAX,
47	REG_CHEMISTRY,
48	REG_MANUFACTURER,
49	REG_MODEL_NAME,
50	REG_CHARGE_CURRENT,
51	REG_CHARGE_VOLTAGE,
52};
53
54#define REG_ADDR_SPEC_INFO		0x1A
55#define SPEC_INFO_VERSION_MASK		GENMASK(7, 4)
56#define SPEC_INFO_VERSION_SHIFT		4
57
58#define SBS_VERSION_1_0			1
59#define SBS_VERSION_1_1			2
60#define SBS_VERSION_1_1_WITH_PEC	3
61
62#define REG_ADDR_MANUFACTURE_DATE	0x1B
63
64/* Battery Mode defines */
65#define BATTERY_MODE_OFFSET		0x03
66#define BATTERY_MODE_CAPACITY_MASK	BIT(15)
67enum sbs_capacity_mode {
68	CAPACITY_MODE_AMPS = 0,
69	CAPACITY_MODE_WATTS = BATTERY_MODE_CAPACITY_MASK
70};
71#define BATTERY_MODE_CHARGER_MASK	(1<<14)
72
73/* manufacturer access defines */
74#define MANUFACTURER_ACCESS_STATUS	0x0006
75#define MANUFACTURER_ACCESS_SLEEP	0x0011
76
77/* battery status value bits */
78#define BATTERY_INITIALIZED		0x80
79#define BATTERY_DISCHARGING		0x40
80#define BATTERY_FULL_CHARGED		0x20
81#define BATTERY_FULL_DISCHARGED		0x10
82
83/* min_value and max_value are only valid for numerical data */
84#define SBS_DATA(_psp, _addr, _min_value, _max_value) { \
85	.psp = _psp, \
86	.addr = _addr, \
87	.min_value = _min_value, \
88	.max_value = _max_value, \
89}
90
91static const struct chip_data {
92	enum power_supply_property psp;
93	u8 addr;
94	int min_value;
95	int max_value;
96} sbs_data[] = {
97	[REG_MANUFACTURER_DATA] =
98		SBS_DATA(POWER_SUPPLY_PROP_PRESENT, 0x00, 0, 65535),
99	[REG_BATTERY_MODE] =
100		SBS_DATA(-1, 0x03, 0, 65535),
101	[REG_TEMPERATURE] =
102		SBS_DATA(POWER_SUPPLY_PROP_TEMP, 0x08, 0, 65535),
103	[REG_VOLTAGE] =
104		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_NOW, 0x09, 0, 20000),
105	[REG_CURRENT_NOW] =
106		SBS_DATA(POWER_SUPPLY_PROP_CURRENT_NOW, 0x0A, -32768, 32767),
107	[REG_CURRENT_AVG] =
108		SBS_DATA(POWER_SUPPLY_PROP_CURRENT_AVG, 0x0B, -32768, 32767),
109	[REG_MAX_ERR] =
110		SBS_DATA(POWER_SUPPLY_PROP_CAPACITY_ERROR_MARGIN, 0x0c, 0, 100),
111	[REG_CAPACITY] =
112		SBS_DATA(POWER_SUPPLY_PROP_CAPACITY, 0x0D, 0, 100),
113	[REG_REMAINING_CAPACITY] =
114		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_NOW, 0x0F, 0, 65535),
115	[REG_REMAINING_CAPACITY_CHARGE] =
116		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_NOW, 0x0F, 0, 65535),
117	[REG_FULL_CHARGE_CAPACITY] =
118		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_FULL, 0x10, 0, 65535),
119	[REG_FULL_CHARGE_CAPACITY_CHARGE] =
120		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_FULL, 0x10, 0, 65535),
121	[REG_TIME_TO_EMPTY] =
122		SBS_DATA(POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, 0x12, 0, 65535),
123	[REG_TIME_TO_FULL] =
124		SBS_DATA(POWER_SUPPLY_PROP_TIME_TO_FULL_AVG, 0x13, 0, 65535),
125	[REG_CHARGE_CURRENT] =
126		SBS_DATA(POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, 0x14, 0, 65535),
127	[REG_CHARGE_VOLTAGE] =
128		SBS_DATA(POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX, 0x15, 0, 65535),
129	[REG_STATUS] =
130		SBS_DATA(POWER_SUPPLY_PROP_STATUS, 0x16, 0, 65535),
131	[REG_CAPACITY_LEVEL] =
132		SBS_DATA(POWER_SUPPLY_PROP_CAPACITY_LEVEL, 0x16, 0, 65535),
133	[REG_CYCLE_COUNT] =
134		SBS_DATA(POWER_SUPPLY_PROP_CYCLE_COUNT, 0x17, 0, 65535),
135	[REG_DESIGN_CAPACITY] =
136		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN, 0x18, 0, 65535),
137	[REG_DESIGN_CAPACITY_CHARGE] =
138		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, 0x18, 0, 65535),
139	[REG_DESIGN_VOLTAGE_MIN] =
140		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, 0x19, 0, 65535),
141	[REG_DESIGN_VOLTAGE_MAX] =
142		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, 0x19, 0, 65535),
143	[REG_SERIAL_NUMBER] =
144		SBS_DATA(POWER_SUPPLY_PROP_SERIAL_NUMBER, 0x1C, 0, 65535),
145	/* Properties of type `const char *' */
146	[REG_MANUFACTURER] =
147		SBS_DATA(POWER_SUPPLY_PROP_MANUFACTURER, 0x20, 0, 65535),
148	[REG_MODEL_NAME] =
149		SBS_DATA(POWER_SUPPLY_PROP_MODEL_NAME, 0x21, 0, 65535),
150	[REG_CHEMISTRY] =
151		SBS_DATA(POWER_SUPPLY_PROP_TECHNOLOGY, 0x22, 0, 65535)
152};
153
154static const enum power_supply_property sbs_properties[] = {
155	POWER_SUPPLY_PROP_STATUS,
156	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
157	POWER_SUPPLY_PROP_HEALTH,
158	POWER_SUPPLY_PROP_PRESENT,
159	POWER_SUPPLY_PROP_TECHNOLOGY,
160	POWER_SUPPLY_PROP_CYCLE_COUNT,
161	POWER_SUPPLY_PROP_VOLTAGE_NOW,
162	POWER_SUPPLY_PROP_CURRENT_NOW,
163	POWER_SUPPLY_PROP_CURRENT_AVG,
164	POWER_SUPPLY_PROP_CAPACITY,
165	POWER_SUPPLY_PROP_CAPACITY_ERROR_MARGIN,
166	POWER_SUPPLY_PROP_TEMP,
167	POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG,
168	POWER_SUPPLY_PROP_TIME_TO_FULL_AVG,
169	POWER_SUPPLY_PROP_SERIAL_NUMBER,
170	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
171	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
172	POWER_SUPPLY_PROP_ENERGY_NOW,
173	POWER_SUPPLY_PROP_ENERGY_FULL,
174	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
175	POWER_SUPPLY_PROP_CHARGE_NOW,
176	POWER_SUPPLY_PROP_CHARGE_FULL,
177	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
178	POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX,
179	POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX,
180	POWER_SUPPLY_PROP_MANUFACTURE_YEAR,
181	POWER_SUPPLY_PROP_MANUFACTURE_MONTH,
182	POWER_SUPPLY_PROP_MANUFACTURE_DAY,
183	/* Properties of type `const char *' */
184	POWER_SUPPLY_PROP_MANUFACTURER,
185	POWER_SUPPLY_PROP_MODEL_NAME
186};
187
188/* Supports special manufacturer commands from TI BQ20Z65 and BQ20Z75 IC. */
189#define SBS_FLAGS_TI_BQ20ZX5		BIT(0)
190
191struct sbs_info {
192	struct i2c_client		*client;
193	struct power_supply		*power_supply;
194	bool				is_present;
195	struct gpio_desc		*gpio_detect;
196	bool				charger_broadcasts;
197	int				last_state;
198	int				poll_time;
199	u32				i2c_retry_count;
200	u32				poll_retry_count;
201	struct delayed_work		work;
202	struct mutex			mode_lock;
203	u32				flags;
204};
205
206static char model_name[I2C_SMBUS_BLOCK_MAX + 1];
207static char manufacturer[I2C_SMBUS_BLOCK_MAX + 1];
208static char chemistry[I2C_SMBUS_BLOCK_MAX + 1];
209static bool force_load;
210
211static int sbs_read_word_data(struct i2c_client *client, u8 address);
212static int sbs_write_word_data(struct i2c_client *client, u8 address, u16 value);
213
214static void sbs_disable_charger_broadcasts(struct sbs_info *chip)
215{
216	int val = sbs_read_word_data(chip->client, BATTERY_MODE_OFFSET);
217	if (val < 0)
218		goto exit;
219
220	val |= BATTERY_MODE_CHARGER_MASK;
221
222	val = sbs_write_word_data(chip->client, BATTERY_MODE_OFFSET, val);
223
224exit:
225	if (val < 0)
226		dev_err(&chip->client->dev,
227			"Failed to disable charger broadcasting: %d\n", val);
228	else
229		dev_dbg(&chip->client->dev, "%s\n", __func__);
230}
231
232static int sbs_update_presence(struct sbs_info *chip, bool is_present)
233{
234	struct i2c_client *client = chip->client;
235	int retries = chip->i2c_retry_count;
236	s32 ret = 0;
237	u8 version;
238
239	if (chip->is_present == is_present)
240		return 0;
241
242	if (!is_present) {
243		chip->is_present = false;
244		/* Disable PEC when no device is present */
245		client->flags &= ~I2C_CLIENT_PEC;
246		return 0;
247	}
248
249	/* Check if device supports packet error checking and use it */
250	while (retries > 0) {
251		ret = i2c_smbus_read_word_data(client, REG_ADDR_SPEC_INFO);
252		if (ret >= 0)
253			break;
254
255		/*
256		 * Some batteries trigger the detection pin before the
257		 * I2C bus is properly connected. This works around the
258		 * issue.
259		 */
260		msleep(100);
261
262		retries--;
263	}
264
265	if (ret < 0) {
266		dev_dbg(&client->dev, "failed to read spec info: %d\n", ret);
267
268		/* fallback to old behaviour */
269		client->flags &= ~I2C_CLIENT_PEC;
270		chip->is_present = true;
271
272		return ret;
273	}
274
275	version = (ret & SPEC_INFO_VERSION_MASK) >> SPEC_INFO_VERSION_SHIFT;
276
277	if (version == SBS_VERSION_1_1_WITH_PEC)
278		client->flags |= I2C_CLIENT_PEC;
279	else
280		client->flags &= ~I2C_CLIENT_PEC;
281
282	if (of_device_is_compatible(client->dev.parent->of_node, "google,cros-ec-i2c-tunnel")
283	    && client->flags & I2C_CLIENT_PEC) {
284		dev_info(&client->dev, "Disabling PEC because of broken Cros-EC implementation\n");
285		client->flags &= ~I2C_CLIENT_PEC;
286	}
287
288	dev_dbg(&client->dev, "PEC: %s\n", (client->flags & I2C_CLIENT_PEC) ?
289		"enabled" : "disabled");
290
291	if (!chip->is_present && is_present && !chip->charger_broadcasts)
292		sbs_disable_charger_broadcasts(chip);
293
294	chip->is_present = true;
295
296	return 0;
297}
298
299static int sbs_read_word_data(struct i2c_client *client, u8 address)
300{
301	struct sbs_info *chip = i2c_get_clientdata(client);
302	int retries = chip->i2c_retry_count;
303	s32 ret = 0;
304
305	while (retries > 0) {
306		ret = i2c_smbus_read_word_data(client, address);
307		if (ret >= 0)
308			break;
309		retries--;
310	}
311
312	if (ret < 0) {
313		dev_dbg(&client->dev,
314			"%s: i2c read at address 0x%x failed\n",
315			__func__, address);
316		return ret;
317	}
318
319	return ret;
320}
321
322static int sbs_read_string_data_fallback(struct i2c_client *client, u8 address, char *values)
323{
324	struct sbs_info *chip = i2c_get_clientdata(client);
325	s32 ret = 0, block_length = 0;
326	int retries_length, retries_block;
327	u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
328
329	retries_length = chip->i2c_retry_count;
330	retries_block = chip->i2c_retry_count;
331
332	dev_warn_once(&client->dev, "I2C adapter does not support I2C_FUNC_SMBUS_READ_BLOCK_DATA.\n"
333				    "Fallback method does not support PEC.\n");
334
335	/* Adapter needs to support these two functions */
336	if (!i2c_check_functionality(client->adapter,
337				     I2C_FUNC_SMBUS_BYTE_DATA |
338				     I2C_FUNC_SMBUS_I2C_BLOCK)){
339		return -ENODEV;
340	}
341
342	/* Get the length of block data */
343	while (retries_length > 0) {
344		ret = i2c_smbus_read_byte_data(client, address);
345		if (ret >= 0)
346			break;
347		retries_length--;
348	}
349
350	if (ret < 0) {
351		dev_dbg(&client->dev,
352			"%s: i2c read at address 0x%x failed\n",
353			__func__, address);
354		return ret;
355	}
356
357	/* block_length does not include NULL terminator */
358	block_length = ret;
359	if (block_length > I2C_SMBUS_BLOCK_MAX) {
360		dev_err(&client->dev,
361			"%s: Returned block_length is longer than 0x%x\n",
362			__func__, I2C_SMBUS_BLOCK_MAX);
363		return -EINVAL;
364	}
365
366	/* Get the block data */
367	while (retries_block > 0) {
368		ret = i2c_smbus_read_i2c_block_data(
369				client, address,
370				block_length + 1, block_buffer);
371		if (ret >= 0)
372			break;
373		retries_block--;
374	}
375
376	if (ret < 0) {
377		dev_dbg(&client->dev,
378			"%s: i2c read at address 0x%x failed\n",
379			__func__, address);
380		return ret;
381	}
382
383	/* block_buffer[0] == block_length */
384	memcpy(values, block_buffer + 1, block_length);
385	values[block_length] = '\0';
386
387	return ret;
388}
389
390static int sbs_read_string_data(struct i2c_client *client, u8 address, char *values)
391{
392	struct sbs_info *chip = i2c_get_clientdata(client);
393	int retries = chip->i2c_retry_count;
394	int ret = 0;
395
396	if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BLOCK_DATA)) {
397		bool pec = client->flags & I2C_CLIENT_PEC;
398		client->flags &= ~I2C_CLIENT_PEC;
399		ret = sbs_read_string_data_fallback(client, address, values);
400		if (pec)
401			client->flags |= I2C_CLIENT_PEC;
402		return ret;
403	}
404
405	while (retries > 0) {
406		ret = i2c_smbus_read_block_data(client, address, values);
407		if (ret >= 0)
408			break;
409		retries--;
410	}
411
412	if (ret < 0) {
413		dev_dbg(&client->dev, "failed to read block 0x%x: %d\n", address, ret);
414		return ret;
415	}
416
417	/* add string termination */
418	values[ret] = '\0';
419	return ret;
420}
421
422static int sbs_write_word_data(struct i2c_client *client, u8 address,
423	u16 value)
424{
425	struct sbs_info *chip = i2c_get_clientdata(client);
426	int retries = chip->i2c_retry_count;
427	s32 ret = 0;
428
429	while (retries > 0) {
430		ret = i2c_smbus_write_word_data(client, address, value);
431		if (ret >= 0)
432			break;
433		retries--;
434	}
435
436	if (ret < 0) {
437		dev_dbg(&client->dev,
438			"%s: i2c write to address 0x%x failed\n",
439			__func__, address);
440		return ret;
441	}
442
443	return 0;
444}
445
446static int sbs_status_correct(struct i2c_client *client, int *intval)
447{
448	int ret;
449
450	ret = sbs_read_word_data(client, sbs_data[REG_CURRENT_NOW].addr);
451	if (ret < 0)
452		return ret;
453
454	ret = (s16)ret;
455
456	/* Not drawing current -> not charging (i.e. idle) */
457	if (*intval != POWER_SUPPLY_STATUS_FULL && ret == 0)
458		*intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
459
460	if (*intval == POWER_SUPPLY_STATUS_FULL) {
461		/* Drawing or providing current when full */
462		if (ret > 0)
463			*intval = POWER_SUPPLY_STATUS_CHARGING;
464		else if (ret < 0)
465			*intval = POWER_SUPPLY_STATUS_DISCHARGING;
466	}
467
468	return 0;
469}
470
471static bool sbs_bat_needs_calibration(struct i2c_client *client)
472{
473	int ret;
474
475	ret = sbs_read_word_data(client, sbs_data[REG_BATTERY_MODE].addr);
476	if (ret < 0)
477		return false;
478
479	return !!(ret & BIT(7));
480}
481
482static int sbs_get_ti_battery_presence_and_health(
483	struct i2c_client *client, enum power_supply_property psp,
484	union power_supply_propval *val)
485{
486	s32 ret;
487
488	/*
489	 * Write to ManufacturerAccess with ManufacturerAccess command
490	 * and then read the status.
491	 */
492	ret = sbs_write_word_data(client, sbs_data[REG_MANUFACTURER_DATA].addr,
493				  MANUFACTURER_ACCESS_STATUS);
494	if (ret < 0) {
495		if (psp == POWER_SUPPLY_PROP_PRESENT)
496			val->intval = 0; /* battery removed */
497		return ret;
498	}
499
500	ret = sbs_read_word_data(client, sbs_data[REG_MANUFACTURER_DATA].addr);
501	if (ret < 0) {
502		if (psp == POWER_SUPPLY_PROP_PRESENT)
503			val->intval = 0; /* battery removed */
504		return ret;
505	}
506
507	if (ret < sbs_data[REG_MANUFACTURER_DATA].min_value ||
508	    ret > sbs_data[REG_MANUFACTURER_DATA].max_value) {
509		val->intval = 0;
510		return 0;
511	}
512
513	/* Mask the upper nibble of 2nd byte and
514	 * lower byte of response then
515	 * shift the result by 8 to get status*/
516	ret &= 0x0F00;
517	ret >>= 8;
518	if (psp == POWER_SUPPLY_PROP_PRESENT) {
519		if (ret == 0x0F)
520			/* battery removed */
521			val->intval = 0;
522		else
523			val->intval = 1;
524	} else if (psp == POWER_SUPPLY_PROP_HEALTH) {
525		if (ret == 0x09)
526			val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
527		else if (ret == 0x0B)
528			val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
529		else if (ret == 0x0C)
530			val->intval = POWER_SUPPLY_HEALTH_DEAD;
531		else if (sbs_bat_needs_calibration(client))
532			val->intval = POWER_SUPPLY_HEALTH_CALIBRATION_REQUIRED;
533		else
534			val->intval = POWER_SUPPLY_HEALTH_GOOD;
535	}
536
537	return 0;
538}
539
540static int sbs_get_battery_presence_and_health(
541	struct i2c_client *client, enum power_supply_property psp,
542	union power_supply_propval *val)
543{
544	struct sbs_info *chip = i2c_get_clientdata(client);
545	int ret;
546
547	if (chip->flags & SBS_FLAGS_TI_BQ20ZX5)
548		return sbs_get_ti_battery_presence_and_health(client, psp, val);
549
550	/* Dummy command; if it succeeds, battery is present. */
551	ret = sbs_read_word_data(client, sbs_data[REG_STATUS].addr);
552
553	if (ret < 0) { /* battery not present*/
554		if (psp == POWER_SUPPLY_PROP_PRESENT) {
555			val->intval = 0;
556			return 0;
557		}
558		return ret;
559	}
560
561	if (psp == POWER_SUPPLY_PROP_PRESENT)
562		val->intval = 1; /* battery present */
563	else { /* POWER_SUPPLY_PROP_HEALTH */
564		if (sbs_bat_needs_calibration(client)) {
565			val->intval = POWER_SUPPLY_HEALTH_CALIBRATION_REQUIRED;
566		} else {
567			/* SBS spec doesn't have a general health command. */
568			val->intval = POWER_SUPPLY_HEALTH_UNKNOWN;
569		}
570	}
571
572	return 0;
573}
574
575static int sbs_get_battery_property(struct i2c_client *client,
576	int reg_offset, enum power_supply_property psp,
577	union power_supply_propval *val)
578{
579	struct sbs_info *chip = i2c_get_clientdata(client);
580	s32 ret;
581
582	ret = sbs_read_word_data(client, sbs_data[reg_offset].addr);
583	if (ret < 0)
584		return ret;
585
586	/* returned values are 16 bit */
587	if (sbs_data[reg_offset].min_value < 0)
588		ret = (s16)ret;
589
590	if (ret >= sbs_data[reg_offset].min_value &&
591	    ret <= sbs_data[reg_offset].max_value) {
592		val->intval = ret;
593		if (psp == POWER_SUPPLY_PROP_CAPACITY_LEVEL) {
594			if (!(ret & BATTERY_INITIALIZED))
595				val->intval =
596					POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
597			else if (ret & BATTERY_FULL_CHARGED)
598				val->intval =
599					POWER_SUPPLY_CAPACITY_LEVEL_FULL;
600			else if (ret & BATTERY_FULL_DISCHARGED)
601				val->intval =
602					POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
603			else
604				val->intval =
605					POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
606			return 0;
607		} else if (psp != POWER_SUPPLY_PROP_STATUS) {
608			return 0;
609		}
610
611		if (ret & BATTERY_FULL_CHARGED)
612			val->intval = POWER_SUPPLY_STATUS_FULL;
613		else if (ret & BATTERY_DISCHARGING)
614			val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
615		else
616			val->intval = POWER_SUPPLY_STATUS_CHARGING;
617
618		sbs_status_correct(client, &val->intval);
619
620		if (chip->poll_time == 0)
621			chip->last_state = val->intval;
622		else if (chip->last_state != val->intval) {
623			cancel_delayed_work_sync(&chip->work);
624			power_supply_changed(chip->power_supply);
625			chip->poll_time = 0;
626		}
627	} else {
628		if (psp == POWER_SUPPLY_PROP_STATUS)
629			val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
630		else if (psp == POWER_SUPPLY_PROP_CAPACITY)
631			/* sbs spec says that this can be >100 %
632			 * even if max value is 100 %
633			 */
634			val->intval = min(ret, 100);
635		else
636			val->intval = 0;
637	}
638
639	return 0;
640}
641
642static int sbs_get_battery_string_property(struct i2c_client *client,
643	int reg_offset, enum power_supply_property psp, char *val)
644{
645	s32 ret;
646
647	ret = sbs_read_string_data(client, sbs_data[reg_offset].addr, val);
648
649	if (ret < 0)
650		return ret;
651
652	return 0;
653}
654
655static void  sbs_unit_adjustment(struct i2c_client *client,
656	enum power_supply_property psp, union power_supply_propval *val)
657{
658#define BASE_UNIT_CONVERSION		1000
659#define BATTERY_MODE_CAP_MULT_WATT	(10 * BASE_UNIT_CONVERSION)
660#define TIME_UNIT_CONVERSION		60
661#define TEMP_KELVIN_TO_CELSIUS		2731
662	switch (psp) {
663	case POWER_SUPPLY_PROP_ENERGY_NOW:
664	case POWER_SUPPLY_PROP_ENERGY_FULL:
665	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
666		/* sbs provides energy in units of 10mWh.
667		 * Convert to µWh
668		 */
669		val->intval *= BATTERY_MODE_CAP_MULT_WATT;
670		break;
671
672	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
673	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
674	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
675	case POWER_SUPPLY_PROP_CURRENT_NOW:
676	case POWER_SUPPLY_PROP_CURRENT_AVG:
677	case POWER_SUPPLY_PROP_CHARGE_NOW:
678	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
679	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
680	case POWER_SUPPLY_PROP_CHARGE_FULL:
681	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
682		val->intval *= BASE_UNIT_CONVERSION;
683		break;
684
685	case POWER_SUPPLY_PROP_TEMP:
686		/* sbs provides battery temperature in 0.1K
687		 * so convert it to 0.1°C
688		 */
689		val->intval -= TEMP_KELVIN_TO_CELSIUS;
690		break;
691
692	case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
693	case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
694		/* sbs provides time to empty and time to full in minutes.
695		 * Convert to seconds
696		 */
697		val->intval *= TIME_UNIT_CONVERSION;
698		break;
699
700	default:
701		dev_dbg(&client->dev,
702			"%s: no need for unit conversion %d\n", __func__, psp);
703	}
704}
705
706static enum sbs_capacity_mode sbs_set_capacity_mode(struct i2c_client *client,
707	enum sbs_capacity_mode mode)
708{
709	int ret, original_val;
710
711	original_val = sbs_read_word_data(client, BATTERY_MODE_OFFSET);
712	if (original_val < 0)
713		return original_val;
714
715	if ((original_val & BATTERY_MODE_CAPACITY_MASK) == mode)
716		return mode;
717
718	if (mode == CAPACITY_MODE_AMPS)
719		ret = original_val & ~BATTERY_MODE_CAPACITY_MASK;
720	else
721		ret = original_val | BATTERY_MODE_CAPACITY_MASK;
722
723	ret = sbs_write_word_data(client, BATTERY_MODE_OFFSET, ret);
724	if (ret < 0)
725		return ret;
726
727	usleep_range(1000, 2000);
728
729	return original_val & BATTERY_MODE_CAPACITY_MASK;
730}
731
732static int sbs_get_battery_capacity(struct i2c_client *client,
733	int reg_offset, enum power_supply_property psp,
734	union power_supply_propval *val)
735{
736	s32 ret;
737	enum sbs_capacity_mode mode = CAPACITY_MODE_WATTS;
738
739	if (power_supply_is_amp_property(psp))
740		mode = CAPACITY_MODE_AMPS;
741
742	mode = sbs_set_capacity_mode(client, mode);
743	if ((int)mode < 0)
744		return mode;
745
746	ret = sbs_read_word_data(client, sbs_data[reg_offset].addr);
747	if (ret < 0)
748		return ret;
749
750	val->intval = ret;
751
752	ret = sbs_set_capacity_mode(client, mode);
753	if (ret < 0)
754		return ret;
755
756	return 0;
757}
758
759static char sbs_serial[5];
760static int sbs_get_battery_serial_number(struct i2c_client *client,
761	union power_supply_propval *val)
762{
763	int ret;
764
765	ret = sbs_read_word_data(client, sbs_data[REG_SERIAL_NUMBER].addr);
766	if (ret < 0)
767		return ret;
768
769	sprintf(sbs_serial, "%04x", ret);
770	val->strval = sbs_serial;
771
772	return 0;
773}
774
775static int sbs_get_property_index(struct i2c_client *client,
776	enum power_supply_property psp)
777{
778	int count;
779	for (count = 0; count < ARRAY_SIZE(sbs_data); count++)
780		if (psp == sbs_data[count].psp)
781			return count;
782
783	dev_warn(&client->dev,
784		"%s: Invalid Property - %d\n", __func__, psp);
785
786	return -EINVAL;
787}
788
789static int sbs_get_chemistry(struct i2c_client *client,
790		union power_supply_propval *val)
791{
792	enum power_supply_property psp = POWER_SUPPLY_PROP_TECHNOLOGY;
793	int ret;
794
795	ret = sbs_get_property_index(client, psp);
796	if (ret < 0)
797		return ret;
798
799	ret = sbs_get_battery_string_property(client, ret, psp,
800					      chemistry);
801	if (ret < 0)
802		return ret;
803
804	if (!strncasecmp(chemistry, "LION", 4))
805		val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
806	else if (!strncasecmp(chemistry, "LiP", 3))
807		val->intval = POWER_SUPPLY_TECHNOLOGY_LIPO;
808	else if (!strncasecmp(chemistry, "NiCd", 4))
809		val->intval = POWER_SUPPLY_TECHNOLOGY_NiCd;
810	else if (!strncasecmp(chemistry, "NiMH", 4))
811		val->intval = POWER_SUPPLY_TECHNOLOGY_NiMH;
812	else
813		val->intval = POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
814
815	if (val->intval == POWER_SUPPLY_TECHNOLOGY_UNKNOWN)
816		dev_warn(&client->dev, "Unknown chemistry: %s\n", chemistry);
817
818	return 0;
819}
820
821static int sbs_get_battery_manufacture_date(struct i2c_client *client,
822	enum power_supply_property psp,
823	union power_supply_propval *val)
824{
825	int ret;
826	u16 day, month, year;
827
828	ret = sbs_read_word_data(client, REG_ADDR_MANUFACTURE_DATE);
829	if (ret < 0)
830		return ret;
831
832	day   = ret   & GENMASK(4,  0);
833	month = (ret  & GENMASK(8,  5)) >> 5;
834	year  = ((ret & GENMASK(15, 9)) >> 9) + 1980;
835
836	switch (psp) {
837	case POWER_SUPPLY_PROP_MANUFACTURE_YEAR:
838		val->intval = year;
839		break;
840	case POWER_SUPPLY_PROP_MANUFACTURE_MONTH:
841		val->intval = month;
842		break;
843	case POWER_SUPPLY_PROP_MANUFACTURE_DAY:
844		val->intval = day;
845		break;
846	default:
847		return -EINVAL;
848	}
849
850	return 0;
851}
852
853static int sbs_get_property(struct power_supply *psy,
854	enum power_supply_property psp,
855	union power_supply_propval *val)
856{
857	int ret = 0;
858	struct sbs_info *chip = power_supply_get_drvdata(psy);
859	struct i2c_client *client = chip->client;
860
861	if (chip->gpio_detect) {
862		ret = gpiod_get_value_cansleep(chip->gpio_detect);
863		if (ret < 0)
864			return ret;
865		if (psp == POWER_SUPPLY_PROP_PRESENT) {
866			val->intval = ret;
867			sbs_update_presence(chip, ret);
868			return 0;
869		}
870		if (ret == 0)
871			return -ENODATA;
872	}
873
874	switch (psp) {
875	case POWER_SUPPLY_PROP_PRESENT:
876	case POWER_SUPPLY_PROP_HEALTH:
877		ret = sbs_get_battery_presence_and_health(client, psp, val);
878
879		/* this can only be true if no gpio is used */
880		if (psp == POWER_SUPPLY_PROP_PRESENT)
881			return 0;
882		break;
883
884	case POWER_SUPPLY_PROP_TECHNOLOGY:
885		ret = sbs_get_chemistry(client, val);
886		if (ret < 0)
887			break;
888
889		goto done; /* don't trigger power_supply_changed()! */
890
891	case POWER_SUPPLY_PROP_ENERGY_NOW:
892	case POWER_SUPPLY_PROP_ENERGY_FULL:
893	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
894	case POWER_SUPPLY_PROP_CHARGE_NOW:
895	case POWER_SUPPLY_PROP_CHARGE_FULL:
896	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
897		ret = sbs_get_property_index(client, psp);
898		if (ret < 0)
899			break;
900
901		/* sbs_get_battery_capacity() will change the battery mode
902		 * temporarily to read the requested attribute. Ensure we stay
903		 * in the desired mode for the duration of the attribute read.
904		 */
905		mutex_lock(&chip->mode_lock);
906		ret = sbs_get_battery_capacity(client, ret, psp, val);
907		mutex_unlock(&chip->mode_lock);
908		break;
909
910	case POWER_SUPPLY_PROP_SERIAL_NUMBER:
911		ret = sbs_get_battery_serial_number(client, val);
912		break;
913
914	case POWER_SUPPLY_PROP_STATUS:
915	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
916	case POWER_SUPPLY_PROP_CYCLE_COUNT:
917	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
918	case POWER_SUPPLY_PROP_CURRENT_NOW:
919	case POWER_SUPPLY_PROP_CURRENT_AVG:
920	case POWER_SUPPLY_PROP_TEMP:
921	case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
922	case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
923	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
924	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
925	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX:
926	case POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX:
927	case POWER_SUPPLY_PROP_CAPACITY:
928	case POWER_SUPPLY_PROP_CAPACITY_ERROR_MARGIN:
929		ret = sbs_get_property_index(client, psp);
930		if (ret < 0)
931			break;
932
933		ret = sbs_get_battery_property(client, ret, psp, val);
934		break;
935
936	case POWER_SUPPLY_PROP_MODEL_NAME:
937		ret = sbs_get_property_index(client, psp);
938		if (ret < 0)
939			break;
940
941		ret = sbs_get_battery_string_property(client, ret, psp,
942						      model_name);
943		val->strval = model_name;
944		break;
945
946	case POWER_SUPPLY_PROP_MANUFACTURER:
947		ret = sbs_get_property_index(client, psp);
948		if (ret < 0)
949			break;
950
951		ret = sbs_get_battery_string_property(client, ret, psp,
952						      manufacturer);
953		val->strval = manufacturer;
954		break;
955
956	case POWER_SUPPLY_PROP_MANUFACTURE_YEAR:
957	case POWER_SUPPLY_PROP_MANUFACTURE_MONTH:
958	case POWER_SUPPLY_PROP_MANUFACTURE_DAY:
959		ret = sbs_get_battery_manufacture_date(client, psp, val);
960		break;
961
962	default:
963		dev_err(&client->dev,
964			"%s: INVALID property\n", __func__);
965		return -EINVAL;
966	}
967
968	if (!chip->gpio_detect && chip->is_present != (ret >= 0)) {
969		bool old_present = chip->is_present;
970		union power_supply_propval val;
971		int err = sbs_get_battery_presence_and_health(
972				client, POWER_SUPPLY_PROP_PRESENT, &val);
973
974		sbs_update_presence(chip, !err && val.intval);
975
976		if (old_present != chip->is_present)
977			power_supply_changed(chip->power_supply);
978	}
979
980done:
981	if (!ret) {
982		/* Convert units to match requirements for power supply class */
983		sbs_unit_adjustment(client, psp, val);
984		dev_dbg(&client->dev,
985			"%s: property = %d, value = %x\n", __func__,
986			psp, val->intval);
987	} else if (!chip->is_present)  {
988		/* battery not present, so return NODATA for properties */
989		ret = -ENODATA;
990	}
991	return ret;
992}
993
994static void sbs_supply_changed(struct sbs_info *chip)
995{
996	struct power_supply *battery = chip->power_supply;
997	int ret;
998
999	ret = gpiod_get_value_cansleep(chip->gpio_detect);
1000	if (ret < 0)
1001		return;
1002	sbs_update_presence(chip, ret);
1003	power_supply_changed(battery);
1004}
1005
1006static irqreturn_t sbs_irq(int irq, void *devid)
1007{
1008	sbs_supply_changed(devid);
1009	return IRQ_HANDLED;
1010}
1011
1012static void sbs_alert(struct i2c_client *client, enum i2c_alert_protocol prot,
1013	unsigned int data)
1014{
1015	sbs_supply_changed(i2c_get_clientdata(client));
1016}
1017
1018static void sbs_external_power_changed(struct power_supply *psy)
1019{
1020	struct sbs_info *chip = power_supply_get_drvdata(psy);
1021
1022	/* cancel outstanding work */
1023	cancel_delayed_work_sync(&chip->work);
1024
1025	schedule_delayed_work(&chip->work, HZ);
1026	chip->poll_time = chip->poll_retry_count;
1027}
1028
1029static void sbs_delayed_work(struct work_struct *work)
1030{
1031	struct sbs_info *chip;
1032	s32 ret;
1033
1034	chip = container_of(work, struct sbs_info, work.work);
1035
1036	ret = sbs_read_word_data(chip->client, sbs_data[REG_STATUS].addr);
1037	/* if the read failed, give up on this work */
1038	if (ret < 0) {
1039		chip->poll_time = 0;
1040		return;
1041	}
1042
1043	if (ret & BATTERY_FULL_CHARGED)
1044		ret = POWER_SUPPLY_STATUS_FULL;
1045	else if (ret & BATTERY_DISCHARGING)
1046		ret = POWER_SUPPLY_STATUS_DISCHARGING;
1047	else
1048		ret = POWER_SUPPLY_STATUS_CHARGING;
1049
1050	sbs_status_correct(chip->client, &ret);
1051
1052	if (chip->last_state != ret) {
1053		chip->poll_time = 0;
1054		power_supply_changed(chip->power_supply);
1055		return;
1056	}
1057	if (chip->poll_time > 0) {
1058		schedule_delayed_work(&chip->work, HZ);
1059		chip->poll_time--;
1060		return;
1061	}
1062}
1063
1064static const struct power_supply_desc sbs_default_desc = {
1065	.type = POWER_SUPPLY_TYPE_BATTERY,
1066	.properties = sbs_properties,
1067	.num_properties = ARRAY_SIZE(sbs_properties),
1068	.get_property = sbs_get_property,
1069	.external_power_changed = sbs_external_power_changed,
1070};
1071
1072static int sbs_probe(struct i2c_client *client)
1073{
1074	struct sbs_info *chip;
1075	struct power_supply_desc *sbs_desc;
1076	struct sbs_platform_data *pdata = client->dev.platform_data;
1077	struct power_supply_config psy_cfg = {};
1078	int rc;
1079	int irq;
1080
1081	sbs_desc = devm_kmemdup(&client->dev, &sbs_default_desc,
1082			sizeof(*sbs_desc), GFP_KERNEL);
1083	if (!sbs_desc)
1084		return -ENOMEM;
1085
1086	sbs_desc->name = devm_kasprintf(&client->dev, GFP_KERNEL, "sbs-%s",
1087			dev_name(&client->dev));
1088	if (!sbs_desc->name)
1089		return -ENOMEM;
1090
1091	chip = devm_kzalloc(&client->dev, sizeof(struct sbs_info), GFP_KERNEL);
1092	if (!chip)
1093		return -ENOMEM;
1094
1095	chip->flags = (u32)(uintptr_t)device_get_match_data(&client->dev);
1096	chip->client = client;
1097	psy_cfg.of_node = client->dev.of_node;
1098	psy_cfg.drv_data = chip;
1099	chip->last_state = POWER_SUPPLY_STATUS_UNKNOWN;
1100	mutex_init(&chip->mode_lock);
1101
1102	/* use pdata if available, fall back to DT properties,
1103	 * or hardcoded defaults if not
1104	 */
1105	rc = device_property_read_u32(&client->dev, "sbs,i2c-retry-count",
1106				      &chip->i2c_retry_count);
1107	if (rc)
1108		chip->i2c_retry_count = 0;
1109
1110	rc = device_property_read_u32(&client->dev, "sbs,poll-retry-count",
1111				      &chip->poll_retry_count);
1112	if (rc)
1113		chip->poll_retry_count = 0;
1114
1115	if (pdata) {
1116		chip->poll_retry_count = pdata->poll_retry_count;
1117		chip->i2c_retry_count  = pdata->i2c_retry_count;
1118	}
1119	chip->i2c_retry_count = chip->i2c_retry_count + 1;
1120
1121	chip->charger_broadcasts = !device_property_read_bool(&client->dev,
1122					"sbs,disable-charger-broadcasts");
1123
1124	chip->gpio_detect = devm_gpiod_get_optional(&client->dev,
1125			"sbs,battery-detect", GPIOD_IN);
1126	if (IS_ERR(chip->gpio_detect)) {
1127		dev_err(&client->dev, "Failed to get gpio: %ld\n",
1128			PTR_ERR(chip->gpio_detect));
1129		return PTR_ERR(chip->gpio_detect);
1130	}
1131
1132	i2c_set_clientdata(client, chip);
1133
1134	if (!chip->gpio_detect)
1135		goto skip_gpio;
1136
1137	irq = gpiod_to_irq(chip->gpio_detect);
1138	if (irq <= 0) {
1139		dev_warn(&client->dev, "Failed to get gpio as irq: %d\n", irq);
1140		goto skip_gpio;
1141	}
1142
1143	rc = devm_request_threaded_irq(&client->dev, irq, NULL, sbs_irq,
1144		IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
1145		dev_name(&client->dev), chip);
1146	if (rc) {
1147		dev_warn(&client->dev, "Failed to request irq: %d\n", rc);
1148		goto skip_gpio;
1149	}
1150
1151skip_gpio:
1152	/*
1153	 * Before we register, we might need to make sure we can actually talk
1154	 * to the battery.
1155	 */
1156	if (!(force_load || chip->gpio_detect)) {
1157		union power_supply_propval val;
1158
1159		rc = sbs_get_battery_presence_and_health(
1160				client, POWER_SUPPLY_PROP_PRESENT, &val);
1161		if (rc < 0 || !val.intval) {
1162			dev_err(&client->dev, "Failed to get present status\n");
1163			rc = -ENODEV;
1164			goto exit_psupply;
1165		}
1166	}
1167
1168	INIT_DELAYED_WORK(&chip->work, sbs_delayed_work);
1169
1170	chip->power_supply = devm_power_supply_register(&client->dev, sbs_desc,
1171						   &psy_cfg);
1172	if (IS_ERR(chip->power_supply)) {
1173		dev_err(&client->dev,
1174			"%s: Failed to register power supply\n", __func__);
1175		rc = PTR_ERR(chip->power_supply);
1176		goto exit_psupply;
1177	}
1178
1179	dev_info(&client->dev,
1180		"%s: battery gas gauge device registered\n", client->name);
1181
1182	return 0;
1183
1184exit_psupply:
1185	return rc;
1186}
1187
1188static int sbs_remove(struct i2c_client *client)
1189{
1190	struct sbs_info *chip = i2c_get_clientdata(client);
1191
1192	cancel_delayed_work_sync(&chip->work);
1193
1194	return 0;
1195}
1196
1197#if defined CONFIG_PM_SLEEP
1198
1199static int sbs_suspend(struct device *dev)
1200{
1201	struct i2c_client *client = to_i2c_client(dev);
1202	struct sbs_info *chip = i2c_get_clientdata(client);
1203	int ret;
1204
1205	if (chip->poll_time > 0)
1206		cancel_delayed_work_sync(&chip->work);
1207
1208	if (chip->flags & SBS_FLAGS_TI_BQ20ZX5) {
1209		/* Write to manufacturer access with sleep command. */
1210		ret = sbs_write_word_data(client,
1211					  sbs_data[REG_MANUFACTURER_DATA].addr,
1212					  MANUFACTURER_ACCESS_SLEEP);
1213		if (chip->is_present && ret < 0)
1214			return ret;
1215	}
1216
1217	return 0;
1218}
1219
1220static SIMPLE_DEV_PM_OPS(sbs_pm_ops, sbs_suspend, NULL);
1221#define SBS_PM_OPS (&sbs_pm_ops)
1222
1223#else
1224#define SBS_PM_OPS NULL
1225#endif
1226
1227static const struct i2c_device_id sbs_id[] = {
1228	{ "bq20z65", 0 },
1229	{ "bq20z75", 0 },
1230	{ "sbs-battery", 1 },
1231	{}
1232};
1233MODULE_DEVICE_TABLE(i2c, sbs_id);
1234
1235static const struct of_device_id sbs_dt_ids[] = {
1236	{ .compatible = "sbs,sbs-battery" },
1237	{
1238		.compatible = "ti,bq20z65",
1239		.data = (void *)SBS_FLAGS_TI_BQ20ZX5,
1240	},
1241	{
1242		.compatible = "ti,bq20z75",
1243		.data = (void *)SBS_FLAGS_TI_BQ20ZX5,
1244	},
1245	{ }
1246};
1247MODULE_DEVICE_TABLE(of, sbs_dt_ids);
1248
1249static struct i2c_driver sbs_battery_driver = {
1250	.probe_new	= sbs_probe,
1251	.remove		= sbs_remove,
1252	.alert		= sbs_alert,
1253	.id_table	= sbs_id,
1254	.driver = {
1255		.name	= "sbs-battery",
1256		.of_match_table = sbs_dt_ids,
1257		.pm	= SBS_PM_OPS,
1258	},
1259};
1260module_i2c_driver(sbs_battery_driver);
1261
1262MODULE_DESCRIPTION("SBS battery monitor driver");
1263MODULE_LICENSE("GPL");
1264
1265module_param(force_load, bool, 0444);
1266MODULE_PARM_DESC(force_load,
1267		 "Attempt to load the driver even if no battery is connected");
1268