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