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