xref: /linux/drivers/acpi/battery.c (revision 9a199794fd789c783d34281ac1acde011a7affa8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  battery.c - ACPI Battery Driver (Revision: 2.0)
4  *
5  *  Copyright (C) 2007 Alexey Starikovskiy <astarikovskiy@suse.de>
6  *  Copyright (C) 2004-2007 Vladimir Lebedev <vladimir.p.lebedev@intel.com>
7  *  Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
8  *  Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
9  */
10 
11 #define pr_fmt(fmt) "ACPI: battery: " fmt
12 
13 #include <linux/delay.h>
14 #include <linux/dmi.h>
15 #include <linux/jiffies.h>
16 #include <linux/kernel.h>
17 #include <linux/list.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/platform_device.h>
21 #include <linux/slab.h>
22 #include <linux/suspend.h>
23 #include <linux/types.h>
24 
25 #include <linux/unaligned.h>
26 
27 #include <linux/acpi.h>
28 #include <linux/power_supply.h>
29 
30 #include <acpi/battery.h>
31 
32 #define ACPI_BATTERY_VALUE_UNKNOWN 0xFFFFFFFF
33 #define ACPI_BATTERY_CAPACITY_VALID(capacity) \
34 	((capacity) != 0 && (capacity) != ACPI_BATTERY_VALUE_UNKNOWN)
35 
36 #define ACPI_BATTERY_DEVICE_NAME	"Battery"
37 
38 /* Battery power unit: 0 means mW, 1 means mA */
39 #define ACPI_BATTERY_POWER_UNIT_MA	1
40 
41 #define ACPI_BATTERY_STATE_DISCHARGING		0x1
42 #define ACPI_BATTERY_STATE_CHARGING		0x2
43 #define ACPI_BATTERY_STATE_CRITICAL		0x4
44 #define ACPI_BATTERY_STATE_CHARGE_LIMITING	0x8
45 
46 #define MAX_STRING_LENGTH	64
47 
48 MODULE_AUTHOR("Paul Diefenbaugh");
49 MODULE_AUTHOR("Alexey Starikovskiy <astarikovskiy@suse.de>");
50 MODULE_DESCRIPTION("ACPI Battery Driver");
51 MODULE_LICENSE("GPL");
52 
53 static int battery_bix_broken_package;
54 static int battery_notification_delay_ms;
55 static int battery_ac_is_broken;
56 static unsigned int cache_time = 1000;
57 module_param(cache_time, uint, 0644);
58 MODULE_PARM_DESC(cache_time, "cache time in milliseconds");
59 
60 static const struct acpi_device_id battery_device_ids[] = {
61 	{"PNP0C0A", 0},
62 
63 	/* Microsoft Surface Go 3 */
64 	{"MSHW0146", 0},
65 
66 	{"", 0},
67 };
68 
69 MODULE_DEVICE_TABLE(acpi, battery_device_ids);
70 
71 enum {
72 	ACPI_BATTERY_ALARM_PRESENT,
73 	ACPI_BATTERY_XINFO_PRESENT,
74 	ACPI_BATTERY_QUIRK_PERCENTAGE_CAPACITY,
75 	/* On Lenovo Thinkpad models from 2010 and 2011, the power unit
76 	 * switches between mWh and mAh depending on whether the system
77 	 * is running on battery or not.  When mAh is the unit, most
78 	 * reported values are incorrect and need to be adjusted by
79 	 * 10000/design_voltage.  Verified on x201, t410, t410s, and x220.
80 	 * Pre-2010 and 2012 models appear to always report in mWh and
81 	 * are thus unaffected (tested with t42, t61, t500, x200, x300,
82 	 * and x230).  Also, in mid-2012 Lenovo issued a BIOS update for
83 	 *  the 2011 models that fixes the issue (tested on x220 with a
84 	 * post-1.29 BIOS), but as of Nov. 2012, no such update is
85 	 * available for the 2010 models.
86 	 */
87 	ACPI_BATTERY_QUIRK_THINKPAD_MAH,
88 	/* for batteries reporting current capacity with design capacity
89 	 * on a full charge, but showing degradation in full charge cap.
90 	 */
91 	ACPI_BATTERY_QUIRK_DEGRADED_FULL_CHARGE,
92 };
93 
94 struct acpi_battery {
95 	struct mutex update_lock;
96 	struct power_supply *bat;
97 	struct power_supply_desc bat_desc;
98 	struct acpi_device *device;
99 	struct notifier_block pm_nb;
100 	struct list_head list;
101 	unsigned long update_time;
102 	int revision;
103 	int rate_now;
104 	int capacity_now;
105 	int voltage_now;
106 	int design_capacity;
107 	int full_charge_capacity;
108 	int technology;
109 	int design_voltage;
110 	int design_capacity_warning;
111 	int design_capacity_low;
112 	int cycle_count;
113 	int measurement_accuracy;
114 	int max_sampling_time;
115 	int min_sampling_time;
116 	int max_averaging_interval;
117 	int min_averaging_interval;
118 	int capacity_granularity_1;
119 	int capacity_granularity_2;
120 	int alarm;
121 	char model_number[MAX_STRING_LENGTH];
122 	char serial_number[MAX_STRING_LENGTH];
123 	char type[MAX_STRING_LENGTH];
124 	char oem_info[MAX_STRING_LENGTH];
125 	int state;
126 	int power_unit;
127 	unsigned long flags;
128 };
129 
130 #define to_acpi_battery(x) power_supply_get_drvdata(x)
131 
acpi_battery_present(struct acpi_battery * battery)132 static inline int acpi_battery_present(struct acpi_battery *battery)
133 {
134 	return battery->device->status.battery_present;
135 }
136 
acpi_battery_technology(struct acpi_battery * battery)137 static int acpi_battery_technology(struct acpi_battery *battery)
138 {
139 	if (!strcasecmp("NiCd", battery->type))
140 		return POWER_SUPPLY_TECHNOLOGY_NiCd;
141 	if (!strcasecmp("NiMH", battery->type))
142 		return POWER_SUPPLY_TECHNOLOGY_NiMH;
143 	if (!strcasecmp("LION", battery->type))
144 		return POWER_SUPPLY_TECHNOLOGY_LION;
145 	if (!strncasecmp("LI-ION", battery->type, 6))
146 		return POWER_SUPPLY_TECHNOLOGY_LION;
147 	if (!strcasecmp("LiP", battery->type))
148 		return POWER_SUPPLY_TECHNOLOGY_LIPO;
149 	return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
150 }
151 
152 static int acpi_battery_get_state(struct acpi_battery *battery);
153 
acpi_battery_is_charged(struct acpi_battery * battery)154 static int acpi_battery_is_charged(struct acpi_battery *battery)
155 {
156 	/* charging, discharging, critical low or charge limited */
157 	if (battery->state != 0)
158 		return 0;
159 
160 	/* battery not reporting charge */
161 	if (battery->capacity_now == ACPI_BATTERY_VALUE_UNKNOWN ||
162 	    battery->capacity_now == 0)
163 		return 0;
164 
165 	/* good batteries update full_charge as the batteries degrade */
166 	if (battery->full_charge_capacity == battery->capacity_now)
167 		return 1;
168 
169 	/* fallback to using design values for broken batteries */
170 	if (battery->design_capacity <= battery->capacity_now)
171 		return 1;
172 
173 	/* we don't do any sort of metric based on percentages */
174 	return 0;
175 }
176 
acpi_battery_is_degraded(struct acpi_battery * battery)177 static bool acpi_battery_is_degraded(struct acpi_battery *battery)
178 {
179 	return ACPI_BATTERY_CAPACITY_VALID(battery->full_charge_capacity) &&
180 		ACPI_BATTERY_CAPACITY_VALID(battery->design_capacity) &&
181 		battery->full_charge_capacity < battery->design_capacity;
182 }
183 
acpi_battery_handle_discharging(struct acpi_battery * battery)184 static int acpi_battery_handle_discharging(struct acpi_battery *battery)
185 {
186 	/*
187 	 * Some devices wrongly report discharging if the battery's charge level
188 	 * was above the device's start charging threshold atm the AC adapter
189 	 * was plugged in and the device thus did not start a new charge cycle.
190 	 */
191 	if ((battery_ac_is_broken || power_supply_is_system_supplied()) &&
192 	    battery->rate_now == 0)
193 		return POWER_SUPPLY_STATUS_NOT_CHARGING;
194 
195 	return POWER_SUPPLY_STATUS_DISCHARGING;
196 }
197 
acpi_battery_get_property(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)198 static int acpi_battery_get_property(struct power_supply *psy,
199 				     enum power_supply_property psp,
200 				     union power_supply_propval *val)
201 {
202 	int full_capacity = ACPI_BATTERY_VALUE_UNKNOWN, ret = 0;
203 	struct acpi_battery *battery = to_acpi_battery(psy);
204 
205 	if (acpi_battery_present(battery)) {
206 		/* run battery update only if it is present */
207 		acpi_battery_get_state(battery);
208 	} else if (psp != POWER_SUPPLY_PROP_PRESENT)
209 		return -ENODEV;
210 	switch (psp) {
211 	case POWER_SUPPLY_PROP_STATUS:
212 		if (battery->state & ACPI_BATTERY_STATE_DISCHARGING)
213 			val->intval = acpi_battery_handle_discharging(battery);
214 		else if (battery->state & ACPI_BATTERY_STATE_CHARGING)
215 			/* Validate the status by checking the current. */
216 			if (battery->rate_now != ACPI_BATTERY_VALUE_UNKNOWN &&
217 			    battery->rate_now == 0) {
218 				/* On charge but no current (0W/0mA). */
219 				val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
220 			} else {
221 				val->intval = POWER_SUPPLY_STATUS_CHARGING;
222 			}
223 		else if (battery->state & ACPI_BATTERY_STATE_CHARGE_LIMITING)
224 			val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
225 		else if (acpi_battery_is_charged(battery))
226 			val->intval = POWER_SUPPLY_STATUS_FULL;
227 		else
228 			val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING;
229 		break;
230 	case POWER_SUPPLY_PROP_PRESENT:
231 		val->intval = acpi_battery_present(battery);
232 		break;
233 	case POWER_SUPPLY_PROP_TECHNOLOGY:
234 		val->intval = acpi_battery_technology(battery);
235 		break;
236 	case POWER_SUPPLY_PROP_CYCLE_COUNT:
237 		val->intval = battery->cycle_count;
238 		break;
239 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
240 		if (battery->design_voltage == ACPI_BATTERY_VALUE_UNKNOWN)
241 			ret = -ENODEV;
242 		else
243 			val->intval = battery->design_voltage * 1000;
244 		break;
245 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
246 		if (battery->voltage_now == ACPI_BATTERY_VALUE_UNKNOWN)
247 			ret = -ENODEV;
248 		else
249 			val->intval = battery->voltage_now * 1000;
250 		break;
251 	case POWER_SUPPLY_PROP_CURRENT_NOW:
252 	case POWER_SUPPLY_PROP_POWER_NOW:
253 		if (battery->rate_now == ACPI_BATTERY_VALUE_UNKNOWN)
254 			ret = -ENODEV;
255 		else
256 			val->intval = battery->rate_now * 1000;
257 		break;
258 	case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
259 	case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
260 		if (!ACPI_BATTERY_CAPACITY_VALID(battery->design_capacity))
261 			ret = -ENODEV;
262 		else
263 			val->intval = battery->design_capacity * 1000;
264 		break;
265 	case POWER_SUPPLY_PROP_CHARGE_FULL:
266 	case POWER_SUPPLY_PROP_ENERGY_FULL:
267 		if (!ACPI_BATTERY_CAPACITY_VALID(battery->full_charge_capacity))
268 			ret = -ENODEV;
269 		else
270 			val->intval = battery->full_charge_capacity * 1000;
271 		break;
272 	case POWER_SUPPLY_PROP_CHARGE_NOW:
273 	case POWER_SUPPLY_PROP_ENERGY_NOW:
274 		if (battery->capacity_now == ACPI_BATTERY_VALUE_UNKNOWN)
275 			ret = -ENODEV;
276 		else
277 			val->intval = battery->capacity_now * 1000;
278 		break;
279 	case POWER_SUPPLY_PROP_CAPACITY:
280 		if (ACPI_BATTERY_CAPACITY_VALID(battery->full_charge_capacity))
281 			full_capacity = battery->full_charge_capacity;
282 		else if (ACPI_BATTERY_CAPACITY_VALID(battery->design_capacity))
283 			full_capacity = battery->design_capacity;
284 
285 		if (battery->capacity_now == ACPI_BATTERY_VALUE_UNKNOWN ||
286 		    full_capacity == ACPI_BATTERY_VALUE_UNKNOWN)
287 			ret = -ENODEV;
288 		else
289 			val->intval = DIV_ROUND_CLOSEST_ULL(battery->capacity_now * 100ULL,
290 					full_capacity);
291 		break;
292 	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
293 		if (battery->state & ACPI_BATTERY_STATE_CRITICAL)
294 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
295 		else if (test_bit(ACPI_BATTERY_ALARM_PRESENT, &battery->flags) &&
296 			(battery->capacity_now <= battery->alarm))
297 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
298 		else if (acpi_battery_is_charged(battery))
299 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
300 		else
301 			val->intval = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
302 		break;
303 	case POWER_SUPPLY_PROP_MODEL_NAME:
304 		val->strval = battery->model_number;
305 		break;
306 	case POWER_SUPPLY_PROP_MANUFACTURER:
307 		val->strval = battery->oem_info;
308 		break;
309 	case POWER_SUPPLY_PROP_SERIAL_NUMBER:
310 		val->strval = battery->serial_number;
311 		break;
312 	default:
313 		ret = -EINVAL;
314 	}
315 	return ret;
316 }
317 
318 static const enum power_supply_property charge_battery_props[] = {
319 	POWER_SUPPLY_PROP_STATUS,
320 	POWER_SUPPLY_PROP_PRESENT,
321 	POWER_SUPPLY_PROP_TECHNOLOGY,
322 	POWER_SUPPLY_PROP_CYCLE_COUNT,
323 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
324 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
325 	POWER_SUPPLY_PROP_CURRENT_NOW,
326 	POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
327 	POWER_SUPPLY_PROP_CHARGE_FULL,
328 	POWER_SUPPLY_PROP_CHARGE_NOW,
329 	POWER_SUPPLY_PROP_CAPACITY,
330 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
331 	POWER_SUPPLY_PROP_MODEL_NAME,
332 	POWER_SUPPLY_PROP_MANUFACTURER,
333 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
334 };
335 
336 static const enum power_supply_property charge_battery_full_cap_broken_props[] = {
337 	POWER_SUPPLY_PROP_STATUS,
338 	POWER_SUPPLY_PROP_PRESENT,
339 	POWER_SUPPLY_PROP_TECHNOLOGY,
340 	POWER_SUPPLY_PROP_CYCLE_COUNT,
341 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
342 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
343 	POWER_SUPPLY_PROP_CURRENT_NOW,
344 	POWER_SUPPLY_PROP_CHARGE_NOW,
345 	POWER_SUPPLY_PROP_MODEL_NAME,
346 	POWER_SUPPLY_PROP_MANUFACTURER,
347 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
348 };
349 
350 static const enum power_supply_property energy_battery_props[] = {
351 	POWER_SUPPLY_PROP_STATUS,
352 	POWER_SUPPLY_PROP_PRESENT,
353 	POWER_SUPPLY_PROP_TECHNOLOGY,
354 	POWER_SUPPLY_PROP_CYCLE_COUNT,
355 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
356 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
357 	POWER_SUPPLY_PROP_POWER_NOW,
358 	POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
359 	POWER_SUPPLY_PROP_ENERGY_FULL,
360 	POWER_SUPPLY_PROP_ENERGY_NOW,
361 	POWER_SUPPLY_PROP_CAPACITY,
362 	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
363 	POWER_SUPPLY_PROP_MODEL_NAME,
364 	POWER_SUPPLY_PROP_MANUFACTURER,
365 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
366 };
367 
368 static const enum power_supply_property energy_battery_full_cap_broken_props[] = {
369 	POWER_SUPPLY_PROP_STATUS,
370 	POWER_SUPPLY_PROP_PRESENT,
371 	POWER_SUPPLY_PROP_TECHNOLOGY,
372 	POWER_SUPPLY_PROP_CYCLE_COUNT,
373 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
374 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
375 	POWER_SUPPLY_PROP_POWER_NOW,
376 	POWER_SUPPLY_PROP_ENERGY_NOW,
377 	POWER_SUPPLY_PROP_MODEL_NAME,
378 	POWER_SUPPLY_PROP_MANUFACTURER,
379 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
380 };
381 
382 /* Battery Management */
383 struct acpi_offsets {
384 	size_t offset;		/* offset inside struct acpi_sbs_battery */
385 	u8 mode;		/* int or string? */
386 };
387 
388 static const struct acpi_offsets state_offsets[] = {
389 	{offsetof(struct acpi_battery, state), 0},
390 	{offsetof(struct acpi_battery, rate_now), 0},
391 	{offsetof(struct acpi_battery, capacity_now), 0},
392 	{offsetof(struct acpi_battery, voltage_now), 0},
393 };
394 
395 static const struct acpi_offsets info_offsets[] = {
396 	{offsetof(struct acpi_battery, power_unit), 0},
397 	{offsetof(struct acpi_battery, design_capacity), 0},
398 	{offsetof(struct acpi_battery, full_charge_capacity), 0},
399 	{offsetof(struct acpi_battery, technology), 0},
400 	{offsetof(struct acpi_battery, design_voltage), 0},
401 	{offsetof(struct acpi_battery, design_capacity_warning), 0},
402 	{offsetof(struct acpi_battery, design_capacity_low), 0},
403 	{offsetof(struct acpi_battery, capacity_granularity_1), 0},
404 	{offsetof(struct acpi_battery, capacity_granularity_2), 0},
405 	{offsetof(struct acpi_battery, model_number), 1},
406 	{offsetof(struct acpi_battery, serial_number), 1},
407 	{offsetof(struct acpi_battery, type), 1},
408 	{offsetof(struct acpi_battery, oem_info), 1},
409 };
410 
411 static const struct acpi_offsets extended_info_offsets[] = {
412 	{offsetof(struct acpi_battery, revision), 0},
413 	{offsetof(struct acpi_battery, power_unit), 0},
414 	{offsetof(struct acpi_battery, design_capacity), 0},
415 	{offsetof(struct acpi_battery, full_charge_capacity), 0},
416 	{offsetof(struct acpi_battery, technology), 0},
417 	{offsetof(struct acpi_battery, design_voltage), 0},
418 	{offsetof(struct acpi_battery, design_capacity_warning), 0},
419 	{offsetof(struct acpi_battery, design_capacity_low), 0},
420 	{offsetof(struct acpi_battery, cycle_count), 0},
421 	{offsetof(struct acpi_battery, measurement_accuracy), 0},
422 	{offsetof(struct acpi_battery, max_sampling_time), 0},
423 	{offsetof(struct acpi_battery, min_sampling_time), 0},
424 	{offsetof(struct acpi_battery, max_averaging_interval), 0},
425 	{offsetof(struct acpi_battery, min_averaging_interval), 0},
426 	{offsetof(struct acpi_battery, capacity_granularity_1), 0},
427 	{offsetof(struct acpi_battery, capacity_granularity_2), 0},
428 	{offsetof(struct acpi_battery, model_number), 1},
429 	{offsetof(struct acpi_battery, serial_number), 1},
430 	{offsetof(struct acpi_battery, type), 1},
431 	{offsetof(struct acpi_battery, oem_info), 1},
432 };
433 
extract_package(struct acpi_battery * battery,union acpi_object * package,const struct acpi_offsets * offsets,int num)434 static int extract_package(struct acpi_battery *battery,
435 			   union acpi_object *package,
436 			   const struct acpi_offsets *offsets, int num)
437 {
438 	int i;
439 	union acpi_object *element;
440 
441 	if (package->type != ACPI_TYPE_PACKAGE)
442 		return -EFAULT;
443 	for (i = 0; i < num; ++i) {
444 		if (package->package.count <= i)
445 			return -EFAULT;
446 		element = &package->package.elements[i];
447 		if (offsets[i].mode) {
448 			u8 *ptr = (u8 *)battery + offsets[i].offset;
449 			u32 len = MAX_STRING_LENGTH;
450 
451 			switch (element->type) {
452 			case ACPI_TYPE_BUFFER:
453 				if (len > element->buffer.length + 1)
454 					len = element->buffer.length + 1;
455 
456 				fallthrough;
457 			case ACPI_TYPE_STRING:
458 				strscpy(ptr, element->string.pointer, len);
459 
460 				break;
461 			case ACPI_TYPE_INTEGER:
462 				strscpy(ptr, (u8 *)&element->integer.value, sizeof(u64) + 1);
463 
464 				break;
465 			default:
466 				*ptr = 0; /* don't have value */
467 			}
468 		} else {
469 			int *x = (int *)((u8 *)battery + offsets[i].offset);
470 			*x = (element->type == ACPI_TYPE_INTEGER) ?
471 				element->integer.value : -1;
472 		}
473 	}
474 	return 0;
475 }
476 
acpi_battery_get_status(struct acpi_battery * battery)477 static int acpi_battery_get_status(struct acpi_battery *battery)
478 {
479 	if (acpi_bus_get_status(battery->device)) {
480 		acpi_handle_info(battery->device->handle,
481 				 "_STA evaluation failed\n");
482 		return -ENODEV;
483 	}
484 	return 0;
485 }
486 
487 
extract_battery_info(const int use_bix,struct acpi_battery * battery,const struct acpi_buffer * buffer)488 static int extract_battery_info(const int use_bix,
489 			 struct acpi_battery *battery,
490 			 const struct acpi_buffer *buffer)
491 {
492 	int result = -EFAULT;
493 
494 	if (use_bix && battery_bix_broken_package)
495 		result = extract_package(battery, buffer->pointer,
496 				extended_info_offsets + 1,
497 				ARRAY_SIZE(extended_info_offsets) - 1);
498 	else if (use_bix)
499 		result = extract_package(battery, buffer->pointer,
500 				extended_info_offsets,
501 				ARRAY_SIZE(extended_info_offsets));
502 	else
503 		result = extract_package(battery, buffer->pointer,
504 				info_offsets, ARRAY_SIZE(info_offsets));
505 	if (test_bit(ACPI_BATTERY_QUIRK_PERCENTAGE_CAPACITY, &battery->flags))
506 		battery->full_charge_capacity = battery->design_capacity;
507 	if (test_bit(ACPI_BATTERY_QUIRK_THINKPAD_MAH, &battery->flags) &&
508 	    battery->power_unit && battery->design_voltage) {
509 		battery->design_capacity = battery->design_capacity *
510 		    10000 / battery->design_voltage;
511 		battery->full_charge_capacity = battery->full_charge_capacity *
512 		    10000 / battery->design_voltage;
513 		battery->design_capacity_warning =
514 		    battery->design_capacity_warning *
515 		    10000 / battery->design_voltage;
516 		/* Curiously, design_capacity_low, unlike the rest of them,
517 		 *  is correct.
518 		 */
519 		/* capacity_granularity_* equal 1 on the systems tested, so
520 		 * it's impossible to tell if they would need an adjustment
521 		 * or not if their values were higher.
522 		 */
523 	}
524 	if (test_bit(ACPI_BATTERY_QUIRK_DEGRADED_FULL_CHARGE, &battery->flags) &&
525 	    battery->capacity_now > battery->full_charge_capacity)
526 		battery->capacity_now = battery->full_charge_capacity;
527 
528 	return result;
529 }
530 
acpi_battery_get_info(struct acpi_battery * battery)531 static int acpi_battery_get_info(struct acpi_battery *battery)
532 {
533 	const int xinfo = test_bit(ACPI_BATTERY_XINFO_PRESENT, &battery->flags);
534 	int use_bix;
535 	int result = -ENODEV;
536 
537 	if (!acpi_battery_present(battery))
538 		return 0;
539 
540 
541 	for (use_bix = xinfo ? 1 : 0; use_bix >= 0; use_bix--) {
542 		struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
543 		acpi_status status = AE_ERROR;
544 
545 		status = acpi_evaluate_object(battery->device->handle,
546 					      use_bix ? "_BIX":"_BIF",
547 					      NULL, &buffer);
548 
549 		if (ACPI_FAILURE(status)) {
550 			acpi_handle_info(battery->device->handle,
551 					 "%s evaluation failed: %s\n",
552 					 use_bix ? "_BIX":"_BIF",
553 					 acpi_format_exception(status));
554 		} else {
555 			result = extract_battery_info(use_bix,
556 						      battery,
557 						      &buffer);
558 
559 			kfree(buffer.pointer);
560 			break;
561 		}
562 	}
563 
564 	if (!result && !use_bix && xinfo)
565 		pr_warn(FW_BUG "The _BIX method is broken, using _BIF.\n");
566 
567 	return result;
568 }
569 
acpi_battery_get_state(struct acpi_battery * battery)570 static int acpi_battery_get_state(struct acpi_battery *battery)
571 {
572 	int result = 0;
573 	acpi_status status = 0;
574 	struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
575 
576 	if (!acpi_battery_present(battery))
577 		return 0;
578 
579 	if (battery->update_time &&
580 	    time_before(jiffies, battery->update_time +
581 			msecs_to_jiffies(cache_time)))
582 		return 0;
583 
584 	status = acpi_evaluate_object(battery->device->handle, "_BST",
585 				      NULL, &buffer);
586 	if (ACPI_FAILURE(status)) {
587 		acpi_handle_info(battery->device->handle,
588 				 "_BST evaluation failed: %s",
589 				 acpi_format_exception(status));
590 		return -ENODEV;
591 	}
592 
593 	result = extract_package(battery, buffer.pointer,
594 				 state_offsets, ARRAY_SIZE(state_offsets));
595 	battery->update_time = jiffies;
596 	kfree(buffer.pointer);
597 
598 	/* For buggy DSDTs that report negative 16-bit values for either
599 	 * charging or discharging current and/or report 0 as 65536
600 	 * due to bad math.
601 	 */
602 	if (battery->power_unit == ACPI_BATTERY_POWER_UNIT_MA &&
603 		battery->rate_now != ACPI_BATTERY_VALUE_UNKNOWN &&
604 		(s16)(battery->rate_now) < 0) {
605 		battery->rate_now = abs((s16)battery->rate_now);
606 		pr_warn_once(FW_BUG "(dis)charge rate invalid.\n");
607 	}
608 
609 	if (test_bit(ACPI_BATTERY_QUIRK_PERCENTAGE_CAPACITY, &battery->flags)
610 	    && battery->capacity_now >= 0 && battery->capacity_now <= 100)
611 		battery->capacity_now = (battery->capacity_now *
612 				battery->full_charge_capacity) / 100;
613 	if (test_bit(ACPI_BATTERY_QUIRK_THINKPAD_MAH, &battery->flags) &&
614 	    battery->power_unit && battery->design_voltage) {
615 		battery->capacity_now = battery->capacity_now *
616 		    10000 / battery->design_voltage;
617 	}
618 	if (test_bit(ACPI_BATTERY_QUIRK_DEGRADED_FULL_CHARGE, &battery->flags) &&
619 	    battery->capacity_now > battery->full_charge_capacity)
620 		battery->capacity_now = battery->full_charge_capacity;
621 
622 	return result;
623 }
624 
acpi_battery_set_alarm(struct acpi_battery * battery)625 static int acpi_battery_set_alarm(struct acpi_battery *battery)
626 {
627 	acpi_status status = 0;
628 
629 	if (!acpi_battery_present(battery) ||
630 	    !test_bit(ACPI_BATTERY_ALARM_PRESENT, &battery->flags))
631 		return -ENODEV;
632 
633 	status = acpi_execute_simple_method(battery->device->handle, "_BTP",
634 					    battery->alarm);
635 	if (ACPI_FAILURE(status))
636 		return -ENODEV;
637 
638 	acpi_handle_debug(battery->device->handle, "Alarm set to %d\n",
639 			  battery->alarm);
640 
641 	return 0;
642 }
643 
acpi_battery_init_alarm(struct acpi_battery * battery)644 static int acpi_battery_init_alarm(struct acpi_battery *battery)
645 {
646 	/* See if alarms are supported, and if so, set default */
647 	if (!acpi_has_method(battery->device->handle, "_BTP")) {
648 		clear_bit(ACPI_BATTERY_ALARM_PRESENT, &battery->flags);
649 		return 0;
650 	}
651 	set_bit(ACPI_BATTERY_ALARM_PRESENT, &battery->flags);
652 	if (!battery->alarm)
653 		battery->alarm = battery->design_capacity_warning;
654 	return acpi_battery_set_alarm(battery);
655 }
656 
acpi_battery_alarm_show(struct device * dev,struct device_attribute * attr,char * buf)657 static ssize_t acpi_battery_alarm_show(struct device *dev,
658 					struct device_attribute *attr,
659 					char *buf)
660 {
661 	struct acpi_battery *battery = to_acpi_battery(dev_get_drvdata(dev));
662 
663 	return sysfs_emit(buf, "%d\n", battery->alarm * 1000);
664 }
665 
acpi_battery_alarm_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)666 static ssize_t acpi_battery_alarm_store(struct device *dev,
667 					struct device_attribute *attr,
668 					const char *buf, size_t count)
669 {
670 	unsigned long x;
671 	struct acpi_battery *battery = to_acpi_battery(dev_get_drvdata(dev));
672 
673 	if (sscanf(buf, "%lu\n", &x) == 1)
674 		battery->alarm = x/1000;
675 	if (acpi_battery_present(battery))
676 		acpi_battery_set_alarm(battery);
677 	return count;
678 }
679 
680 static struct device_attribute alarm_attr = {
681 	.attr = {.name = "alarm", .mode = 0644},
682 	.show = acpi_battery_alarm_show,
683 	.store = acpi_battery_alarm_store,
684 };
685 
686 static struct attribute *acpi_battery_attrs[] = {
687 	&alarm_attr.attr,
688 	NULL
689 };
690 ATTRIBUTE_GROUPS(acpi_battery);
691 
692 /*
693  * The Battery Hooking API
694  *
695  * This API is used inside other drivers that need to expose
696  * platform-specific behaviour within the generic driver in a
697  * generic way.
698  *
699  */
700 
701 static LIST_HEAD(acpi_battery_list);
702 static LIST_HEAD(battery_hook_list);
703 static DEFINE_MUTEX(hook_mutex);
704 
battery_hook_unregister_unlocked(struct acpi_battery_hook * hook)705 static void battery_hook_unregister_unlocked(struct acpi_battery_hook *hook)
706 {
707 	struct acpi_battery *battery;
708 
709 	/*
710 	 * In order to remove a hook, we first need to
711 	 * de-register all the batteries that are registered.
712 	 */
713 	list_for_each_entry(battery, &acpi_battery_list, list) {
714 		if (!hook->remove_battery(battery->bat, hook))
715 			power_supply_changed(battery->bat);
716 	}
717 	list_del_init(&hook->list);
718 
719 	pr_info("hook unregistered: %s\n", hook->name);
720 }
721 
battery_hook_unregister(struct acpi_battery_hook * hook)722 void battery_hook_unregister(struct acpi_battery_hook *hook)
723 {
724 	mutex_lock(&hook_mutex);
725 	/*
726 	 * Ignore already unregistered battery hooks. This might happen
727 	 * if a battery hook was previously unloaded due to an error when
728 	 * adding a new battery.
729 	 */
730 	if (!list_empty(&hook->list))
731 		battery_hook_unregister_unlocked(hook);
732 
733 	mutex_unlock(&hook_mutex);
734 }
735 EXPORT_SYMBOL_GPL(battery_hook_unregister);
736 
battery_hook_register(struct acpi_battery_hook * hook)737 void battery_hook_register(struct acpi_battery_hook *hook)
738 {
739 	struct acpi_battery *battery;
740 
741 	mutex_lock(&hook_mutex);
742 	list_add(&hook->list, &battery_hook_list);
743 	/*
744 	 * Now that the driver is registered, we need
745 	 * to notify the hook that a battery is available
746 	 * for each battery, so that the driver may add
747 	 * its attributes.
748 	 */
749 	list_for_each_entry(battery, &acpi_battery_list, list) {
750 		if (hook->add_battery(battery->bat, hook)) {
751 			/*
752 			 * If a add-battery returns non-zero,
753 			 * the registration of the hook has failed,
754 			 * and we will not add it to the list of loaded
755 			 * hooks.
756 			 */
757 			pr_err("hook failed to load: %s", hook->name);
758 			battery_hook_unregister_unlocked(hook);
759 			goto end;
760 		}
761 
762 		power_supply_changed(battery->bat);
763 	}
764 	pr_info("new hook: %s\n", hook->name);
765 end:
766 	mutex_unlock(&hook_mutex);
767 }
768 EXPORT_SYMBOL_GPL(battery_hook_register);
769 
devm_battery_hook_unregister(void * data)770 static void devm_battery_hook_unregister(void *data)
771 {
772 	struct acpi_battery_hook *hook = data;
773 
774 	battery_hook_unregister(hook);
775 }
776 
devm_battery_hook_register(struct device * dev,struct acpi_battery_hook * hook)777 int devm_battery_hook_register(struct device *dev, struct acpi_battery_hook *hook)
778 {
779 	battery_hook_register(hook);
780 
781 	return devm_add_action_or_reset(dev, devm_battery_hook_unregister, hook);
782 }
783 EXPORT_SYMBOL_GPL(devm_battery_hook_register);
784 
785 /*
786  * This function gets called right after the battery sysfs
787  * attributes have been added, so that the drivers that
788  * define custom sysfs attributes can add their own.
789  */
battery_hook_add_battery(struct acpi_battery * battery)790 static void battery_hook_add_battery(struct acpi_battery *battery)
791 {
792 	struct acpi_battery_hook *hook_node, *tmp;
793 
794 	mutex_lock(&hook_mutex);
795 	INIT_LIST_HEAD(&battery->list);
796 	list_add(&battery->list, &acpi_battery_list);
797 	/*
798 	 * Since we added a new battery to the list, we need to
799 	 * iterate over the hooks and call add_battery for each
800 	 * hook that was registered. This usually happens
801 	 * when a battery gets hotplugged or initialized
802 	 * during the battery module initialization.
803 	 */
804 	list_for_each_entry_safe(hook_node, tmp, &battery_hook_list, list) {
805 		if (hook_node->add_battery(battery->bat, hook_node)) {
806 			/*
807 			 * The notification of the hook has failed, to
808 			 * prevent further errors we will unload the hook.
809 			 */
810 			pr_err("error in hook, unloading: %s",
811 					hook_node->name);
812 			battery_hook_unregister_unlocked(hook_node);
813 		}
814 	}
815 	mutex_unlock(&hook_mutex);
816 }
817 
battery_hook_remove_battery(struct acpi_battery * battery)818 static void battery_hook_remove_battery(struct acpi_battery *battery)
819 {
820 	struct acpi_battery_hook *hook;
821 
822 	mutex_lock(&hook_mutex);
823 	/*
824 	 * Before removing the hook, we need to remove all
825 	 * custom attributes from the battery.
826 	 */
827 	list_for_each_entry(hook, &battery_hook_list, list) {
828 		hook->remove_battery(battery->bat, hook);
829 	}
830 	/* Then, just remove the battery from the list */
831 	list_del(&battery->list);
832 	mutex_unlock(&hook_mutex);
833 }
834 
battery_hook_exit(void)835 static void __exit battery_hook_exit(void)
836 {
837 	struct acpi_battery_hook *hook;
838 	struct acpi_battery_hook *ptr;
839 	/*
840 	 * At this point, the acpi_bus_unregister_driver()
841 	 * has called remove for all batteries. We just
842 	 * need to remove the hooks.
843 	 */
844 	list_for_each_entry_safe(hook, ptr, &battery_hook_list, list) {
845 		battery_hook_unregister(hook);
846 	}
847 	mutex_destroy(&hook_mutex);
848 }
849 
sysfs_add_battery(struct acpi_battery * battery)850 static int sysfs_add_battery(struct acpi_battery *battery)
851 {
852 	struct power_supply_config psy_cfg = {
853 		.drv_data = battery,
854 		.attr_grp = acpi_battery_groups,
855 		.no_wakeup_source = true,
856 	};
857 	bool full_cap_broken = false;
858 
859 	if (!ACPI_BATTERY_CAPACITY_VALID(battery->full_charge_capacity) &&
860 	    !ACPI_BATTERY_CAPACITY_VALID(battery->design_capacity))
861 		full_cap_broken = true;
862 
863 	if (battery->power_unit == ACPI_BATTERY_POWER_UNIT_MA) {
864 		if (full_cap_broken) {
865 			battery->bat_desc.properties =
866 			    charge_battery_full_cap_broken_props;
867 			battery->bat_desc.num_properties =
868 			    ARRAY_SIZE(charge_battery_full_cap_broken_props);
869 		} else {
870 			battery->bat_desc.properties = charge_battery_props;
871 			battery->bat_desc.num_properties =
872 			    ARRAY_SIZE(charge_battery_props);
873 		}
874 	} else {
875 		if (full_cap_broken) {
876 			battery->bat_desc.properties =
877 			    energy_battery_full_cap_broken_props;
878 			battery->bat_desc.num_properties =
879 			    ARRAY_SIZE(energy_battery_full_cap_broken_props);
880 		} else {
881 			battery->bat_desc.properties = energy_battery_props;
882 			battery->bat_desc.num_properties =
883 			    ARRAY_SIZE(energy_battery_props);
884 		}
885 	}
886 
887 	battery->bat_desc.name = acpi_device_bid(battery->device);
888 	battery->bat_desc.type = POWER_SUPPLY_TYPE_BATTERY;
889 	battery->bat_desc.get_property = acpi_battery_get_property;
890 
891 	battery->bat = power_supply_register(&battery->device->dev,
892 				&battery->bat_desc, &psy_cfg);
893 
894 	if (IS_ERR(battery->bat)) {
895 		int result = PTR_ERR(battery->bat);
896 
897 		battery->bat = NULL;
898 		return result;
899 	}
900 	battery_hook_add_battery(battery);
901 	return 0;
902 }
903 
sysfs_remove_battery(struct acpi_battery * battery)904 static void sysfs_remove_battery(struct acpi_battery *battery)
905 {
906 	if (!battery->bat)
907 		return;
908 
909 	battery_hook_remove_battery(battery);
910 	power_supply_unregister(battery->bat);
911 	battery->bat = NULL;
912 }
913 
find_battery(const struct dmi_header * dm,void * private)914 static void find_battery(const struct dmi_header *dm, void *private)
915 {
916 	struct acpi_battery *battery = (struct acpi_battery *)private;
917 	/* Note: the hardcoded offsets below have been extracted from
918 	 * the source code of dmidecode.
919 	 */
920 	if (dm->type == DMI_ENTRY_PORTABLE_BATTERY && dm->length >= 8) {
921 		const u8 *dmi_data = (const u8 *)(dm + 1);
922 		int dmi_capacity = get_unaligned((const u16 *)(dmi_data + 6));
923 
924 		if (dm->length >= 18)
925 			dmi_capacity *= dmi_data[17];
926 		if (battery->design_capacity * battery->design_voltage / 1000
927 		    != dmi_capacity &&
928 		    battery->design_capacity * 10 == dmi_capacity)
929 			set_bit(ACPI_BATTERY_QUIRK_THINKPAD_MAH,
930 				&battery->flags);
931 	}
932 }
933 
934 /*
935  * According to the ACPI spec, some kinds of primary batteries can
936  * report percentage battery remaining capacity directly to OS.
937  * In this case, it reports the Last Full Charged Capacity == 100
938  * and BatteryPresentRate == 0xFFFFFFFF.
939  *
940  * Now we found some battery reports percentage remaining capacity
941  * even if it's rechargeable.
942  * https://bugzilla.kernel.org/show_bug.cgi?id=15979
943  *
944  * Handle this correctly so that they won't break userspace.
945  */
acpi_battery_quirks(struct acpi_battery * battery)946 static void acpi_battery_quirks(struct acpi_battery *battery)
947 {
948 	if (test_bit(ACPI_BATTERY_QUIRK_PERCENTAGE_CAPACITY, &battery->flags))
949 		return;
950 
951 	if (battery->full_charge_capacity == 100 &&
952 		battery->rate_now == ACPI_BATTERY_VALUE_UNKNOWN &&
953 		battery->capacity_now >= 0 && battery->capacity_now <= 100) {
954 		set_bit(ACPI_BATTERY_QUIRK_PERCENTAGE_CAPACITY, &battery->flags);
955 		battery->full_charge_capacity = battery->design_capacity;
956 		battery->capacity_now = (battery->capacity_now *
957 				battery->full_charge_capacity) / 100;
958 	}
959 
960 	if (test_bit(ACPI_BATTERY_QUIRK_THINKPAD_MAH, &battery->flags))
961 		return;
962 
963 	if (battery->power_unit && dmi_name_in_vendors("LENOVO")) {
964 		const char *s;
965 
966 		s = dmi_get_system_info(DMI_PRODUCT_VERSION);
967 		if (s && !strncasecmp(s, "ThinkPad", 8)) {
968 			dmi_walk(find_battery, battery);
969 			if (test_bit(ACPI_BATTERY_QUIRK_THINKPAD_MAH,
970 				     &battery->flags) &&
971 			    battery->design_voltage) {
972 				battery->design_capacity =
973 				    battery->design_capacity *
974 				    10000 / battery->design_voltage;
975 				battery->full_charge_capacity =
976 				    battery->full_charge_capacity *
977 				    10000 / battery->design_voltage;
978 				battery->design_capacity_warning =
979 				    battery->design_capacity_warning *
980 				    10000 / battery->design_voltage;
981 				battery->capacity_now = battery->capacity_now *
982 				    10000 / battery->design_voltage;
983 			}
984 		}
985 	}
986 
987 	if (test_bit(ACPI_BATTERY_QUIRK_DEGRADED_FULL_CHARGE, &battery->flags))
988 		return;
989 
990 	if (acpi_battery_is_degraded(battery) &&
991 	    battery->capacity_now > battery->full_charge_capacity) {
992 		set_bit(ACPI_BATTERY_QUIRK_DEGRADED_FULL_CHARGE, &battery->flags);
993 		battery->capacity_now = battery->full_charge_capacity;
994 	}
995 }
996 
acpi_battery_update(struct acpi_battery * battery,bool resume)997 static int acpi_battery_update(struct acpi_battery *battery, bool resume)
998 {
999 	int result = acpi_battery_get_status(battery);
1000 
1001 	if (result)
1002 		return result;
1003 
1004 	if (!acpi_battery_present(battery)) {
1005 		sysfs_remove_battery(battery);
1006 		battery->update_time = 0;
1007 		return 0;
1008 	}
1009 
1010 	if (resume)
1011 		return 0;
1012 
1013 	if (!battery->update_time) {
1014 		result = acpi_battery_get_info(battery);
1015 		if (result)
1016 			return result;
1017 		acpi_battery_init_alarm(battery);
1018 	}
1019 
1020 	result = acpi_battery_get_state(battery);
1021 	if (result)
1022 		return result;
1023 	acpi_battery_quirks(battery);
1024 
1025 	if (!battery->bat) {
1026 		result = sysfs_add_battery(battery);
1027 		if (result)
1028 			return result;
1029 	}
1030 
1031 	/*
1032 	 * Wakeup the system if battery is critical low
1033 	 * or lower than the alarm level
1034 	 */
1035 	if ((battery->state & ACPI_BATTERY_STATE_CRITICAL) ||
1036 	    (test_bit(ACPI_BATTERY_ALARM_PRESENT, &battery->flags) &&
1037 	     (battery->capacity_now <= battery->alarm)))
1038 		acpi_pm_wakeup_event(&battery->device->dev);
1039 
1040 	return result;
1041 }
1042 
acpi_battery_refresh(struct acpi_battery * battery)1043 static void acpi_battery_refresh(struct acpi_battery *battery)
1044 {
1045 	int power_unit;
1046 
1047 	if (!battery->bat)
1048 		return;
1049 
1050 	power_unit = battery->power_unit;
1051 
1052 	acpi_battery_get_info(battery);
1053 
1054 	if (power_unit == battery->power_unit)
1055 		return;
1056 
1057 	/* The battery has changed its reporting units. */
1058 	sysfs_remove_battery(battery);
1059 	sysfs_add_battery(battery);
1060 }
1061 
1062 /* Driver Interface */
acpi_battery_notify(acpi_handle handle,u32 event,void * data)1063 static void acpi_battery_notify(acpi_handle handle, u32 event, void *data)
1064 {
1065 	struct acpi_battery *battery = data;
1066 	struct acpi_device *device = battery->device;
1067 	struct power_supply *old;
1068 
1069 	guard(mutex)(&battery->update_lock);
1070 
1071 	old = battery->bat;
1072 	/*
1073 	 * On Acer Aspire V5-573G notifications are sometimes triggered too
1074 	 * early. For example, when AC is unplugged and notification is
1075 	 * triggered, battery state is still reported as "Full", and changes to
1076 	 * "Discharging" only after short delay, without any notification.
1077 	 */
1078 	if (battery_notification_delay_ms > 0)
1079 		msleep(battery_notification_delay_ms);
1080 	if (event == ACPI_BATTERY_NOTIFY_INFO)
1081 		acpi_battery_refresh(battery);
1082 	acpi_battery_update(battery, false);
1083 	acpi_bus_generate_netlink_event(device->pnp.device_class,
1084 					dev_name(&device->dev), event,
1085 					acpi_battery_present(battery));
1086 	acpi_notifier_call_chain(device, event, acpi_battery_present(battery));
1087 	/* acpi_battery_update could remove power_supply object */
1088 	if (old && battery->bat)
1089 		power_supply_changed(battery->bat);
1090 }
1091 
battery_notify(struct notifier_block * nb,unsigned long mode,void * _unused)1092 static int battery_notify(struct notifier_block *nb,
1093 			  unsigned long mode, void *_unused)
1094 {
1095 	struct acpi_battery *battery = container_of(nb, struct acpi_battery,
1096 						    pm_nb);
1097 
1098 	if (mode == PM_POST_SUSPEND || mode == PM_POST_HIBERNATION) {
1099 		guard(mutex)(&battery->update_lock);
1100 
1101 		if (!acpi_battery_present(battery))
1102 			return 0;
1103 
1104 		if (battery->bat) {
1105 			acpi_battery_refresh(battery);
1106 		} else {
1107 			int result;
1108 
1109 			result = acpi_battery_get_info(battery);
1110 			if (result)
1111 				return result;
1112 
1113 			result = sysfs_add_battery(battery);
1114 			if (result)
1115 				return result;
1116 		}
1117 
1118 		acpi_battery_init_alarm(battery);
1119 		acpi_battery_get_state(battery);
1120 	}
1121 
1122 	return 0;
1123 }
1124 
1125 static int __init
battery_bix_broken_package_quirk(const struct dmi_system_id * d)1126 battery_bix_broken_package_quirk(const struct dmi_system_id *d)
1127 {
1128 	battery_bix_broken_package = 1;
1129 	return 0;
1130 }
1131 
1132 static int __init
battery_notification_delay_quirk(const struct dmi_system_id * d)1133 battery_notification_delay_quirk(const struct dmi_system_id *d)
1134 {
1135 	battery_notification_delay_ms = 1000;
1136 	return 0;
1137 }
1138 
1139 static int __init
battery_ac_is_broken_quirk(const struct dmi_system_id * d)1140 battery_ac_is_broken_quirk(const struct dmi_system_id *d)
1141 {
1142 	battery_ac_is_broken = 1;
1143 	return 0;
1144 }
1145 
1146 static const struct dmi_system_id bat_dmi_table[] __initconst = {
1147 	{
1148 		/* NEC LZ750/LS */
1149 		.callback = battery_bix_broken_package_quirk,
1150 		.matches = {
1151 			DMI_MATCH(DMI_SYS_VENDOR, "NEC"),
1152 			DMI_MATCH(DMI_PRODUCT_NAME, "PC-LZ750LS"),
1153 		},
1154 	},
1155 	{
1156 		/* Acer Aspire V5-573G */
1157 		.callback = battery_notification_delay_quirk,
1158 		.matches = {
1159 			DMI_MATCH(DMI_SYS_VENDOR, "Acer"),
1160 			DMI_MATCH(DMI_PRODUCT_NAME, "Aspire V5-573G"),
1161 		},
1162 	},
1163 	{
1164 		/* Point of View mobii wintab p800w */
1165 		.callback = battery_ac_is_broken_quirk,
1166 		.matches = {
1167 			DMI_MATCH(DMI_BOARD_VENDOR, "AMI Corporation"),
1168 			DMI_MATCH(DMI_BOARD_NAME, "Aptio CRB"),
1169 			DMI_MATCH(DMI_BIOS_VERSION, "3BAIR1013"),
1170 			/* Above matches are too generic, add bios-date match */
1171 			DMI_MATCH(DMI_BIOS_DATE, "08/22/2014"),
1172 		},
1173 	},
1174 	{
1175 		/* Microsoft Surface Go 3 */
1176 		.callback = battery_notification_delay_quirk,
1177 		.matches = {
1178 			DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
1179 			DMI_MATCH(DMI_PRODUCT_NAME, "Surface Go 3"),
1180 		},
1181 	},
1182 	{},
1183 };
1184 
1185 /*
1186  * Some machines'(E,G Lenovo Z480) ECs are not stable
1187  * during boot up and this causes battery driver fails to be
1188  * probed due to failure of getting battery information
1189  * from EC sometimes. After several retries, the operation
1190  * may work. So add retry code here and 20ms sleep between
1191  * every retries.
1192  */
acpi_battery_update_retry(struct acpi_battery * battery)1193 static int acpi_battery_update_retry(struct acpi_battery *battery)
1194 {
1195 	int retry, ret;
1196 
1197 	guard(mutex)(&battery->update_lock);
1198 
1199 	for (retry = 5; retry; retry--) {
1200 		ret = acpi_battery_update(battery, false);
1201 		if (!ret)
1202 			break;
1203 
1204 		msleep(20);
1205 	}
1206 	return ret;
1207 }
1208 
sysfs_battery_cleanup(struct acpi_battery * battery)1209 static void sysfs_battery_cleanup(struct acpi_battery *battery)
1210 {
1211 	guard(mutex)(&battery->update_lock);
1212 
1213 	sysfs_remove_battery(battery);
1214 }
1215 
acpi_battery_probe(struct platform_device * pdev)1216 static int acpi_battery_probe(struct platform_device *pdev)
1217 {
1218 	struct acpi_device *device = ACPI_COMPANION(&pdev->dev);
1219 	struct acpi_battery *battery;
1220 	int result;
1221 
1222 	if (device->dep_unmet)
1223 		return -EPROBE_DEFER;
1224 
1225 	battery = devm_kzalloc(&pdev->dev, sizeof(*battery), GFP_KERNEL);
1226 	if (!battery)
1227 		return -ENOMEM;
1228 
1229 	platform_set_drvdata(pdev, battery);
1230 
1231 	battery->device = device;
1232 	strscpy(acpi_device_name(device), ACPI_BATTERY_DEVICE_NAME);
1233 	strscpy(acpi_device_class(device), ACPI_BATTERY_CLASS);
1234 
1235 	result = devm_mutex_init(&pdev->dev, &battery->update_lock);
1236 	if (result)
1237 		return result;
1238 
1239 	if (acpi_has_method(battery->device->handle, "_BIX"))
1240 		set_bit(ACPI_BATTERY_XINFO_PRESENT, &battery->flags);
1241 
1242 	result = acpi_battery_update_retry(battery);
1243 	if (result)
1244 		goto fail;
1245 
1246 	pr_info("Slot [%s] (battery %s)\n", acpi_device_bid(device),
1247 		device->status.battery_present ? "present" : "absent");
1248 
1249 	battery->pm_nb.notifier_call = battery_notify;
1250 	result = register_pm_notifier(&battery->pm_nb);
1251 	if (result)
1252 		goto fail;
1253 
1254 	device_init_wakeup(&pdev->dev, true);
1255 
1256 	result = acpi_dev_install_notify_handler(device, ACPI_ALL_NOTIFY,
1257 						 acpi_battery_notify, battery);
1258 	if (result)
1259 		goto fail_pm;
1260 
1261 	return 0;
1262 
1263 fail_pm:
1264 	device_init_wakeup(&pdev->dev, false);
1265 	unregister_pm_notifier(&battery->pm_nb);
1266 fail:
1267 	sysfs_battery_cleanup(battery);
1268 
1269 	return result;
1270 }
1271 
acpi_battery_remove(struct platform_device * pdev)1272 static void acpi_battery_remove(struct platform_device *pdev)
1273 {
1274 	struct acpi_battery *battery = platform_get_drvdata(pdev);
1275 
1276 	acpi_dev_remove_notify_handler(battery->device, ACPI_ALL_NOTIFY,
1277 				       acpi_battery_notify);
1278 
1279 	device_init_wakeup(&pdev->dev, false);
1280 	unregister_pm_notifier(&battery->pm_nb);
1281 
1282 	sysfs_battery_cleanup(battery);
1283 }
1284 
1285 /* this is needed to learn about changes made in suspended state */
acpi_battery_resume(struct device * dev)1286 static int acpi_battery_resume(struct device *dev)
1287 {
1288 	struct acpi_battery *battery = dev_get_drvdata(dev);
1289 
1290 	if (!battery)
1291 		return -EINVAL;
1292 
1293 	battery->update_time = 0;
1294 
1295 	guard(mutex)(&battery->update_lock);
1296 
1297 	acpi_battery_update(battery, true);
1298 	return 0;
1299 }
1300 
1301 static DEFINE_SIMPLE_DEV_PM_OPS(acpi_battery_pm, NULL, acpi_battery_resume);
1302 
1303 static struct platform_driver acpi_battery_driver = {
1304 	.probe = acpi_battery_probe,
1305 	.remove = acpi_battery_remove,
1306 	.driver = {
1307 		.name = "acpi-battery",
1308 		.acpi_match_table = battery_device_ids,
1309 		.pm = pm_sleep_ptr(&acpi_battery_pm),
1310 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
1311 	},
1312 };
1313 
acpi_battery_init(void)1314 static int __init acpi_battery_init(void)
1315 {
1316 	if (acpi_disabled || acpi_quirk_skip_acpi_ac_and_battery())
1317 		return -ENODEV;
1318 
1319 	dmi_check_system(bat_dmi_table);
1320 
1321 	return platform_driver_register(&acpi_battery_driver);
1322 }
1323 
acpi_battery_exit(void)1324 static void __exit acpi_battery_exit(void)
1325 {
1326 	platform_driver_unregister(&acpi_battery_driver);
1327 	battery_hook_exit();
1328 }
1329 
1330 module_init(acpi_battery_init);
1331 module_exit(acpi_battery_exit);
1332