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