c4360651964208234c0393ce57289d07b5e7baf7
[dragonfly.git] / sys / dev / acpica5 / acpi_battery.c
1 /*-
2  * Copyright (c) 2005 Nate Lawson
3  * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@jp.freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/dev/acpica/acpi_battery.c,v 1.26 2007/11/20 18:35:36 jkim Exp $
28  * $DragonFly: src/sys/dev/acpica5/acpi_battery.c,v 1.4 2008/09/29 06:59:45 hasso Exp $
29  */
30
31 #include "opt_acpi.h"
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/bus.h>
36 #include <sys/ioccom.h>
37 #include <sys/sysctl.h>
38 #include <sys/thread2.h>
39
40 #include "acpi.h"
41 #include <dev/acpica5/acpivar.h>
42 #include <dev/acpica5/acpiio.h>
43
44 /* Default seconds before re-sampling the battery state. */
45 #define ACPI_BATTERY_INFO_EXPIRE        5
46
47 static int      acpi_batteries_initted;
48 static int      acpi_battery_info_expire = ACPI_BATTERY_INFO_EXPIRE;
49 static struct   acpi_battinfo   acpi_battery_battinfo;
50 static struct   sysctl_ctx_list acpi_battery_sysctl_ctx;
51 static struct   sysctl_oid      *acpi_battery_sysctl_tree;
52
53 static void acpi_reset_battinfo(struct acpi_battinfo *info);
54 static void acpi_battery_clean_str(char *str, int len);
55 static device_t acpi_battery_find_dev(u_int logical_unit);
56 static int acpi_battery_ioctl(u_long cmd, caddr_t addr, void *arg);
57 static int acpi_battery_sysctl(SYSCTL_HANDLER_ARGS);
58 static int acpi_battery_units_sysctl(SYSCTL_HANDLER_ARGS);
59 static int acpi_battery_init(void);
60
61 int
62 acpi_battery_register(device_t dev)
63 {
64     int error;
65
66     error = 0;
67     crit_enter();
68     if (!acpi_batteries_initted)
69         error = acpi_battery_init();
70     crit_exit();
71     return (error);
72 }
73
74 int
75 acpi_battery_remove(device_t dev)
76 {
77     return (0);
78 }
79
80 int
81 acpi_battery_get_units(void)
82 {
83     devclass_t batt_dc;
84
85     batt_dc = devclass_find("battery");
86     if (batt_dc == NULL)
87         return (0);
88     return (devclass_get_count(batt_dc));
89 }
90
91 int
92 acpi_battery_get_info_expire(void)
93 {
94     return (acpi_battery_info_expire);
95 }
96
97 /* Check _BST results for validity. */
98 int
99 acpi_battery_bst_valid(struct acpi_bst *bst)
100 {
101     return (bst->state < ACPI_BATT_STAT_MAX && bst->cap != ACPI_BATT_UNKNOWN &&
102         bst->volt != ACPI_BATT_UNKNOWN);
103 }
104
105 /* Check _BIF results for validity. */
106 int
107 acpi_battery_bif_valid(struct acpi_bif *bif)
108 {
109     return (bif->lfcap != 0);
110 }
111
112 /* Get info about one or all batteries. */
113 int
114 acpi_battery_get_battinfo(device_t dev, struct acpi_battinfo *battinfo)
115 {
116     int batt_stat, devcount, dev_idx, error, i;
117     int total_cap, total_min, valid_rate, valid_units;
118     devclass_t batt_dc;
119     device_t batt_dev;
120     struct acpi_bst *bst;
121     struct acpi_bif *bif;
122     struct acpi_battinfo *bi;
123
124     /*
125      * Get the battery devclass and max unit for battery devices.  If there
126      * are none or error, return immediately.
127      */
128     batt_dc = devclass_find("battery");
129     if (batt_dc == NULL)
130         return (ENXIO);
131     devcount = devclass_get_maxunit(batt_dc);
132     if (devcount == 0)
133         return (ENXIO);
134
135     /*
136      * Allocate storage for all _BST data, their derived battinfo data,
137      * and the current battery's _BIF data.
138      */
139     bst = kmalloc(devcount * sizeof(*bst), M_TEMP, M_WAITOK | M_ZERO);
140     bi = kmalloc(devcount * sizeof(*bi), M_TEMP, M_WAITOK | M_ZERO);
141     bif = kmalloc(sizeof(*bif), M_TEMP, M_WAITOK | M_ZERO);
142
143     /*
144      * Pass 1:  for each battery that is present and valid, get its status,
145      * calculate percent capacity remaining, and sum all the current
146      * discharge rates.
147      */
148     dev_idx = -1;
149     batt_stat = valid_rate = valid_units = 0;
150     for (i = 0; i < devcount; i++) {
151         /* Default info for every battery is "not present". */
152         acpi_reset_battinfo(&bi[i]);
153
154         /*
155          * Find the device.  Since devcount is in terms of max units, this
156          * may be a sparse array so skip devices that aren't present.
157          */
158         batt_dev = devclass_get_device(batt_dc, i);
159         if (batt_dev == NULL)
160             continue;
161
162         /* If examining a specific battery and this is it, record its index. */
163         if (dev != NULL && dev == batt_dev)
164             dev_idx = i;
165
166         /*
167          * Be sure we can get various info from the battery.  Note that
168          * acpi_BatteryIsPresent() is not enough because smart batteries only
169          * return that the device is present.
170          */
171         if (!acpi_BatteryIsPresent(batt_dev) ||
172             ACPI_BATT_GET_STATUS(batt_dev, &bst[i]) != 0 ||
173             ACPI_BATT_GET_INFO(batt_dev, bif) != 0)
174             continue;
175
176         /* If a battery is not installed, we sometimes get strange values. */
177         if (!acpi_battery_bst_valid(&bst[i]) ||
178             !acpi_battery_bif_valid(bif))
179             continue;
180
181         /*
182          * Record current state.  If both charging and discharging are set,
183          * ignore the charging flag.
184          */
185         valid_units++;
186         if ((bst[i].state & ACPI_BATT_STAT_DISCHARG) != 0)
187             bst[i].state &= ~ACPI_BATT_STAT_CHARGING;
188         batt_stat |= bst[i].state;
189         bi[i].state = bst[i].state;
190
191         /*
192          * If the battery info is in terms of mA, convert to mW by
193          * multiplying by the design voltage.  If the design voltage
194          * is 0 (due to some error reading the battery), skip this
195          * conversion.
196          */
197         if (bif->units == ACPI_BIF_UNITS_MA && bif->dvol != 0) {
198             bst[i].rate = (bst[i].rate * bif->dvol) / 1000;
199             bst[i].cap = (bst[i].cap * bif->dvol) / 1000;
200             bif->lfcap = (bif->lfcap * bif->dvol) / 1000;
201         }
202
203         /* Calculate percent capacity remaining. */
204         bi[i].cap = (100 * bst[i].cap) / bif->lfcap;
205
206         /*
207          * Some laptops report the "design-capacity" instead of the
208          * "real-capacity" when the battery is fully charged.  That breaks
209          * the above arithmetic as it needs to be 100% maximum.
210          */
211         if (bi[i].cap > 100)
212             bi[i].cap = 100;
213
214         /*
215          * On systems with more than one battery, they may get used
216          * sequentially, thus bst.rate may only signify the one currently
217          * in use.  For the remaining batteries, bst.rate will be zero,
218          * which makes it impossible to calculate the total remaining time.
219          * Therefore, we sum the bst.rate for batteries in the discharging
220          * state and use the sum to calculate the total remaining time.
221          */
222         if (bst[i].rate != ACPI_BATT_UNKNOWN &&
223             (bst[i].state & ACPI_BATT_STAT_DISCHARG) != 0)
224             valid_rate += bst[i].rate;
225     }
226
227     /* If the caller asked for a device but we didn't find it, error. */
228     if (dev != NULL && dev_idx == -1) {
229         error = ENXIO;
230         goto out;
231     }
232
233     /* Pass 2:  calculate capacity and remaining time for all batteries. */
234     total_cap = total_min = 0;
235     for (i = 0; i < devcount; i++) {
236         /*
237          * If any batteries are discharging, use the sum of the bst.rate
238          * values.  Otherwise, we are on AC power, and there is infinite
239          * time remaining for this battery until we go offline.
240          */
241         if (valid_rate > 0)
242             bi[i].min = (60 * bst[i].cap) / valid_rate;
243         else
244             bi[i].min = 0;
245         total_min += bi[i].min;
246
247         /* If this battery is not present, don't use its capacity. */
248         if (bi[i].cap != -1)
249             total_cap += bi[i].cap;
250     }
251
252     /*
253      * Return total battery percent and time remaining.  If there are
254      * no valid batteries, report values as unknown.
255      */
256     if (valid_units > 0) {
257         if (dev == NULL) {
258             battinfo->cap = total_cap / valid_units;
259             battinfo->min = total_min;
260             battinfo->state = batt_stat;
261             battinfo->rate = valid_rate;
262         } else {
263             battinfo->cap = bi[dev_idx].cap;
264             battinfo->min = bi[dev_idx].min;
265             battinfo->state = bi[dev_idx].state;
266             battinfo->rate = bst[dev_idx].rate;
267         }
268
269         /*
270          * If the queried battery has no discharge rate or is charging,
271          * report that we don't know the remaining time.
272          */
273         if (valid_rate == 0 || (battinfo->state & ACPI_BATT_STAT_CHARGING))
274             battinfo->min = -1;
275     } else
276         acpi_reset_battinfo(battinfo);
277
278     error = 0;
279
280 out:
281     if (bi)
282         kfree(bi, M_TEMP);
283     if (bif)
284         kfree(bif, M_TEMP);
285     if (bst)
286         kfree(bst, M_TEMP);
287     return (error);
288 }
289
290 static void
291 acpi_reset_battinfo(struct acpi_battinfo *info)
292 {
293     info->cap = -1;
294     info->min = -1;
295     info->state = ACPI_BATT_STAT_NOT_PRESENT;
296     info->rate = -1;
297 }
298
299 /* Make string printable, removing invalid chars. */
300 static void
301 acpi_battery_clean_str(char *str, int len)
302 {
303     int i;
304
305     for (i = 0; i < len && *str != '\0'; i++, str++) {
306         if (!isprint(*str))
307             *str = '?';
308     }
309
310     /* NUL-terminate the string if we reached the end. */
311     if (i == len)
312         *str = '\0';
313 }
314
315 /*
316  * The battery interface deals with devices and methods but userland
317  * expects a logical unit number.  Convert a logical unit to a device_t.
318  */
319 static device_t
320 acpi_battery_find_dev(u_int logical_unit)
321 {
322     int found_unit, i, maxunit;
323     device_t dev;
324     devclass_t batt_dc;
325
326     dev = NULL;
327     found_unit = 0;
328     batt_dc = devclass_find("battery");
329     maxunit = devclass_get_maxunit(batt_dc);
330     for (i = 0; i < maxunit; i++) {
331         dev = devclass_get_device(batt_dc, i);
332         if (dev == NULL)
333             continue;
334         if (logical_unit == found_unit)
335             break;
336         found_unit++;
337         dev = NULL;
338     }
339
340     return (dev);
341 }
342
343 static int
344 acpi_battery_ioctl(u_long cmd, caddr_t addr, void *arg)
345 {
346     union acpi_battery_ioctl_arg *ioctl_arg;
347     int error, unit;
348     device_t dev;
349
350     /* For commands that use the ioctl_arg struct, validate it first. */
351     error = ENXIO;
352     unit = 0;
353     dev = NULL;
354     ioctl_arg = NULL;
355     if (IOCPARM_LEN(cmd) == sizeof(*ioctl_arg)) {
356         ioctl_arg = (union acpi_battery_ioctl_arg *)addr;
357         unit = ioctl_arg->unit;
358         if (unit != ACPI_BATTERY_ALL_UNITS)
359             dev = acpi_battery_find_dev(unit);
360     }
361
362     /*
363      * No security check required: information retrieval only.  If
364      * new functions are added here, a check might be required.
365      */
366     switch (cmd) {
367     case ACPIIO_BATT_GET_UNITS:
368         *(int *)addr = acpi_battery_get_units();
369         error = 0;
370         break;
371     case ACPIIO_BATT_GET_BATTINFO:
372         if (dev != NULL || unit == ACPI_BATTERY_ALL_UNITS) {
373             bzero(&ioctl_arg->battinfo, sizeof(ioctl_arg->battinfo));
374             error = acpi_battery_get_battinfo(dev, &ioctl_arg->battinfo);
375         }
376         break;
377     case ACPIIO_BATT_GET_BIF:
378         if (dev != NULL) {
379             bzero(&ioctl_arg->bif, sizeof(ioctl_arg->bif));
380             error = ACPI_BATT_GET_INFO(dev, &ioctl_arg->bif);
381
382             /*
383              * Remove invalid characters.  Perhaps this should be done
384              * within a convenience function so all callers get the
385              * benefit.
386              */
387             acpi_battery_clean_str(ioctl_arg->bif.model,
388                 sizeof(ioctl_arg->bif.model));
389             acpi_battery_clean_str(ioctl_arg->bif.serial,
390                 sizeof(ioctl_arg->bif.serial));
391             acpi_battery_clean_str(ioctl_arg->bif.type,
392                 sizeof(ioctl_arg->bif.type));
393             acpi_battery_clean_str(ioctl_arg->bif.oeminfo,
394                 sizeof(ioctl_arg->bif.oeminfo));
395         }
396         break;
397     case ACPIIO_BATT_GET_BST:
398         if (dev != NULL) {
399             bzero(&ioctl_arg->bst, sizeof(ioctl_arg->bst));
400             error = ACPI_BATT_GET_STATUS(dev, &ioctl_arg->bst);
401         }
402         break;
403     default:
404         error = EINVAL;
405     }
406
407     return (error);
408 }
409
410 static int
411 acpi_battery_sysctl(SYSCTL_HANDLER_ARGS)
412 {
413     int val, error;
414
415     acpi_battery_get_battinfo(NULL, &acpi_battery_battinfo);
416     val = *(u_int *)oidp->oid_arg1;
417     error = sysctl_handle_int(oidp, &val, 0, req);
418     return (error);
419 }
420
421 static int
422 acpi_battery_units_sysctl(SYSCTL_HANDLER_ARGS)
423 {
424     int count, error;
425
426     count = acpi_battery_get_units();
427     error = sysctl_handle_int(oidp, &count, 0, req);
428     return (error);
429 }
430
431 static int
432 acpi_battery_init(void)
433 {
434     struct acpi_softc   *sc;
435     device_t             dev;
436     int                  error;
437
438     error = ENXIO;
439     dev = devclass_get_device(devclass_find("acpi"), 0);
440     if (dev == NULL)
441         goto out;
442     sc = device_get_softc(dev);
443
444     error = acpi_register_ioctl(ACPIIO_BATT_GET_UNITS, acpi_battery_ioctl,
445         NULL);
446     if (error != 0)
447         goto out;
448     error = acpi_register_ioctl(ACPIIO_BATT_GET_BATTINFO, acpi_battery_ioctl,
449         NULL);
450     if (error != 0)
451         goto out;
452     error = acpi_register_ioctl(ACPIIO_BATT_GET_BIF, acpi_battery_ioctl, NULL);
453     if (error != 0)
454         goto out;
455     error = acpi_register_ioctl(ACPIIO_BATT_GET_BST, acpi_battery_ioctl, NULL);
456     if (error != 0)
457         goto out;
458
459     sysctl_ctx_init(&acpi_battery_sysctl_ctx);
460     acpi_battery_sysctl_tree = SYSCTL_ADD_NODE(&acpi_battery_sysctl_ctx,
461         SYSCTL_CHILDREN(sc->acpi_sysctl_tree), OID_AUTO, "battery", CTLFLAG_RD,
462         0, "battery status and info");
463     SYSCTL_ADD_PROC(&acpi_battery_sysctl_ctx,
464         SYSCTL_CHILDREN(acpi_battery_sysctl_tree),
465         OID_AUTO, "life", CTLTYPE_INT | CTLFLAG_RD,
466         &acpi_battery_battinfo.cap, 0, acpi_battery_sysctl, "I",
467         "percent capacity remaining");
468     SYSCTL_ADD_PROC(&acpi_battery_sysctl_ctx,
469         SYSCTL_CHILDREN(acpi_battery_sysctl_tree),
470         OID_AUTO, "time", CTLTYPE_INT | CTLFLAG_RD,
471         &acpi_battery_battinfo.min, 0, acpi_battery_sysctl, "I",
472         "remaining time in minutes");
473     SYSCTL_ADD_PROC(&acpi_battery_sysctl_ctx,
474         SYSCTL_CHILDREN(acpi_battery_sysctl_tree),
475         OID_AUTO, "state", CTLTYPE_INT | CTLFLAG_RD,
476         &acpi_battery_battinfo.state, 0, acpi_battery_sysctl, "I",
477         "current status flags");
478     SYSCTL_ADD_PROC(&acpi_battery_sysctl_ctx,
479         SYSCTL_CHILDREN(acpi_battery_sysctl_tree),
480         OID_AUTO, "units", CTLTYPE_INT | CTLFLAG_RD,
481         NULL, 0, acpi_battery_units_sysctl, "I", "number of batteries");
482     SYSCTL_ADD_INT(&acpi_battery_sysctl_ctx,
483         SYSCTL_CHILDREN(acpi_battery_sysctl_tree),
484         OID_AUTO, "info_expire", CTLFLAG_RW,
485         &acpi_battery_info_expire, 0,
486         "time in seconds until info is refreshed");
487
488     acpi_batteries_initted = TRUE;
489
490 out:
491     if (error != 0) {
492         acpi_deregister_ioctl(ACPIIO_BATT_GET_UNITS, acpi_battery_ioctl);
493         acpi_deregister_ioctl(ACPIIO_BATT_GET_BATTINFO, acpi_battery_ioctl);
494         acpi_deregister_ioctl(ACPIIO_BATT_GET_BIF, acpi_battery_ioctl);
495         acpi_deregister_ioctl(ACPIIO_BATT_GET_BST, acpi_battery_ioctl);
496     }
497     return (error);
498 }