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