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