1/*-
2 * Copyright (c) 2005 Nate Lawson
3 * Copyright (c) 2000 Munehiro Matsuda
4 * Copyright (c) 2000 Takanori Watanabe
5 * Copyright (c) 2000 Mitsuru IWASAKI <iwasaki@FreeBSD.org>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD$");
32
33#include "opt_acpi.h"
34#include <sys/param.h>
35#include <sys/kernel.h>
36#include <sys/module.h>
37#include <sys/bus.h>
38#include <sys/ioccom.h>
39
40#include <machine/bus.h>
41#include <sys/rman.h>
42#include <sys/malloc.h>
43
44#include <contrib/dev/acpica/include/acpi.h>
45
46#include <dev/acpica/acpivar.h>
47#include <dev/acpica/acpiio.h>
48
49static MALLOC_DEFINE(M_ACPICMBAT, "acpicmbat",
50    "ACPI control method battery data");
51
52/* Number of times to retry initialization before giving up. */
53#define ACPI_CMBAT_RETRY_MAX	6
54
55/* Check the battery once a minute. */
56#define	CMBAT_POLLRATE		(60 * hz)
57
58/* Hooks for the ACPI CA debugging infrastructure */
59#define	_COMPONENT	ACPI_BATTERY
60ACPI_MODULE_NAME("BATTERY")
61
62#define	ACPI_BATTERY_BST_CHANGE	0x80
63#define	ACPI_BATTERY_BIF_CHANGE	0x81
64
65struct acpi_cmbat_softc {
66    device_t	    dev;
67    int		    flags;
68
69    struct acpi_bif bif;
70    struct acpi_bst bst;
71    struct timespec bst_lastupdated;
72};
73
74ACPI_SERIAL_DECL(cmbat, "ACPI cmbat");
75
76static int		acpi_cmbat_probe(device_t dev);
77static int		acpi_cmbat_attach(device_t dev);
78static int		acpi_cmbat_detach(device_t dev);
79static int		acpi_cmbat_resume(device_t dev);
80static void		acpi_cmbat_notify_handler(ACPI_HANDLE h, UINT32 notify,
81			    void *context);
82static int		acpi_cmbat_info_expired(struct timespec *lastupdated);
83static void		acpi_cmbat_info_updated(struct timespec *lastupdated);
84static void		acpi_cmbat_get_bst(void *arg);
85static void		acpi_cmbat_get_bif_task(void *arg);
86static void		acpi_cmbat_get_bif(void *arg);
87static int		acpi_cmbat_bst(device_t dev, struct acpi_bst *bstp);
88static int		acpi_cmbat_bif(device_t dev, struct acpi_bif *bifp);
89static void		acpi_cmbat_init_battery(void *arg);
90
91static device_method_t acpi_cmbat_methods[] = {
92    /* Device interface */
93    DEVMETHOD(device_probe,	acpi_cmbat_probe),
94    DEVMETHOD(device_attach,	acpi_cmbat_attach),
95    DEVMETHOD(device_detach,	acpi_cmbat_detach),
96    DEVMETHOD(device_resume,	acpi_cmbat_resume),
97
98    /* ACPI battery interface */
99    DEVMETHOD(acpi_batt_get_info, acpi_cmbat_bif),
100    DEVMETHOD(acpi_batt_get_status, acpi_cmbat_bst),
101
102    DEVMETHOD_END
103};
104
105static driver_t acpi_cmbat_driver = {
106    "battery",
107    acpi_cmbat_methods,
108    sizeof(struct acpi_cmbat_softc),
109};
110
111static devclass_t acpi_cmbat_devclass;
112DRIVER_MODULE(acpi_cmbat, acpi, acpi_cmbat_driver, acpi_cmbat_devclass, 0, 0);
113MODULE_DEPEND(acpi_cmbat, acpi, 1, 1, 1);
114
115static int
116acpi_cmbat_probe(device_t dev)
117{
118    static char *cmbat_ids[] = { "PNP0C0A", NULL };
119
120    if (acpi_disabled("cmbat") ||
121	ACPI_ID_PROBE(device_get_parent(dev), dev, cmbat_ids) == NULL)
122	return (ENXIO);
123
124    device_set_desc(dev, "ACPI Control Method Battery");
125    return (0);
126}
127
128static int
129acpi_cmbat_attach(device_t dev)
130{
131    int		error;
132    ACPI_HANDLE	handle;
133    struct acpi_cmbat_softc *sc;
134
135    sc = device_get_softc(dev);
136    handle = acpi_get_handle(dev);
137    sc->dev = dev;
138
139    timespecclear(&sc->bst_lastupdated);
140
141    error = acpi_battery_register(dev);
142    if (error != 0) {
143    	device_printf(dev, "registering battery failed\n");
144	return (error);
145    }
146
147    /*
148     * Install a system notify handler in addition to the device notify.
149     * Toshiba notebook uses this alternate notify for its battery.
150     */
151    AcpiInstallNotifyHandler(handle, ACPI_ALL_NOTIFY,
152	acpi_cmbat_notify_handler, dev);
153
154    AcpiOsExecute(OSL_NOTIFY_HANDLER, acpi_cmbat_init_battery, dev);
155
156    return (0);
157}
158
159static int
160acpi_cmbat_detach(device_t dev)
161{
162    ACPI_HANDLE	handle;
163
164    handle = acpi_get_handle(dev);
165    AcpiRemoveNotifyHandler(handle, ACPI_ALL_NOTIFY, acpi_cmbat_notify_handler);
166    acpi_battery_remove(dev);
167    return (0);
168}
169
170static int
171acpi_cmbat_resume(device_t dev)
172{
173
174    AcpiOsExecute(OSL_NOTIFY_HANDLER, acpi_cmbat_init_battery, dev);
175    return (0);
176}
177
178static void
179acpi_cmbat_notify_handler(ACPI_HANDLE h, UINT32 notify, void *context)
180{
181    struct acpi_cmbat_softc *sc;
182    device_t dev;
183
184    dev = (device_t)context;
185    sc = device_get_softc(dev);
186
187    switch (notify) {
188    case ACPI_NOTIFY_DEVICE_CHECK:
189    case ACPI_BATTERY_BST_CHANGE:
190	/*
191	 * Clear the last updated time.  The next call to retrieve the
192	 * battery status will get the new value for us.
193	 */
194	timespecclear(&sc->bst_lastupdated);
195	break;
196    case ACPI_NOTIFY_BUS_CHECK:
197    case ACPI_BATTERY_BIF_CHANGE:
198	/*
199	 * Queue a callback to get the current battery info from thread
200	 * context.  It's not safe to block in a notify handler.
201	 */
202	AcpiOsExecute(OSL_NOTIFY_HANDLER, acpi_cmbat_get_bif_task, dev);
203	break;
204    }
205
206    acpi_UserNotify("CMBAT", h, notify);
207}
208
209static int
210acpi_cmbat_info_expired(struct timespec *lastupdated)
211{
212    struct timespec	curtime;
213
214    ACPI_SERIAL_ASSERT(cmbat);
215
216    if (lastupdated == NULL)
217	return (TRUE);
218    if (!timespecisset(lastupdated))
219	return (TRUE);
220
221    getnanotime(&curtime);
222    timespecsub(&curtime, lastupdated);
223    return (curtime.tv_sec < 0 ||
224	    curtime.tv_sec > acpi_battery_get_info_expire());
225}
226
227static void
228acpi_cmbat_info_updated(struct timespec *lastupdated)
229{
230
231    ACPI_SERIAL_ASSERT(cmbat);
232
233    if (lastupdated != NULL)
234	getnanotime(lastupdated);
235}
236
237static void
238acpi_cmbat_get_bst(void *arg)
239{
240    struct acpi_cmbat_softc *sc;
241    ACPI_STATUS	as;
242    ACPI_OBJECT	*res;
243    ACPI_HANDLE	h;
244    ACPI_BUFFER	bst_buffer;
245    device_t dev;
246
247    ACPI_SERIAL_ASSERT(cmbat);
248
249    dev = arg;
250    sc = device_get_softc(dev);
251    h = acpi_get_handle(dev);
252    bst_buffer.Pointer = NULL;
253    bst_buffer.Length = ACPI_ALLOCATE_BUFFER;
254
255    if (!acpi_cmbat_info_expired(&sc->bst_lastupdated))
256	goto end;
257
258    as = AcpiEvaluateObject(h, "_BST", NULL, &bst_buffer);
259    if (ACPI_FAILURE(as)) {
260	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
261		    "error fetching current battery status -- %s\n",
262		    AcpiFormatException(as));
263	goto end;
264    }
265
266    res = (ACPI_OBJECT *)bst_buffer.Pointer;
267    if (!ACPI_PKG_VALID(res, 4)) {
268	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
269		    "battery status corrupted\n");
270	goto end;
271    }
272
273    if (acpi_PkgInt32(res, 0, &sc->bst.state) != 0)
274	goto end;
275    if (acpi_PkgInt32(res, 1, &sc->bst.rate) != 0)
276	goto end;
277    if (acpi_PkgInt32(res, 2, &sc->bst.cap) != 0)
278	goto end;
279    if (acpi_PkgInt32(res, 3, &sc->bst.volt) != 0)
280	goto end;
281    acpi_cmbat_info_updated(&sc->bst_lastupdated);
282
283    /* Clear out undefined/extended bits that might be set by hardware. */
284    sc->bst.state &= ACPI_BATT_STAT_BST_MASK;
285    if ((sc->bst.state & ACPI_BATT_STAT_INVALID) == ACPI_BATT_STAT_INVALID)
286	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
287	    "battery reports simultaneous charging and discharging\n");
288
289    /* XXX If all batteries are critical, perhaps we should suspend. */
290    if (sc->bst.state & ACPI_BATT_STAT_CRITICAL) {
291    	if ((sc->flags & ACPI_BATT_STAT_CRITICAL) == 0) {
292	    sc->flags |= ACPI_BATT_STAT_CRITICAL;
293	    device_printf(dev, "critically low charge!\n");
294	}
295    } else
296	sc->flags &= ~ACPI_BATT_STAT_CRITICAL;
297
298end:
299    if (bst_buffer.Pointer != NULL)
300	AcpiOsFree(bst_buffer.Pointer);
301}
302
303/* XXX There should be a cleaner way to do this locking. */
304static void
305acpi_cmbat_get_bif_task(void *arg)
306{
307
308    ACPI_SERIAL_BEGIN(cmbat);
309    acpi_cmbat_get_bif(arg);
310    ACPI_SERIAL_END(cmbat);
311}
312
313static void
314acpi_cmbat_get_bif(void *arg)
315{
316    struct acpi_cmbat_softc *sc;
317    ACPI_STATUS	as;
318    ACPI_OBJECT	*res;
319    ACPI_HANDLE	h;
320    ACPI_BUFFER	bif_buffer;
321    device_t dev;
322
323    ACPI_SERIAL_ASSERT(cmbat);
324
325    dev = arg;
326    sc = device_get_softc(dev);
327    h = acpi_get_handle(dev);
328    bif_buffer.Pointer = NULL;
329    bif_buffer.Length = ACPI_ALLOCATE_BUFFER;
330
331    as = AcpiEvaluateObject(h, "_BIF", NULL, &bif_buffer);
332    if (ACPI_FAILURE(as)) {
333	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
334		    "error fetching current battery info -- %s\n",
335		    AcpiFormatException(as));
336	goto end;
337    }
338
339    res = (ACPI_OBJECT *)bif_buffer.Pointer;
340    if (!ACPI_PKG_VALID(res, 13)) {
341	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
342		    "battery info corrupted\n");
343	goto end;
344    }
345
346    if (acpi_PkgInt32(res, 0, &sc->bif.units) != 0)
347	goto end;
348    if (acpi_PkgInt32(res, 1, &sc->bif.dcap) != 0)
349	goto end;
350    if (acpi_PkgInt32(res, 2, &sc->bif.lfcap) != 0)
351	goto end;
352    if (acpi_PkgInt32(res, 3, &sc->bif.btech) != 0)
353	goto end;
354    if (acpi_PkgInt32(res, 4, &sc->bif.dvol) != 0)
355	goto end;
356    if (acpi_PkgInt32(res, 5, &sc->bif.wcap) != 0)
357	goto end;
358    if (acpi_PkgInt32(res, 6, &sc->bif.lcap) != 0)
359	goto end;
360    if (acpi_PkgInt32(res, 7, &sc->bif.gra1) != 0)
361	goto end;
362    if (acpi_PkgInt32(res, 8, &sc->bif.gra2) != 0)
363	goto end;
364    if (acpi_PkgStr(res,  9, sc->bif.model, ACPI_CMBAT_MAXSTRLEN) != 0)
365	goto end;
366    if (acpi_PkgStr(res, 10, sc->bif.serial, ACPI_CMBAT_MAXSTRLEN) != 0)
367	goto end;
368    if (acpi_PkgStr(res, 11, sc->bif.type, ACPI_CMBAT_MAXSTRLEN) != 0)
369	goto end;
370    if (acpi_PkgStr(res, 12, sc->bif.oeminfo, ACPI_CMBAT_MAXSTRLEN) != 0)
371	goto end;
372
373end:
374    if (bif_buffer.Pointer != NULL)
375	AcpiOsFree(bif_buffer.Pointer);
376}
377
378static int
379acpi_cmbat_bif(device_t dev, struct acpi_bif *bifp)
380{
381    struct acpi_cmbat_softc *sc;
382
383    sc = device_get_softc(dev);
384
385    /*
386     * Just copy the data.  The only value that should change is the
387     * last-full capacity, so we only update when we get a notify that says
388     * the info has changed.  Many systems apparently take a long time to
389     * process a _BIF call so we avoid it if possible.
390     */
391    ACPI_SERIAL_BEGIN(cmbat);
392    bifp->units = sc->bif.units;
393    bifp->dcap = sc->bif.dcap;
394    bifp->lfcap = sc->bif.lfcap;
395    bifp->btech = sc->bif.btech;
396    bifp->dvol = sc->bif.dvol;
397    bifp->wcap = sc->bif.wcap;
398    bifp->lcap = sc->bif.lcap;
399    bifp->gra1 = sc->bif.gra1;
400    bifp->gra2 = sc->bif.gra2;
401    strncpy(bifp->model, sc->bif.model, sizeof(sc->bif.model));
402    strncpy(bifp->serial, sc->bif.serial, sizeof(sc->bif.serial));
403    strncpy(bifp->type, sc->bif.type, sizeof(sc->bif.type));
404    strncpy(bifp->oeminfo, sc->bif.oeminfo, sizeof(sc->bif.oeminfo));
405    ACPI_SERIAL_END(cmbat);
406
407    return (0);
408}
409
410static int
411acpi_cmbat_bst(device_t dev, struct acpi_bst *bstp)
412{
413    struct acpi_cmbat_softc *sc;
414
415    sc = device_get_softc(dev);
416
417    ACPI_SERIAL_BEGIN(cmbat);
418    if (acpi_BatteryIsPresent(dev)) {
419	acpi_cmbat_get_bst(dev);
420	bstp->state = sc->bst.state;
421	bstp->rate = sc->bst.rate;
422	bstp->cap = sc->bst.cap;
423	bstp->volt = sc->bst.volt;
424    } else
425	bstp->state = ACPI_BATT_STAT_NOT_PRESENT;
426    ACPI_SERIAL_END(cmbat);
427
428    return (0);
429}
430
431static void
432acpi_cmbat_init_battery(void *arg)
433{
434    struct acpi_cmbat_softc *sc;
435    int		retry, valid;
436    device_t	dev;
437
438    dev = (device_t)arg;
439    sc = device_get_softc(dev);
440    ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
441		"battery initialization start\n");
442
443    /*
444     * Try repeatedly to get valid data from the battery.  Since the
445     * embedded controller isn't always ready just after boot, we may have
446     * to wait a while.
447     */
448    for (retry = 0; retry < ACPI_CMBAT_RETRY_MAX; retry++, AcpiOsSleep(10000)) {
449	/* batteries on DOCK can be ejected w/ DOCK during retrying */
450	if (!device_is_attached(dev))
451	    return;
452
453	if (!acpi_BatteryIsPresent(dev))
454	    continue;
455
456	/*
457	 * Only query the battery if this is the first try or the specific
458	 * type of info is still invalid.
459	 */
460	ACPI_SERIAL_BEGIN(cmbat);
461	if (retry == 0 || !acpi_battery_bst_valid(&sc->bst)) {
462	    timespecclear(&sc->bst_lastupdated);
463	    acpi_cmbat_get_bst(dev);
464	}
465	if (retry == 0 || !acpi_battery_bif_valid(&sc->bif))
466	    acpi_cmbat_get_bif(dev);
467
468	valid = acpi_battery_bst_valid(&sc->bst) &&
469	    acpi_battery_bif_valid(&sc->bif);
470	ACPI_SERIAL_END(cmbat);
471
472	if (valid)
473	    break;
474    }
475
476    if (retry == ACPI_CMBAT_RETRY_MAX) {
477	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
478		    "battery initialization failed, giving up\n");
479    } else {
480	ACPI_VPRINT(dev, acpi_device_get_parent_softc(dev),
481		    "battery initialization done, tried %d times\n", retry + 1);
482    }
483}
484