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