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/of.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 
24 enum {
25 	REG_MANUFACTURER_DATA,
26 	REG_TEMPERATURE,
27 	REG_VOLTAGE,
28 	REG_CURRENT,
29 	REG_CAPACITY,
30 	REG_TIME_TO_EMPTY,
31 	REG_TIME_TO_FULL,
32 	REG_STATUS,
33 	REG_CAPACITY_LEVEL,
34 	REG_CYCLE_COUNT,
35 	REG_SERIAL_NUMBER,
36 	REG_REMAINING_CAPACITY,
37 	REG_REMAINING_CAPACITY_CHARGE,
38 	REG_FULL_CHARGE_CAPACITY,
39 	REG_FULL_CHARGE_CAPACITY_CHARGE,
40 	REG_DESIGN_CAPACITY,
41 	REG_DESIGN_CAPACITY_CHARGE,
42 	REG_DESIGN_VOLTAGE_MIN,
43 	REG_DESIGN_VOLTAGE_MAX,
44 	REG_MANUFACTURER,
45 	REG_MODEL_NAME,
46 };
47 
48 /* Battery Mode defines */
49 #define BATTERY_MODE_OFFSET		0x03
50 #define BATTERY_MODE_CAPACITY_MASK	BIT(15)
51 enum sbs_capacity_mode {
52 	CAPACITY_MODE_AMPS = 0,
53 	CAPACITY_MODE_WATTS = BATTERY_MODE_CAPACITY_MASK
54 };
55 
56 /* manufacturer access defines */
57 #define MANUFACTURER_ACCESS_STATUS	0x0006
58 #define MANUFACTURER_ACCESS_SLEEP	0x0011
59 
60 /* battery status value bits */
61 #define BATTERY_INITIALIZED		0x80
62 #define BATTERY_DISCHARGING		0x40
63 #define BATTERY_FULL_CHARGED		0x20
64 #define BATTERY_FULL_DISCHARGED		0x10
65 
66 /* min_value and max_value are only valid for numerical data */
67 #define SBS_DATA(_psp, _addr, _min_value, _max_value) { \
68 	.psp = _psp, \
69 	.addr = _addr, \
70 	.min_value = _min_value, \
71 	.max_value = _max_value, \
72 }
73 
74 static const struct chip_data {
75 	enum power_supply_property psp;
76 	u8 addr;
77 	int min_value;
78 	int max_value;
79 } sbs_data[] = {
80 	[REG_MANUFACTURER_DATA] =
81 		SBS_DATA(POWER_SUPPLY_PROP_PRESENT, 0x00, 0, 65535),
82 	[REG_TEMPERATURE] =
83 		SBS_DATA(POWER_SUPPLY_PROP_TEMP, 0x08, 0, 65535),
84 	[REG_VOLTAGE] =
85 		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_NOW, 0x09, 0, 20000),
86 	[REG_CURRENT] =
87 		SBS_DATA(POWER_SUPPLY_PROP_CURRENT_NOW, 0x0A, -32768, 32767),
88 	[REG_CAPACITY] =
89 		SBS_DATA(POWER_SUPPLY_PROP_CAPACITY, 0x0D, 0, 100),
90 	[REG_REMAINING_CAPACITY] =
91 		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_NOW, 0x0F, 0, 65535),
92 	[REG_REMAINING_CAPACITY_CHARGE] =
93 		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_NOW, 0x0F, 0, 65535),
94 	[REG_FULL_CHARGE_CAPACITY] =
95 		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_FULL, 0x10, 0, 65535),
96 	[REG_FULL_CHARGE_CAPACITY_CHARGE] =
97 		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_FULL, 0x10, 0, 65535),
98 	[REG_TIME_TO_EMPTY] =
99 		SBS_DATA(POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG, 0x12, 0, 65535),
100 	[REG_TIME_TO_FULL] =
101 		SBS_DATA(POWER_SUPPLY_PROP_TIME_TO_FULL_AVG, 0x13, 0, 65535),
102 	[REG_STATUS] =
103 		SBS_DATA(POWER_SUPPLY_PROP_STATUS, 0x16, 0, 65535),
104 	[REG_CAPACITY_LEVEL] =
105 		SBS_DATA(POWER_SUPPLY_PROP_CAPACITY_LEVEL, 0x16, 0, 65535),
106 	[REG_CYCLE_COUNT] =
107 		SBS_DATA(POWER_SUPPLY_PROP_CYCLE_COUNT, 0x17, 0, 65535),
108 	[REG_DESIGN_CAPACITY] =
109 		SBS_DATA(POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN, 0x18, 0, 65535),
110 	[REG_DESIGN_CAPACITY_CHARGE] =
111 		SBS_DATA(POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN, 0x18, 0, 65535),
112 	[REG_DESIGN_VOLTAGE_MIN] =
113 		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN, 0x19, 0, 65535),
114 	[REG_DESIGN_VOLTAGE_MAX] =
115 		SBS_DATA(POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, 0x19, 0, 65535),
116 	[REG_SERIAL_NUMBER] =
117 		SBS_DATA(POWER_SUPPLY_PROP_SERIAL_NUMBER, 0x1C, 0, 65535),
118 	/* Properties of type `const char *' */
119 	[REG_MANUFACTURER] =
120 		SBS_DATA(POWER_SUPPLY_PROP_MANUFACTURER, 0x20, 0, 65535),
121 	[REG_MODEL_NAME] =
122 		SBS_DATA(POWER_SUPPLY_PROP_MODEL_NAME, 0x21, 0, 65535)
123 };
124 
125 static enum power_supply_property sbs_properties[] = {
126 	POWER_SUPPLY_PROP_STATUS,
127 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
128 	POWER_SUPPLY_PROP_HEALTH,
129 	POWER_SUPPLY_PROP_PRESENT,
130 	POWER_SUPPLY_PROP_TECHNOLOGY,
131 	POWER_SUPPLY_PROP_CYCLE_COUNT,
132 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
133 	POWER_SUPPLY_PROP_CURRENT_NOW,
134 	POWER_SUPPLY_PROP_CAPACITY,
135 	POWER_SUPPLY_PROP_TEMP,
136 	POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG,
137 	POWER_SUPPLY_PROP_TIME_TO_FULL_AVG,
138 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
139 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
140 	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
141 	POWER_SUPPLY_PROP_ENERGY_NOW,
142 	POWER_SUPPLY_PROP_ENERGY_FULL,
143 	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
144 	POWER_SUPPLY_PROP_CHARGE_NOW,
145 	POWER_SUPPLY_PROP_CHARGE_FULL,
146 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
147 	/* Properties of type `const char *' */
148 	POWER_SUPPLY_PROP_MANUFACTURER,
149 	POWER_SUPPLY_PROP_MODEL_NAME
150 };
151 
152 /* Supports special manufacturer commands from TI BQ20Z75 IC. */
153 #define SBS_FLAGS_TI_BQ20Z75		BIT(0)
154 
155 struct sbs_info {
156 	struct i2c_client		*client;
157 	struct power_supply		*power_supply;
158 	bool				is_present;
159 	struct gpio_desc		*gpio_detect;
160 	bool				enable_detection;
161 	int				last_state;
162 	int				poll_time;
163 	u32				i2c_retry_count;
164 	u32				poll_retry_count;
165 	struct delayed_work		work;
166 	struct mutex			mode_lock;
167 	u32				flags;
168 };
169 
170 static char model_name[I2C_SMBUS_BLOCK_MAX + 1];
171 static char manufacturer[I2C_SMBUS_BLOCK_MAX + 1];
172 static bool force_load;
173 
174 static int sbs_read_word_data(struct i2c_client *client, u8 address)
175 {
176 	struct sbs_info *chip = i2c_get_clientdata(client);
177 	int retries = chip->i2c_retry_count;
178 	s32 ret = 0;
179 
180 	while (retries > 0) {
181 		ret = i2c_smbus_read_word_data(client, address);
182 		if (ret >= 0)
183 			break;
184 		retries--;
185 	}
186 
187 	if (ret < 0) {
188 		dev_dbg(&client->dev,
189 			"%s: i2c read at address 0x%x failed\n",
190 			__func__, address);
191 		return ret;
192 	}
193 
194 	return ret;
195 }
196 
197 static int sbs_read_string_data(struct i2c_client *client, u8 address,
198 				char *values)
199 {
200 	struct sbs_info *chip = i2c_get_clientdata(client);
201 	s32 ret = 0, block_length = 0;
202 	int retries_length, retries_block;
203 	u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
204 
205 	retries_length = chip->i2c_retry_count;
206 	retries_block = chip->i2c_retry_count;
207 
208 	/* Adapter needs to support these two functions */
209 	if (!i2c_check_functionality(client->adapter,
210 				     I2C_FUNC_SMBUS_BYTE_DATA |
211 				     I2C_FUNC_SMBUS_I2C_BLOCK)){
212 		return -ENODEV;
213 	}
214 
215 	/* Get the length of block data */
216 	while (retries_length > 0) {
217 		ret = i2c_smbus_read_byte_data(client, address);
218 		if (ret >= 0)
219 			break;
220 		retries_length--;
221 	}
222 
223 	if (ret < 0) {
224 		dev_dbg(&client->dev,
225 			"%s: i2c read at address 0x%x failed\n",
226 			__func__, address);
227 		return ret;
228 	}
229 
230 	/* block_length does not include NULL terminator */
231 	block_length = ret;
232 	if (block_length > I2C_SMBUS_BLOCK_MAX) {
233 		dev_err(&client->dev,
234 			"%s: Returned block_length is longer than 0x%x\n",
235 			__func__, I2C_SMBUS_BLOCK_MAX);
236 		return -EINVAL;
237 	}
238 
239 	/* Get the block data */
240 	while (retries_block > 0) {
241 		ret = i2c_smbus_read_i2c_block_data(
242 				client, address,
243 				block_length + 1, block_buffer);
244 		if (ret >= 0)
245 			break;
246 		retries_block--;
247 	}
248 
249 	if (ret < 0) {
250 		dev_dbg(&client->dev,
251 			"%s: i2c read at address 0x%x failed\n",
252 			__func__, address);
253 		return ret;
254 	}
255 
256 	/* block_buffer[0] == block_length */
257 	memcpy(values, block_buffer + 1, block_length);
258 	values[block_length] = '\0';
259 
260 	return ret;
261 }
262 
263 static int sbs_write_word_data(struct i2c_client *client, u8 address,
264 	u16 value)
265 {
266 	struct sbs_info *chip = i2c_get_clientdata(client);
267 	int retries = chip->i2c_retry_count;
268 	s32 ret = 0;
269 
270 	while (retries > 0) {
271 		ret = i2c_smbus_write_word_data(client, address, value);
272 		if (ret >= 0)
273 			break;
274 		retries--;
275 	}
276 
277 	if (ret < 0) {
278 		dev_dbg(&client->dev,
279 			"%s: i2c write to address 0x%x failed\n",
280 			__func__, address);
281 		return ret;
282 	}
283 
284 	return 0;
285 }
286 
287 static int sbs_status_correct(struct i2c_client *client, int *intval)
288 {
289 	int ret;
290 
291 	ret = sbs_read_word_data(client, sbs_data[REG_CURRENT].addr);
292 	if (ret < 0)
293 		return ret;
294 
295 	ret = (s16)ret;
296 
297 	/* Not drawing current means full (cannot be not charging) */
298 	if (ret == 0)
299 		*intval = POWER_SUPPLY_STATUS_FULL;
300 
301 	if (*intval == POWER_SUPPLY_STATUS_FULL) {
302 		/* Drawing or providing current when full */
303 		if (ret > 0)
304 			*intval = POWER_SUPPLY_STATUS_CHARGING;
305 		else if (ret < 0)
306 			*intval = POWER_SUPPLY_STATUS_DISCHARGING;
307 	}
308 
309 	return 0;
310 }
311 
312 static int sbs_get_battery_presence_and_health(
313 	struct i2c_client *client, enum power_supply_property psp,
314 	union power_supply_propval *val)
315 {
316 	int ret;
317 
318 	/* Dummy command; if it succeeds, battery is present. */
319 	ret = sbs_read_word_data(client, sbs_data[REG_STATUS].addr);
320 
321 	if (ret < 0) { /* battery not present*/
322 		if (psp == POWER_SUPPLY_PROP_PRESENT) {
323 			val->intval = 0;
324 			return 0;
325 		}
326 		return ret;
327 	}
328 
329 	if (psp == POWER_SUPPLY_PROP_PRESENT)
330 		val->intval = 1; /* battery present */
331 	else /* POWER_SUPPLY_PROP_HEALTH */
332 		/* SBS spec doesn't have a general health command. */
333 		val->intval = POWER_SUPPLY_HEALTH_UNKNOWN;
334 
335 	return 0;
336 }
337 
338 static int sbs_get_ti_battery_presence_and_health(
339 	struct i2c_client *client, enum power_supply_property psp,
340 	union power_supply_propval *val)
341 {
342 	s32 ret;
343 
344 	/*
345 	 * Write to ManufacturerAccess with ManufacturerAccess command
346 	 * and then read the status.
347 	 */
348 	ret = sbs_write_word_data(client, sbs_data[REG_MANUFACTURER_DATA].addr,
349 				  MANUFACTURER_ACCESS_STATUS);
350 	if (ret < 0) {
351 		if (psp == POWER_SUPPLY_PROP_PRESENT)
352 			val->intval = 0; /* battery removed */
353 		return ret;
354 	}
355 
356 	ret = sbs_read_word_data(client, sbs_data[REG_MANUFACTURER_DATA].addr);
357 	if (ret < 0) {
358 		if (psp == POWER_SUPPLY_PROP_PRESENT)
359 			val->intval = 0; /* battery removed */
360 		return ret;
361 	}
362 
363 	if (ret < sbs_data[REG_MANUFACTURER_DATA].min_value ||
364 	    ret > sbs_data[REG_MANUFACTURER_DATA].max_value) {
365 		val->intval = 0;
366 		return 0;
367 	}
368 
369 	/* Mask the upper nibble of 2nd byte and
370 	 * lower byte of response then
371 	 * shift the result by 8 to get status*/
372 	ret &= 0x0F00;
373 	ret >>= 8;
374 	if (psp == POWER_SUPPLY_PROP_PRESENT) {
375 		if (ret == 0x0F)
376 			/* battery removed */
377 			val->intval = 0;
378 		else
379 			val->intval = 1;
380 	} else if (psp == POWER_SUPPLY_PROP_HEALTH) {
381 		if (ret == 0x09)
382 			val->intval = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
383 		else if (ret == 0x0B)
384 			val->intval = POWER_SUPPLY_HEALTH_OVERHEAT;
385 		else if (ret == 0x0C)
386 			val->intval = POWER_SUPPLY_HEALTH_DEAD;
387 		else
388 			val->intval = POWER_SUPPLY_HEALTH_GOOD;
389 	}
390 
391 	return 0;
392 }
393 
394 static int sbs_get_battery_property(struct i2c_client *client,
395 	int reg_offset, enum power_supply_property psp,
396 	union power_supply_propval *val)
397 {
398 	struct sbs_info *chip = i2c_get_clientdata(client);
399 	s32 ret;
400 
401 	ret = sbs_read_word_data(client, sbs_data[reg_offset].addr);
402 	if (ret < 0)
403 		return ret;
404 
405 	/* returned values are 16 bit */
406 	if (sbs_data[reg_offset].min_value < 0)
407 		ret = (s16)ret;
408 
409 	if (ret >= sbs_data[reg_offset].min_value &&
410 	    ret <= sbs_data[reg_offset].max_value) {
411 		val->intval = ret;
412 		if (psp == POWER_SUPPLY_PROP_CAPACITY_LEVEL) {
413 			if (!(ret & BATTERY_INITIALIZED))
414 				val->intval =
415 					POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
416 			else if (ret & BATTERY_FULL_CHARGED)
417 				val->intval =
418 					POWER_SUPPLY_CAPACITY_LEVEL_FULL;
419 			else if (ret & BATTERY_FULL_DISCHARGED)
420 				val->intval =
421 					POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
422 			else
423 				val->intval =
424 					POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
425 			return 0;
426 		} else if (psp != POWER_SUPPLY_PROP_STATUS) {
427 			return 0;
428 		}
429 
430 		if (ret & BATTERY_FULL_CHARGED)
431 			val->intval = POWER_SUPPLY_STATUS_FULL;
432 		else if (ret & BATTERY_DISCHARGING)
433 			val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
434 		else
435 			val->intval = POWER_SUPPLY_STATUS_CHARGING;
436 
437 		sbs_status_correct(client, &val->intval);
438 
439 		if (chip->poll_time == 0)
440 			chip->last_state = val->intval;
441 		else if (chip->last_state != val->intval) {
442 			cancel_delayed_work_sync(&chip->work);
443 			power_supply_changed(chip->power_supply);
444 			chip->poll_time = 0;
445 		}
446 	} else {
447 		if (psp == POWER_SUPPLY_PROP_STATUS)
448 			val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
449 		else if (psp == POWER_SUPPLY_PROP_CAPACITY)
450 			/* sbs spec says that this can be >100 %
451 			 * even if max value is 100 %
452 			 */
453 			val->intval = min(ret, 100);
454 		else
455 			val->intval = 0;
456 	}
457 
458 	return 0;
459 }
460 
461 static int sbs_get_battery_string_property(struct i2c_client *client,
462 	int reg_offset, enum power_supply_property psp, char *val)
463 {
464 	s32 ret;
465 
466 	ret = sbs_read_string_data(client, sbs_data[reg_offset].addr, val);
467 
468 	if (ret < 0)
469 		return ret;
470 
471 	return 0;
472 }
473 
474 static void  sbs_unit_adjustment(struct i2c_client *client,
475 	enum power_supply_property psp, union power_supply_propval *val)
476 {
477 #define BASE_UNIT_CONVERSION		1000
478 #define BATTERY_MODE_CAP_MULT_WATT	(10 * BASE_UNIT_CONVERSION)
479 #define TIME_UNIT_CONVERSION		60
480 #define TEMP_KELVIN_TO_CELSIUS		2731
481 	switch (psp) {
482 	case POWER_SUPPLY_PROP_ENERGY_NOW:
483 	case POWER_SUPPLY_PROP_ENERGY_FULL:
484 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
485 		/* sbs provides energy in units of 10mWh.
486 		 * Convert to µWh
487 		 */
488 		val->intval *= BATTERY_MODE_CAP_MULT_WATT;
489 		break;
490 
491 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
492 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
493 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
494 	case POWER_SUPPLY_PROP_CURRENT_NOW:
495 	case POWER_SUPPLY_PROP_CHARGE_NOW:
496 	case POWER_SUPPLY_PROP_CHARGE_FULL:
497 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
498 		val->intval *= BASE_UNIT_CONVERSION;
499 		break;
500 
501 	case POWER_SUPPLY_PROP_TEMP:
502 		/* sbs provides battery temperature in 0.1K
503 		 * so convert it to 0.1°C
504 		 */
505 		val->intval -= TEMP_KELVIN_TO_CELSIUS;
506 		break;
507 
508 	case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
509 	case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
510 		/* sbs provides time to empty and time to full in minutes.
511 		 * Convert to seconds
512 		 */
513 		val->intval *= TIME_UNIT_CONVERSION;
514 		break;
515 
516 	default:
517 		dev_dbg(&client->dev,
518 			"%s: no need for unit conversion %d\n", __func__, psp);
519 	}
520 }
521 
522 static enum sbs_capacity_mode sbs_set_capacity_mode(struct i2c_client *client,
523 	enum sbs_capacity_mode mode)
524 {
525 	int ret, original_val;
526 
527 	original_val = sbs_read_word_data(client, BATTERY_MODE_OFFSET);
528 	if (original_val < 0)
529 		return original_val;
530 
531 	if ((original_val & BATTERY_MODE_CAPACITY_MASK) == mode)
532 		return mode;
533 
534 	if (mode == CAPACITY_MODE_AMPS)
535 		ret = original_val & ~BATTERY_MODE_CAPACITY_MASK;
536 	else
537 		ret = original_val | BATTERY_MODE_CAPACITY_MASK;
538 
539 	ret = sbs_write_word_data(client, BATTERY_MODE_OFFSET, ret);
540 	if (ret < 0)
541 		return ret;
542 
543 	usleep_range(1000, 2000);
544 
545 	return original_val & BATTERY_MODE_CAPACITY_MASK;
546 }
547 
548 static int sbs_get_battery_capacity(struct i2c_client *client,
549 	int reg_offset, enum power_supply_property psp,
550 	union power_supply_propval *val)
551 {
552 	s32 ret;
553 	enum sbs_capacity_mode mode = CAPACITY_MODE_WATTS;
554 
555 	if (power_supply_is_amp_property(psp))
556 		mode = CAPACITY_MODE_AMPS;
557 
558 	mode = sbs_set_capacity_mode(client, mode);
559 	if ((int)mode < 0)
560 		return mode;
561 
562 	ret = sbs_read_word_data(client, sbs_data[reg_offset].addr);
563 	if (ret < 0)
564 		return ret;
565 
566 	val->intval = ret;
567 
568 	ret = sbs_set_capacity_mode(client, mode);
569 	if (ret < 0)
570 		return ret;
571 
572 	return 0;
573 }
574 
575 static char sbs_serial[5];
576 static int sbs_get_battery_serial_number(struct i2c_client *client,
577 	union power_supply_propval *val)
578 {
579 	int ret;
580 
581 	ret = sbs_read_word_data(client, sbs_data[REG_SERIAL_NUMBER].addr);
582 	if (ret < 0)
583 		return ret;
584 
585 	sprintf(sbs_serial, "%04x", ret);
586 	val->strval = sbs_serial;
587 
588 	return 0;
589 }
590 
591 static int sbs_get_property_index(struct i2c_client *client,
592 	enum power_supply_property psp)
593 {
594 	int count;
595 	for (count = 0; count < ARRAY_SIZE(sbs_data); count++)
596 		if (psp == sbs_data[count].psp)
597 			return count;
598 
599 	dev_warn(&client->dev,
600 		"%s: Invalid Property - %d\n", __func__, psp);
601 
602 	return -EINVAL;
603 }
604 
605 static int sbs_get_property(struct power_supply *psy,
606 	enum power_supply_property psp,
607 	union power_supply_propval *val)
608 {
609 	int ret = 0;
610 	struct sbs_info *chip = power_supply_get_drvdata(psy);
611 	struct i2c_client *client = chip->client;
612 
613 	if (chip->gpio_detect) {
614 		ret = gpiod_get_value_cansleep(chip->gpio_detect);
615 		if (ret < 0)
616 			return ret;
617 		if (psp == POWER_SUPPLY_PROP_PRESENT) {
618 			val->intval = ret;
619 			chip->is_present = val->intval;
620 			return 0;
621 		}
622 		if (ret == 0)
623 			return -ENODATA;
624 	}
625 
626 	switch (psp) {
627 	case POWER_SUPPLY_PROP_PRESENT:
628 	case POWER_SUPPLY_PROP_HEALTH:
629 		if (chip->flags & SBS_FLAGS_TI_BQ20Z75)
630 			ret = sbs_get_ti_battery_presence_and_health(client,
631 								     psp, val);
632 		else
633 			ret = sbs_get_battery_presence_and_health(client, psp,
634 								  val);
635 
636 		/* this can only be true if no gpio is used */
637 		if (psp == POWER_SUPPLY_PROP_PRESENT)
638 			return 0;
639 		break;
640 
641 	case POWER_SUPPLY_PROP_TECHNOLOGY:
642 		val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
643 		goto done; /* don't trigger power_supply_changed()! */
644 
645 	case POWER_SUPPLY_PROP_ENERGY_NOW:
646 	case POWER_SUPPLY_PROP_ENERGY_FULL:
647 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
648 	case POWER_SUPPLY_PROP_CHARGE_NOW:
649 	case POWER_SUPPLY_PROP_CHARGE_FULL:
650 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
651 		ret = sbs_get_property_index(client, psp);
652 		if (ret < 0)
653 			break;
654 
655 		/* sbs_get_battery_capacity() will change the battery mode
656 		 * temporarily to read the requested attribute. Ensure we stay
657 		 * in the desired mode for the duration of the attribute read.
658 		 */
659 		mutex_lock(&chip->mode_lock);
660 		ret = sbs_get_battery_capacity(client, ret, psp, val);
661 		mutex_unlock(&chip->mode_lock);
662 		break;
663 
664 	case POWER_SUPPLY_PROP_SERIAL_NUMBER:
665 		ret = sbs_get_battery_serial_number(client, val);
666 		break;
667 
668 	case POWER_SUPPLY_PROP_STATUS:
669 	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
670 	case POWER_SUPPLY_PROP_CYCLE_COUNT:
671 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
672 	case POWER_SUPPLY_PROP_CURRENT_NOW:
673 	case POWER_SUPPLY_PROP_TEMP:
674 	case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
675 	case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
676 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
677 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
678 	case POWER_SUPPLY_PROP_CAPACITY:
679 		ret = sbs_get_property_index(client, psp);
680 		if (ret < 0)
681 			break;
682 
683 		ret = sbs_get_battery_property(client, ret, psp, val);
684 		break;
685 
686 	case POWER_SUPPLY_PROP_MODEL_NAME:
687 		ret = sbs_get_property_index(client, psp);
688 		if (ret < 0)
689 			break;
690 
691 		ret = sbs_get_battery_string_property(client, ret, psp,
692 						      model_name);
693 		val->strval = model_name;
694 		break;
695 
696 	case POWER_SUPPLY_PROP_MANUFACTURER:
697 		ret = sbs_get_property_index(client, psp);
698 		if (ret < 0)
699 			break;
700 
701 		ret = sbs_get_battery_string_property(client, ret, psp,
702 						      manufacturer);
703 		val->strval = manufacturer;
704 		break;
705 
706 	default:
707 		dev_err(&client->dev,
708 			"%s: INVALID property\n", __func__);
709 		return -EINVAL;
710 	}
711 
712 	if (!chip->enable_detection)
713 		goto done;
714 
715 	if (!chip->gpio_detect &&
716 		chip->is_present != (ret >= 0)) {
717 		chip->is_present = (ret >= 0);
718 		power_supply_changed(chip->power_supply);
719 	}
720 
721 done:
722 	if (!ret) {
723 		/* Convert units to match requirements for power supply class */
724 		sbs_unit_adjustment(client, psp, val);
725 	}
726 
727 	dev_dbg(&client->dev,
728 		"%s: property = %d, value = %x\n", __func__, psp, val->intval);
729 
730 	if (ret && chip->is_present)
731 		return ret;
732 
733 	/* battery not present, so return NODATA for properties */
734 	if (ret)
735 		return -ENODATA;
736 
737 	return 0;
738 }
739 
740 static void sbs_supply_changed(struct sbs_info *chip)
741 {
742 	struct power_supply *battery = chip->power_supply;
743 	int ret;
744 
745 	ret = gpiod_get_value_cansleep(chip->gpio_detect);
746 	if (ret < 0)
747 		return;
748 	chip->is_present = ret;
749 	power_supply_changed(battery);
750 }
751 
752 static irqreturn_t sbs_irq(int irq, void *devid)
753 {
754 	sbs_supply_changed(devid);
755 	return IRQ_HANDLED;
756 }
757 
758 static void sbs_alert(struct i2c_client *client, enum i2c_alert_protocol prot,
759 	unsigned int data)
760 {
761 	sbs_supply_changed(i2c_get_clientdata(client));
762 }
763 
764 static void sbs_external_power_changed(struct power_supply *psy)
765 {
766 	struct sbs_info *chip = power_supply_get_drvdata(psy);
767 
768 	/* cancel outstanding work */
769 	cancel_delayed_work_sync(&chip->work);
770 
771 	schedule_delayed_work(&chip->work, HZ);
772 	chip->poll_time = chip->poll_retry_count;
773 }
774 
775 static void sbs_delayed_work(struct work_struct *work)
776 {
777 	struct sbs_info *chip;
778 	s32 ret;
779 
780 	chip = container_of(work, struct sbs_info, work.work);
781 
782 	ret = sbs_read_word_data(chip->client, sbs_data[REG_STATUS].addr);
783 	/* if the read failed, give up on this work */
784 	if (ret < 0) {
785 		chip->poll_time = 0;
786 		return;
787 	}
788 
789 	if (ret & BATTERY_FULL_CHARGED)
790 		ret = POWER_SUPPLY_STATUS_FULL;
791 	else if (ret & BATTERY_DISCHARGING)
792 		ret = POWER_SUPPLY_STATUS_DISCHARGING;
793 	else
794 		ret = POWER_SUPPLY_STATUS_CHARGING;
795 
796 	sbs_status_correct(chip->client, &ret);
797 
798 	if (chip->last_state != ret) {
799 		chip->poll_time = 0;
800 		power_supply_changed(chip->power_supply);
801 		return;
802 	}
803 	if (chip->poll_time > 0) {
804 		schedule_delayed_work(&chip->work, HZ);
805 		chip->poll_time--;
806 		return;
807 	}
808 }
809 
810 static const struct power_supply_desc sbs_default_desc = {
811 	.type = POWER_SUPPLY_TYPE_BATTERY,
812 	.properties = sbs_properties,
813 	.num_properties = ARRAY_SIZE(sbs_properties),
814 	.get_property = sbs_get_property,
815 	.external_power_changed = sbs_external_power_changed,
816 };
817 
818 static int sbs_probe(struct i2c_client *client,
819 	const struct i2c_device_id *id)
820 {
821 	struct sbs_info *chip;
822 	struct power_supply_desc *sbs_desc;
823 	struct sbs_platform_data *pdata = client->dev.platform_data;
824 	struct power_supply_config psy_cfg = {};
825 	int rc;
826 	int irq;
827 
828 	sbs_desc = devm_kmemdup(&client->dev, &sbs_default_desc,
829 			sizeof(*sbs_desc), GFP_KERNEL);
830 	if (!sbs_desc)
831 		return -ENOMEM;
832 
833 	sbs_desc->name = devm_kasprintf(&client->dev, GFP_KERNEL, "sbs-%s",
834 			dev_name(&client->dev));
835 	if (!sbs_desc->name)
836 		return -ENOMEM;
837 
838 	chip = devm_kzalloc(&client->dev, sizeof(struct sbs_info), GFP_KERNEL);
839 	if (!chip)
840 		return -ENOMEM;
841 
842 	chip->flags = (u32)(uintptr_t)of_device_get_match_data(&client->dev);
843 	chip->client = client;
844 	chip->enable_detection = false;
845 	psy_cfg.of_node = client->dev.of_node;
846 	psy_cfg.drv_data = chip;
847 	chip->last_state = POWER_SUPPLY_STATUS_UNKNOWN;
848 	mutex_init(&chip->mode_lock);
849 
850 	/* use pdata if available, fall back to DT properties,
851 	 * or hardcoded defaults if not
852 	 */
853 	rc = of_property_read_u32(client->dev.of_node, "sbs,i2c-retry-count",
854 				  &chip->i2c_retry_count);
855 	if (rc)
856 		chip->i2c_retry_count = 0;
857 
858 	rc = of_property_read_u32(client->dev.of_node, "sbs,poll-retry-count",
859 				  &chip->poll_retry_count);
860 	if (rc)
861 		chip->poll_retry_count = 0;
862 
863 	if (pdata) {
864 		chip->poll_retry_count = pdata->poll_retry_count;
865 		chip->i2c_retry_count  = pdata->i2c_retry_count;
866 	}
867 	chip->i2c_retry_count = chip->i2c_retry_count + 1;
868 
869 	chip->gpio_detect = devm_gpiod_get_optional(&client->dev,
870 			"sbs,battery-detect", GPIOD_IN);
871 	if (IS_ERR(chip->gpio_detect)) {
872 		dev_err(&client->dev, "Failed to get gpio: %ld\n",
873 			PTR_ERR(chip->gpio_detect));
874 		return PTR_ERR(chip->gpio_detect);
875 	}
876 
877 	i2c_set_clientdata(client, chip);
878 
879 	if (!chip->gpio_detect)
880 		goto skip_gpio;
881 
882 	irq = gpiod_to_irq(chip->gpio_detect);
883 	if (irq <= 0) {
884 		dev_warn(&client->dev, "Failed to get gpio as irq: %d\n", irq);
885 		goto skip_gpio;
886 	}
887 
888 	rc = devm_request_threaded_irq(&client->dev, irq, NULL, sbs_irq,
889 		IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
890 		dev_name(&client->dev), chip);
891 	if (rc) {
892 		dev_warn(&client->dev, "Failed to request irq: %d\n", rc);
893 		goto skip_gpio;
894 	}
895 
896 skip_gpio:
897 	/*
898 	 * Before we register, we might need to make sure we can actually talk
899 	 * to the battery.
900 	 */
901 	if (!(force_load || chip->gpio_detect)) {
902 		rc = sbs_read_word_data(client, sbs_data[REG_STATUS].addr);
903 
904 		if (rc < 0) {
905 			dev_err(&client->dev, "%s: Failed to get device status\n",
906 				__func__);
907 			goto exit_psupply;
908 		}
909 	}
910 
911 	chip->power_supply = devm_power_supply_register(&client->dev, sbs_desc,
912 						   &psy_cfg);
913 	if (IS_ERR(chip->power_supply)) {
914 		dev_err(&client->dev,
915 			"%s: Failed to register power supply\n", __func__);
916 		rc = PTR_ERR(chip->power_supply);
917 		goto exit_psupply;
918 	}
919 
920 	dev_info(&client->dev,
921 		"%s: battery gas gauge device registered\n", client->name);
922 
923 	INIT_DELAYED_WORK(&chip->work, sbs_delayed_work);
924 
925 	chip->enable_detection = true;
926 
927 	return 0;
928 
929 exit_psupply:
930 	return rc;
931 }
932 
933 static int sbs_remove(struct i2c_client *client)
934 {
935 	struct sbs_info *chip = i2c_get_clientdata(client);
936 
937 	cancel_delayed_work_sync(&chip->work);
938 
939 	return 0;
940 }
941 
942 #if defined CONFIG_PM_SLEEP
943 
944 static int sbs_suspend(struct device *dev)
945 {
946 	struct i2c_client *client = to_i2c_client(dev);
947 	struct sbs_info *chip = i2c_get_clientdata(client);
948 	int ret;
949 
950 	if (chip->poll_time > 0)
951 		cancel_delayed_work_sync(&chip->work);
952 
953 	if (chip->flags & SBS_FLAGS_TI_BQ20Z75) {
954 		/* Write to manufacturer access with sleep command. */
955 		ret = sbs_write_word_data(client,
956 					  sbs_data[REG_MANUFACTURER_DATA].addr,
957 					  MANUFACTURER_ACCESS_SLEEP);
958 		if (chip->is_present && ret < 0)
959 			return ret;
960 	}
961 
962 	return 0;
963 }
964 
965 static SIMPLE_DEV_PM_OPS(sbs_pm_ops, sbs_suspend, NULL);
966 #define SBS_PM_OPS (&sbs_pm_ops)
967 
968 #else
969 #define SBS_PM_OPS NULL
970 #endif
971 
972 static const struct i2c_device_id sbs_id[] = {
973 	{ "bq20z75", 0 },
974 	{ "sbs-battery", 1 },
975 	{}
976 };
977 MODULE_DEVICE_TABLE(i2c, sbs_id);
978 
979 static const struct of_device_id sbs_dt_ids[] = {
980 	{ .compatible = "sbs,sbs-battery" },
981 	{
982 		.compatible = "ti,bq20z75",
983 		.data = (void *)SBS_FLAGS_TI_BQ20Z75,
984 	},
985 	{ }
986 };
987 MODULE_DEVICE_TABLE(of, sbs_dt_ids);
988 
989 static struct i2c_driver sbs_battery_driver = {
990 	.probe		= sbs_probe,
991 	.remove		= sbs_remove,
992 	.alert		= sbs_alert,
993 	.id_table	= sbs_id,
994 	.driver = {
995 		.name	= "sbs-battery",
996 		.of_match_table = sbs_dt_ids,
997 		.pm	= SBS_PM_OPS,
998 	},
999 };
1000 module_i2c_driver(sbs_battery_driver);
1001 
1002 MODULE_DESCRIPTION("SBS battery monitor driver");
1003 MODULE_LICENSE("GPL");
1004 
1005 module_param(force_load, bool, 0444);
1006 MODULE_PARM_DESC(force_load,
1007 		 "Attempt to load the driver even if no battery is connected");
1008