apm.c revision 50107
1/*
2 * APM (Advanced Power Management) BIOS Device Driver
3 *
4 * Copyright (c) 1994 UKAI, Fumitoshi.
5 * Copyright (c) 1994-1995 by HOSOKAWA, Tatsumi <hosokawa@jp.FreeBSD.org>
6 * Copyright (c) 1996 Nate Williams <nate@FreeBSD.org>
7 * Copyright (c) 1997 Poul-Henning Kamp <phk@FreeBSD.org>
8 *
9 * This software may be used, modified, copied, and distributed, in
10 * both source and binary form provided that the above copyright and
11 * these terms are retained. Under no circumstances is the author
12 * responsible for the proper functioning of this software, nor does
13 * the author assume any responsibility for damages incurred with its
14 * use.
15 *
16 * Sep, 1994	Implemented on FreeBSD 1.1.5.1R (Toshiba AVS001WD)
17 *
18 *	$Id: apm.c,v 1.99 1999/08/14 18:39:40 iwasaki Exp $
19 */
20
21#include "opt_devfs.h"
22
23#include <sys/param.h>
24#include <sys/systm.h>
25#include <sys/eventhandler.h>
26#include <sys/conf.h>
27#include <sys/kernel.h>
28#ifdef DEVFS
29#include <sys/devfsext.h>
30#endif /*DEVFS*/
31#include <sys/time.h>
32#include <sys/reboot.h>
33#include <sys/bus.h>
34#include <sys/select.h>
35#include <sys/poll.h>
36#include <sys/fcntl.h>
37#include <sys/proc.h>
38#include <sys/uio.h>
39#include <sys/signalvar.h>
40#include <machine/apm_bios.h>
41#include <machine/segments.h>
42#include <machine/clock.h>
43#include <vm/vm.h>
44#include <vm/vm_param.h>
45#include <vm/pmap.h>
46#include <sys/syslog.h>
47
48#include <machine/pc/bios.h>
49#include <machine/vm86.h>
50
51static int apm_display __P((int newstate));
52static void apm_resume __P((void));
53static int apm_bioscall(void);
54static int apm_check_function_supported __P((u_int version, u_int func));
55
56static u_long	apm_version;
57
58#define APM_NEVENTS 16
59#define APM_NPMEV   13
60
61int	apm_evindex;
62
63/* static data */
64struct apm_softc {
65	int	initialized, active, bios_busy;
66	int	always_halt_cpu, slow_idle_cpu;
67	int	disabled, disengaged;
68	u_int	minorversion, majorversion;
69	u_int	intversion, connectmode;
70	struct bios_args bios;
71	struct apmhook sc_suspend;
72	struct apmhook sc_resume;
73	struct selinfo sc_rsel;
74	int	sc_flags;
75	int	event_count;
76	int	event_ptr;
77	struct	apm_event_info event_list[APM_NEVENTS];
78	u_char	event_filter[APM_NPMEV];
79#ifdef DEVFS
80	void 	*sc_devfs_token;
81#endif
82};
83#define	SCFLAG_ONORMAL	0x0000001
84#define	SCFLAG_OCTL	0x0000002
85#define	SCFLAG_OPEN	(SCFLAG_ONORMAL|SCFLAG_OCTL)
86
87#define APMDEV(dev)	(minor(dev)&0x0f)
88#define APMDEV_NORMAL	0
89#define APMDEV_CTL	8
90
91static struct apm_softc apm_softc;
92static struct apmhook	*hook[NAPM_HOOK];		/* XXX */
93
94#define is_enabled(foo) ((foo) ? "enabled" : "disabled")
95
96/* Map version number to integer (keeps ordering of version numbers) */
97#define INTVERSION(major, minor)	((major)*100 + (minor))
98
99static struct callout_handle apm_timeout_ch =
100    CALLOUT_HANDLE_INITIALIZER(&apm_timeout_ch);
101
102static timeout_t apm_timeout;
103static d_open_t apmopen;
104static d_close_t apmclose;
105static d_write_t apmwrite;
106static d_ioctl_t apmioctl;
107static d_poll_t apmpoll;
108
109#define CDEV_MAJOR 39
110static struct cdevsw apm_cdevsw = {
111	/* open */	apmopen,
112	/* close */	apmclose,
113	/* read */	noread,
114	/* write */	apmwrite,
115	/* ioctl */	apmioctl,
116	/* stop */	nostop,
117	/* reset */	noreset,
118	/* devtotty */	nodevtotty,
119	/* poll */	apmpoll,
120	/* mmap */	nommap,
121	/* strategy */	nostrategy,
122	/* name */	"apm",
123	/* parms */	noparms,
124	/* maj */	CDEV_MAJOR,
125	/* dump */	nodump,
126	/* psize */	nopsize,
127	/* flags */	0,
128	/* maxio */	0,
129	/* bmaj */	-1
130};
131
132/*
133 * return  0 if the function successfull,
134 * return  1 if the function unsuccessfull,
135 * return -1 if the function unsupported.
136 */
137static int
138apm_bioscall(void)
139{
140	struct apm_softc *sc = &apm_softc;
141	int errno = 0;
142	u_int apm_func = sc->bios.r.eax & 0xff;
143
144	if (!apm_check_function_supported(sc->intversion, apm_func)) {
145#ifdef APM_DEBUG
146		printf("apm_bioscall: function 0x%x is not supported in v%d.%d\n",
147			apm_func, sc->majorversion, sc->minorversion);
148#endif
149		return (-1);
150	}
151
152	sc->bios_busy = 1;
153	if (sc->connectmode == APM_PROT32CONNECT) {
154		set_bios_selectors(&sc->bios.seg,
155				   BIOSCODE_FLAG | BIOSDATA_FLAG);
156		errno = bios32(&sc->bios.r,
157			       sc->bios.entry, GSEL(GBIOSCODE32_SEL, SEL_KPL));
158	} else {
159		errno = bios16(&sc->bios, NULL);
160	}
161	sc->bios_busy = 0;
162	return (errno);
163}
164
165/* check whether APM function is supported (1)  or not (0). */
166static int
167apm_check_function_supported(u_int version, u_int func)
168{
169	/* except driver version */
170	if (func == APM_DRVVERSION) {
171		return (1);
172	}
173
174	switch (version) {
175	case INTVERSION(1, 0):
176		if (func > APM_GETPMEVENT) {
177			return (0); /* not supported */
178		}
179		break;
180	case INTVERSION(1, 1):
181		if (func > APM_ENGAGEDISENGAGEPM &&
182		    func < APM_OEMFUNC) {
183			return (0); /* not supported */
184		}
185		break;
186	case INTVERSION(1, 2):
187		break;
188	}
189
190	return (1); /* supported */
191}
192
193/* enable/disable power management */
194static int
195apm_enable_disable_pm(int enable)
196{
197	struct apm_softc *sc = &apm_softc;
198
199	sc->bios.r.eax = (APM_BIOS << 8) | APM_ENABLEDISABLEPM;
200
201	if (sc->intversion >= INTVERSION(1, 1))
202		sc->bios.r.ebx  = PMDV_ALLDEV;
203	else
204		sc->bios.r.ebx  = 0xffff;	/* APM version 1.0 only */
205	sc->bios.r.ecx  = enable;
206	sc->bios.r.edx = 0;
207	return (apm_bioscall());
208}
209
210/* register driver version (APM 1.1 or later) */
211static int
212apm_driver_version(int version)
213{
214	struct apm_softc *sc = &apm_softc;
215
216	sc->bios.r.eax = (APM_BIOS << 8) | APM_DRVVERSION;
217	sc->bios.r.ebx  = 0x0;
218	sc->bios.r.ecx  = version;
219	sc->bios.r.edx = 0;
220
221	if (apm_bioscall() == 0 && sc->bios.r.eax == version)
222		return (0);
223
224	/* Some old BIOSes don't return the connection version in %ax. */
225	if (sc->bios.r.eax == ((APM_BIOS << 8) | APM_DRVVERSION))
226		return (0);
227
228	return (1);
229}
230
231/* engage/disengage power management (APM 1.1 or later) */
232static int
233apm_engage_disengage_pm(int engage)
234{
235	struct apm_softc *sc = &apm_softc;
236
237	sc->bios.r.eax = (APM_BIOS << 8) | APM_ENGAGEDISENGAGEPM;
238	sc->bios.r.ebx = PMDV_ALLDEV;
239	sc->bios.r.ecx = engage;
240	sc->bios.r.edx = 0;
241	return (apm_bioscall());
242}
243
244/* get PM event */
245static u_int
246apm_getevent(void)
247{
248	struct apm_softc *sc = &apm_softc;
249
250	sc->bios.r.eax = (APM_BIOS << 8) | APM_GETPMEVENT;
251
252	sc->bios.r.ebx = 0;
253	sc->bios.r.ecx = 0;
254	sc->bios.r.edx = 0;
255	if (apm_bioscall())
256		return (PMEV_NOEVENT);
257	return (sc->bios.r.ebx & 0xffff);
258}
259
260/* suspend entire system */
261static int
262apm_suspend_system(int state)
263{
264	struct apm_softc *sc = &apm_softc;
265
266	sc->bios.r.eax = (APM_BIOS << 8) | APM_SETPWSTATE;
267	sc->bios.r.ebx = PMDV_ALLDEV;
268	sc->bios.r.ecx = state;
269	sc->bios.r.edx = 0;
270
271	if (apm_bioscall()) {
272 		printf("Entire system suspend failure: errcode = %d\n",
273		       0xff & (sc->bios.r.eax >> 8));
274 		return 1;
275 	}
276 	return 0;
277}
278
279/* Display control */
280/*
281 * Experimental implementation: My laptop machine can't handle this function
282 * If your laptop can control the display via APM, please inform me.
283 *                            HOSOKAWA, Tatsumi <hosokawa@jp.FreeBSD.org>
284 */
285static int
286apm_display(int newstate)
287{
288	struct apm_softc *sc = &apm_softc;
289
290	sc->bios.r.eax = (APM_BIOS << 8) | APM_SETPWSTATE;
291	sc->bios.r.ebx = PMDV_DISP0;
292	sc->bios.r.ecx = newstate ? PMST_APMENABLED:PMST_SUSPEND;
293	sc->bios.r.edx = 0;
294	if (apm_bioscall()) {
295 		printf("Display off failure: errcode = %d\n",
296		       0xff & (sc->bios.r.eax >> 8));
297 		return 1;
298 	}
299 	return 0;
300}
301
302/*
303 * Turn off the entire system.
304 */
305static void
306apm_power_off(void *junk, int howto)
307{
308	struct apm_softc *sc = &apm_softc;
309
310	/* Not halting powering off, or not active */
311	if (!(howto & RB_POWEROFF) || !apm_softc.active)
312		return;
313	sc->bios.r.eax = (APM_BIOS << 8) | APM_SETPWSTATE;
314	sc->bios.r.ebx = PMDV_ALLDEV;
315	sc->bios.r.ecx = PMST_OFF;
316	sc->bios.r.edx = 0;
317	(void) apm_bioscall();
318}
319
320/* APM Battery low handler */
321static void
322apm_battery_low(void)
323{
324	printf("\007\007 * * * BATTERY IS LOW * * * \007\007");
325}
326
327/* APM hook manager */
328static struct apmhook *
329apm_add_hook(struct apmhook **list, struct apmhook *ah)
330{
331	int s;
332	struct apmhook *p, *prev;
333
334#ifdef APM_DEBUG
335	printf("Add hook \"%s\"\n", ah->ah_name);
336#endif
337
338	s = splhigh();
339	if (ah == NULL)
340		panic("illegal apm_hook!");
341	prev = NULL;
342	for (p = *list; p != NULL; prev = p, p = p->ah_next)
343		if (p->ah_order > ah->ah_order)
344			break;
345
346	if (prev == NULL) {
347		ah->ah_next = *list;
348		*list = ah;
349	} else {
350		ah->ah_next = prev->ah_next;
351		prev->ah_next = ah;
352	}
353	splx(s);
354	return ah;
355}
356
357static void
358apm_del_hook(struct apmhook **list, struct apmhook *ah)
359{
360	int s;
361	struct apmhook *p, *prev;
362
363	s = splhigh();
364	prev = NULL;
365	for (p = *list; p != NULL; prev = p, p = p->ah_next)
366		if (p == ah)
367			goto deleteit;
368	panic("Tried to delete unregistered apm_hook.");
369	goto nosuchnode;
370deleteit:
371	if (prev != NULL)
372		prev->ah_next = p->ah_next;
373	else
374		*list = p->ah_next;
375nosuchnode:
376	splx(s);
377}
378
379
380/* APM driver calls some functions automatically */
381static void
382apm_execute_hook(struct apmhook *list)
383{
384	struct apmhook *p;
385
386	for (p = list; p != NULL; p = p->ah_next) {
387#ifdef APM_DEBUG
388		printf("Execute APM hook \"%s.\"\n", p->ah_name);
389#endif
390		if ((*(p->ah_fun))(p->ah_arg))
391			printf("Warning: APM hook \"%s\" failed", p->ah_name);
392	}
393}
394
395
396/* establish an apm hook */
397struct apmhook *
398apm_hook_establish(int apmh, struct apmhook *ah)
399{
400	if (apmh < 0 || apmh >= NAPM_HOOK)
401		return NULL;
402
403	return apm_add_hook(&hook[apmh], ah);
404}
405
406/* disestablish an apm hook */
407void
408apm_hook_disestablish(int apmh, struct apmhook *ah)
409{
410	if (apmh < 0 || apmh >= NAPM_HOOK)
411		return;
412
413	apm_del_hook(&hook[apmh], ah);
414}
415
416
417static struct timeval suspend_time;
418static struct timeval diff_time;
419
420static int
421apm_default_resume(void *arg)
422{
423	int pl;
424	u_int second, minute, hour;
425	struct timeval resume_time, tmp_time;
426
427	/* modified for adjkerntz */
428	pl = splsoftclock();
429	inittodr(0);			/* adjust time to RTC */
430	microtime(&resume_time);
431	getmicrotime(&tmp_time);
432	timevaladd(&tmp_time, &diff_time);
433
434#ifdef FIXME
435	/* XXX THIS DOESN'T WORK!!! */
436	time = tmp_time;
437#endif
438
439#ifdef APM_FIXUP_CALLTODO
440	/* Calculate the delta time suspended */
441	timevalsub(&resume_time, &suspend_time);
442	/* Fixup the calltodo list with the delta time. */
443	adjust_timeout_calltodo(&resume_time);
444#endif /* APM_FIXUP_CALLTODOK */
445	splx(pl);
446#ifndef APM_FIXUP_CALLTODO
447	second = resume_time.tv_sec - suspend_time.tv_sec;
448#else /* APM_FIXUP_CALLTODO */
449	/*
450	 * We've already calculated resume_time to be the delta between
451	 * the suspend and the resume.
452	 */
453	second = resume_time.tv_sec;
454#endif /* APM_FIXUP_CALLTODO */
455	hour = second / 3600;
456	second %= 3600;
457	minute = second / 60;
458	second %= 60;
459	log(LOG_NOTICE, "resumed from suspended mode (slept %02d:%02d:%02d)\n",
460		hour, minute, second);
461	return 0;
462}
463
464static int
465apm_default_suspend(void *arg)
466{
467	int	pl;
468
469	pl = splsoftclock();
470	microtime(&diff_time);
471	inittodr(0);
472	microtime(&suspend_time);
473	timevalsub(&diff_time, &suspend_time);
474	splx(pl);
475	return 0;
476}
477
478static int apm_record_event __P((struct apm_softc *, u_int));
479static void apm_processevent(void);
480
481static u_int apm_op_inprog = 0;
482
483static void
484apm_lastreq_notify(void)
485{
486	struct apm_softc *sc = &apm_softc;
487
488	sc->bios.r.eax = (APM_BIOS << 8) | APM_SETPWSTATE;
489	sc->bios.r.ebx = PMDV_ALLDEV;
490	sc->bios.r.ecx = PMST_LASTREQNOTIFY;
491	sc->bios.r.edx = 0;
492	apm_bioscall();
493}
494
495static int
496apm_lastreq_rejected(void)
497{
498	struct apm_softc *sc = &apm_softc;
499
500	if (apm_op_inprog == 0) {
501		return 1;	/* no operation in progress */
502	}
503
504	sc->bios.r.eax = (APM_BIOS << 8) | APM_SETPWSTATE;
505	sc->bios.r.ebx = PMDV_ALLDEV;
506	sc->bios.r.ecx = PMST_LASTREQREJECT;
507	sc->bios.r.edx = 0;
508
509	if (apm_bioscall()) {
510#ifdef APM_DEBUG
511		printf("apm_lastreq_rejected: failed\n");
512#endif
513		return 1;
514	}
515	apm_op_inprog = 0;
516	return 0;
517}
518
519/*
520 * Public interface to the suspend/resume:
521 *
522 * Execute suspend and resume hook before and after sleep, respectively.
523 *
524 */
525
526void
527apm_suspend(int state)
528{
529	struct apm_softc *sc = &apm_softc;
530	int error;
531
532	if (!sc)
533		return;
534
535	apm_op_inprog = 0;
536
537	if (sc->initialized) {
538		error = DEVICE_SUSPEND(root_bus);
539		/*
540		 * XXX Shouldn't ignore the error like this, but should
541		 * instead fix the newbus code.  Until that happens,
542		 * I'm doing this to get suspend working again.
543		 */
544		if (error)
545			printf("DEVICE_SUSPEND error %d, ignored\n", error);
546		apm_execute_hook(hook[APM_HOOK_SUSPEND]);
547		if (apm_suspend_system(state) == 0)
548			apm_processevent();
549		else
550			/* Failure, 'resume' the system again */
551			apm_execute_hook(hook[APM_HOOK_RESUME]);
552	}
553}
554
555void
556apm_resume(void)
557{
558	struct apm_softc *sc = &apm_softc;
559
560	if (!sc)
561		return;
562
563	if (sc->initialized) {
564		DEVICE_RESUME(root_bus);
565		apm_execute_hook(hook[APM_HOOK_RESUME]);
566	}
567}
568
569
570/* get APM information */
571static int
572apm_get_info(apm_info_t aip)
573{
574	struct apm_softc *sc = &apm_softc;
575
576	sc->bios.r.eax = (APM_BIOS << 8) | APM_GETPWSTATUS;
577	sc->bios.r.ebx = PMDV_ALLDEV;
578	sc->bios.r.ecx = 0;
579	sc->bios.r.edx = 0xffff;		/* default to unknown battery time */
580
581	if (apm_bioscall())
582		return 1;
583
584	aip->ai_infoversion = 1;
585	aip->ai_acline      = (sc->bios.r.ebx >> 8) & 0xff;
586	aip->ai_batt_stat   = sc->bios.r.ebx & 0xff;
587	aip->ai_batt_life   = sc->bios.r.ecx & 0xff;
588	aip->ai_major       = (u_int)sc->majorversion;
589	aip->ai_minor       = (u_int)sc->minorversion;
590	aip->ai_status      = (u_int)sc->active;
591	sc->bios.r.edx &= 0xffff;
592	if (sc->bios.r.edx == 0xffff)	/* Time is unknown */
593		aip->ai_batt_time = -1;
594	else if (sc->bios.r.edx & 0x8000)	/* Time is in minutes */
595		aip->ai_batt_time = (sc->bios.r.edx & 0x7fff) * 60;
596	else			/* Time is in seconds */
597		aip->ai_batt_time = sc->bios.r.edx;
598
599	sc->bios.r.eax = (APM_BIOS << 8) | APM_GETCAPABILITIES;
600	sc->bios.r.ebx = 0;
601	sc->bios.r.ecx = 0;
602	sc->bios.r.edx = 0;
603	if (apm_bioscall()) {
604		aip->ai_batteries = -1;	/* Unknown */
605		aip->ai_capabilities = 0xff00; /* Unknown, with no bits set */
606	} else {
607		aip->ai_batteries = sc->bios.r.ebx & 0xff;
608		aip->ai_capabilities = sc->bios.r.ecx & 0xf;
609	}
610
611	bzero(aip->ai_spare, sizeof aip->ai_spare);
612
613	return 0;
614}
615
616
617/* inform APM BIOS that CPU is idle */
618void
619apm_cpu_idle(void)
620{
621	struct apm_softc *sc = &apm_softc;
622
623	if (sc->active) {
624
625		sc->bios.r.eax = (APM_BIOS <<8) | APM_CPUIDLE;
626		sc->bios.r.edx = sc->bios.r.ecx = sc->bios.r.ebx = 0;
627		(void) apm_bioscall();
628	}
629	/*
630	 * Some APM implementation halts CPU in BIOS, whenever
631	 * "CPU-idle" function are invoked, but swtch() of
632	 * FreeBSD halts CPU, therefore, CPU is halted twice
633	 * in the sched loop. It makes the interrupt latency
634	 * terribly long and be able to cause a serious problem
635	 * in interrupt processing. We prevent it by removing
636	 * "hlt" operation from swtch() and managed it under
637	 * APM driver.
638	 */
639	if (!sc->active || sc->always_halt_cpu)
640		__asm("hlt");	/* wait for interrupt */
641}
642
643/* inform APM BIOS that CPU is busy */
644void
645apm_cpu_busy(void)
646{
647	struct apm_softc *sc = &apm_softc;
648
649	/*
650	 * The APM specification says this is only necessary if your BIOS
651	 * slows down the processor in the idle task, otherwise it's not
652	 * necessary.
653	 */
654	if (sc->slow_idle_cpu && sc->active) {
655
656		sc->bios.r.eax = (APM_BIOS <<8) | APM_CPUBUSY;
657		sc->bios.r.edx = sc->bios.r.ecx = sc->bios.r.ebx = 0;
658		apm_bioscall();
659	}
660}
661
662
663/*
664 * APM timeout routine:
665 *
666 * This routine is automatically called by timer once per second.
667 */
668
669static void
670apm_timeout(void *dummy)
671{
672	struct apm_softc *sc = &apm_softc;
673
674	if (apm_op_inprog)
675		apm_lastreq_notify();
676
677	if (!sc->bios_busy)
678		apm_processevent();
679
680	if (sc->active == 1)
681		/* Run slightly more oftan than 1 Hz */
682		apm_timeout_ch = timeout(apm_timeout, NULL, hz - 1 );
683}
684
685/* enable APM BIOS */
686static void
687apm_event_enable(void)
688{
689	struct apm_softc *sc = &apm_softc;
690
691#ifdef APM_DEBUG
692	printf("called apm_event_enable()\n");
693#endif
694	if (sc->initialized) {
695		sc->active = 1;
696		apm_timeout(sc);
697	}
698}
699
700/* disable APM BIOS */
701static void
702apm_event_disable(void)
703{
704	struct apm_softc *sc = &apm_softc;
705
706#ifdef APM_DEBUG
707	printf("called apm_event_disable()\n");
708#endif
709	if (sc->initialized) {
710		untimeout(apm_timeout, NULL, apm_timeout_ch);
711		sc->active = 0;
712	}
713}
714
715/* halt CPU in scheduling loop */
716static void
717apm_halt_cpu(void)
718{
719	struct apm_softc *sc = &apm_softc;
720
721	if (sc->initialized)
722		sc->always_halt_cpu = 1;
723}
724
725/* don't halt CPU in scheduling loop */
726static void
727apm_not_halt_cpu(void)
728{
729	struct apm_softc *sc = &apm_softc;
730
731	if (sc->initialized)
732		sc->always_halt_cpu = 0;
733}
734
735/* device driver definitions */
736
737/*
738 * probe for APM BIOS
739 */
740static int
741apm_probe(device_t dev)
742{
743#define APM_KERNBASE	KERNBASE
744	struct vm86frame	vmf;
745	struct apm_softc	*sc = &apm_softc;
746	int			disabled, flags;
747
748	if (resource_int_value("apm", 0, "disabled", &disabled) == 0
749	    && disabled != 0)
750		return ENXIO;
751
752	device_set_desc(dev, "APM BIOS");
753
754	if ( device_get_unit(dev) > 0 ) {
755		printf("apm: Only one APM driver supported.\n");
756		return ENXIO;
757	}
758
759	if (resource_int_value("apm", 0, "flags", &flags) != 0)
760		flags = 0;
761
762	bzero(&vmf, sizeof(struct vm86frame));		/* safety */
763	bzero(&apm_softc, sizeof(apm_softc));
764	vmf.vmf_ah = APM_BIOS;
765	vmf.vmf_al = APM_INSTCHECK;
766	vmf.vmf_bx = 0;
767	if (vm86_intcall(APM_INT, &vmf))
768		return ENXIO;			/* APM not found */
769	if (vmf.vmf_bx != 0x504d) {
770		printf("apm: incorrect signature (0x%x)\n", vmf.vmf_bx);
771		return ENXIO;
772	}
773	if ((vmf.vmf_cx & (APM_32BIT_SUPPORT | APM_16BIT_SUPPORT)) == 0) {
774		printf("apm: protected mode connections are not supported\n");
775		return ENXIO;
776	}
777
778	apm_version = vmf.vmf_ax;
779	sc->slow_idle_cpu = ((vmf.vmf_cx & APM_CPUIDLE_SLOW) != 0);
780	sc->disabled = ((vmf.vmf_cx & APM_DISABLED) != 0);
781	sc->disengaged = ((vmf.vmf_cx & APM_DISENGAGED) != 0);
782
783	vmf.vmf_ah = APM_BIOS;
784	vmf.vmf_al = APM_DISCONNECT;
785	vmf.vmf_bx = 0;
786        vm86_intcall(APM_INT, &vmf);		/* disconnect, just in case */
787
788	if ((vmf.vmf_cx & APM_32BIT_SUPPORT) != 0) {
789		vmf.vmf_ah = APM_BIOS;
790		vmf.vmf_al = APM_PROT32CONNECT;
791		vmf.vmf_bx = 0;
792		if (vm86_intcall(APM_INT, &vmf)) {
793			printf("apm: 32-bit connection error.\n");
794			return (ENXIO);
795 		}
796		sc->bios.seg.code32.base = (vmf.vmf_ax << 4) + APM_KERNBASE;
797		sc->bios.seg.code32.limit = 0xffff;
798		sc->bios.seg.code16.base = (vmf.vmf_cx << 4) + APM_KERNBASE;
799		sc->bios.seg.code16.limit = 0xffff;
800		sc->bios.seg.data.base = (vmf.vmf_dx << 4) + APM_KERNBASE;
801		sc->bios.seg.data.limit = 0xffff;
802		sc->bios.entry = vmf.vmf_ebx;
803		sc->connectmode = APM_PROT32CONNECT;
804 	} else {
805		/* use 16-bit connection */
806		vmf.vmf_ah = APM_BIOS;
807		vmf.vmf_al = APM_PROT16CONNECT;
808		vmf.vmf_bx = 0;
809		if (vm86_intcall(APM_INT, &vmf)) {
810			printf("apm: 16-bit connection error.\n");
811			return (ENXIO);
812		}
813		sc->bios.seg.code16.base = (vmf.vmf_ax << 4) + APM_KERNBASE;
814		sc->bios.seg.code16.limit = 0xffff;
815		sc->bios.seg.data.base = (vmf.vmf_cx << 4) + APM_KERNBASE;
816		sc->bios.seg.data.limit = 0xffff;
817		sc->bios.entry = vmf.vmf_bx;
818		sc->connectmode = APM_PROT16CONNECT;
819	}
820	return(0);
821}
822
823
824/*
825 * return 0 if the user will notice and handle the event,
826 * return 1 if the kernel driver should do so.
827 */
828static int
829apm_record_event(struct apm_softc *sc, u_int event_type)
830{
831	struct apm_event_info *evp;
832
833	if ((sc->sc_flags & SCFLAG_OPEN) == 0)
834		return 1;		/* no user waiting */
835	if (sc->event_count == APM_NEVENTS)
836		return 1;			/* overflow */
837	if (sc->event_filter[event_type] == 0)
838		return 1;		/* not registered */
839	evp = &sc->event_list[sc->event_ptr];
840	sc->event_count++;
841	sc->event_ptr++;
842	sc->event_ptr %= APM_NEVENTS;
843	evp->type = event_type;
844	evp->index = ++apm_evindex;
845	selwakeup(&sc->sc_rsel);
846	return (sc->sc_flags & SCFLAG_OCTL) ? 0 : 1; /* user may handle */
847}
848
849/* Process APM event */
850static void
851apm_processevent(void)
852{
853	int apm_event;
854	struct apm_softc *sc = &apm_softc;
855
856#ifdef APM_DEBUG
857#  define OPMEV_DEBUGMESSAGE(symbol) case symbol: \
858	printf("Received APM Event: " #symbol "\n");
859#else
860#  define OPMEV_DEBUGMESSAGE(symbol) case symbol:
861#endif
862	do {
863		apm_event = apm_getevent();
864		switch (apm_event) {
865		    OPMEV_DEBUGMESSAGE(PMEV_STANDBYREQ);
866			if (apm_op_inprog == 0) {
867			    apm_op_inprog++;
868			    if (apm_record_event(sc, apm_event)) {
869				apm_suspend(PMST_STANDBY);
870			    }
871			}
872			break;
873		    OPMEV_DEBUGMESSAGE(PMEV_SUSPENDREQ);
874 			apm_lastreq_notify();
875			if (apm_op_inprog == 0) {
876			    apm_op_inprog++;
877			    if (apm_record_event(sc, apm_event)) {
878				apm_suspend(PMST_SUSPEND);
879			    }
880			}
881			return; /* XXX skip the rest */
882		    OPMEV_DEBUGMESSAGE(PMEV_USERSUSPENDREQ);
883 			apm_lastreq_notify();
884			if (apm_op_inprog == 0) {
885			    apm_op_inprog++;
886			    if (apm_record_event(sc, apm_event)) {
887				apm_suspend(PMST_SUSPEND);
888			    }
889			}
890			return; /* XXX skip the rest */
891		    OPMEV_DEBUGMESSAGE(PMEV_CRITSUSPEND);
892			apm_suspend(PMST_SUSPEND);
893			break;
894		    OPMEV_DEBUGMESSAGE(PMEV_NORMRESUME);
895			apm_record_event(sc, apm_event);
896			apm_resume();
897			break;
898		    OPMEV_DEBUGMESSAGE(PMEV_CRITRESUME);
899			apm_record_event(sc, apm_event);
900			apm_resume();
901			break;
902		    OPMEV_DEBUGMESSAGE(PMEV_STANDBYRESUME);
903			apm_record_event(sc, apm_event);
904			apm_resume();
905			break;
906		    OPMEV_DEBUGMESSAGE(PMEV_BATTERYLOW);
907			if (apm_record_event(sc, apm_event)) {
908			    apm_battery_low();
909			    apm_suspend(PMST_SUSPEND);
910			}
911			break;
912		    OPMEV_DEBUGMESSAGE(PMEV_POWERSTATECHANGE);
913			apm_record_event(sc, apm_event);
914			break;
915		    OPMEV_DEBUGMESSAGE(PMEV_UPDATETIME);
916			apm_record_event(sc, apm_event);
917			inittodr(0);	/* adjust time to RTC */
918			break;
919		    case PMEV_NOEVENT:
920			break;
921		    default:
922			printf("Unknown Original APM Event 0x%x\n", apm_event);
923			    break;
924		}
925	} while (apm_event != PMEV_NOEVENT);
926}
927
928/*
929 * Attach APM:
930 *
931 * Initialize APM driver
932 */
933
934static int
935apm_attach(device_t dev)
936{
937	struct apm_softc	*sc = &apm_softc;
938	int			flags;
939	int			drv_version;
940
941	if (resource_int_value("apm", 0, "flags", &flags) != 0)
942		flags = 0;
943
944	if (flags & 0x20)
945		statclock_disable = 1;
946
947	sc->initialized = 0;
948
949	/* Must be externally enabled */
950	sc->active = 0;
951
952	/* Always call HLT in idle loop */
953	sc->always_halt_cpu = 1;
954
955	/* print bootstrap messages */
956#ifdef APM_DEBUG
957	printf("apm: APM BIOS version %04x\n",  apm_version);
958	printf("apm: Code16 0x%08x, Data 0x%08x\n",
959               sc->bios.seg.code16.base, sc->bios.seg.data.base);
960	printf("apm: Code entry 0x%08x, Idling CPU %s, Management %s\n",
961               sc->bios.entry, is_enabled(sc->slow_idle_cpu),
962	       is_enabled(!sc->disabled));
963	printf("apm: CS_limit=0x%x, DS_limit=0x%x\n",
964	      sc->bios.seg.code16.limit, sc->bios.seg.data.limit);
965#endif /* APM_DEBUG */
966
967#if 0
968	/*
969	 * XXX this may not be needed anymore
970	 */
971	if ((flags & 0x10)) {
972		if ((flags & 0xf) >= 0x2) {
973			apm_driver_version(0x102);
974		}
975		if (!apm_version && (flags & 0xf) >= 0x1) {
976			apm_driver_version(0x101);
977		}
978	} else {
979		apm_driver_version(0x102);
980		if (!apm_version)
981			apm_driver_version(0x101);
982	}
983#endif
984	/*
985        * In one test, apm bios version was 1.02; an attempt to register
986        * a 1.04 driver resulted in a 1.00 connection!  Registering a
987        * 1.02 driver resulted in a 1.02 connection.
988        */
989	drv_version = apm_version > 0x102 ? 0x102 : apm_version;
990	for (; drv_version > 0x100; drv_version--)
991		if (apm_driver_version(drv_version) == 0)
992			break;
993	sc->minorversion = ((drv_version & 0x00f0) >>  4) * 10 +
994		((drv_version & 0x000f) >> 0);
995	sc->majorversion = ((drv_version & 0xf000) >> 12) * 10 +
996		((apm_version & 0x0f00) >> 8);
997
998	sc->intversion = INTVERSION(sc->majorversion, sc->minorversion);
999
1000#ifdef APM_DEBUG
1001	if (sc->intversion >= INTVERSION(1, 1))
1002		printf("apm: Engaged control %s\n", is_enabled(!sc->disengaged));
1003#endif
1004
1005	printf("apm: found APM BIOS v%ld.%ld, connected at v%d.%d\n",
1006	       ((apm_version & 0xf000) >> 12) * 10 + ((apm_version & 0x0f00) >> 8),
1007	       ((apm_version & 0x00f0) >> 4) * 10 + ((apm_version & 0x000f) >> 0),
1008	       sc->majorversion, sc->minorversion);
1009
1010#ifdef APM_DEBUG
1011	printf("apm: Slow Idling CPU %s\n", is_enabled(sc->slow_idle_cpu));
1012#endif
1013
1014	/* enable power management */
1015	if (sc->disabled) {
1016		if (apm_enable_disable_pm(1)) {
1017#ifdef APM_DEBUG
1018			printf("apm: *Warning* enable function failed! [%x]\n",
1019				(sc->bios.r.eax >> 8) & 0xff);
1020#endif
1021		}
1022	}
1023
1024	/* engage power managment (APM 1.1 or later) */
1025	if (sc->intversion >= INTVERSION(1, 1) && sc->disengaged) {
1026		if (apm_engage_disengage_pm(1)) {
1027#ifdef APM_DEBUG
1028			printf("apm: *Warning* engage function failed err=[%x]",
1029				(sc->bios.r.eax >> 8) & 0xff);
1030			printf(" (Docked or using external power?).\n");
1031#endif
1032		}
1033	}
1034
1035        /* default suspend hook */
1036        sc->sc_suspend.ah_fun = apm_default_suspend;
1037        sc->sc_suspend.ah_arg = sc;
1038        sc->sc_suspend.ah_name = "default suspend";
1039        sc->sc_suspend.ah_order = APM_MAX_ORDER;
1040
1041        /* default resume hook */
1042        sc->sc_resume.ah_fun = apm_default_resume;
1043        sc->sc_resume.ah_arg = sc;
1044        sc->sc_resume.ah_name = "default resume";
1045        sc->sc_resume.ah_order = APM_MIN_ORDER;
1046
1047        apm_hook_establish(APM_HOOK_SUSPEND, &sc->sc_suspend);
1048        apm_hook_establish(APM_HOOK_RESUME , &sc->sc_resume);
1049
1050	/* Power the system off using APM */
1051	EVENTHANDLER_REGISTER(shutdown_final, apm_power_off, NULL,
1052			      SHUTDOWN_PRI_LAST);
1053
1054	sc->initialized = 1;
1055
1056#ifdef DEVFS
1057	sc->sc_devfs_token =
1058		devfs_add_devswf(&apm_cdevsw, 0, DV_CHR, 0, 0, 0600, "apm");
1059#endif
1060	return 0;
1061}
1062
1063static int
1064apmopen(dev_t dev, int flag, int fmt, struct proc *p)
1065{
1066	struct apm_softc *sc = &apm_softc;
1067	int ctl = APMDEV(dev);
1068
1069	if (!sc->initialized)
1070		return (ENXIO);
1071
1072	switch (ctl) {
1073	case APMDEV_CTL:
1074		if (!(flag & FWRITE))
1075			return EINVAL;
1076		if (sc->sc_flags & SCFLAG_OCTL)
1077			return EBUSY;
1078		sc->sc_flags |= SCFLAG_OCTL;
1079		bzero(sc->event_filter, sizeof sc->event_filter);
1080		break;
1081	case APMDEV_NORMAL:
1082		sc->sc_flags |= SCFLAG_ONORMAL;
1083		break;
1084	default:
1085		return ENXIO;
1086		break;
1087	}
1088	return 0;
1089}
1090
1091static int
1092apmclose(dev_t dev, int flag, int fmt, struct proc *p)
1093{
1094	struct apm_softc *sc = &apm_softc;
1095	int ctl = APMDEV(dev);
1096
1097	switch (ctl) {
1098	case APMDEV_CTL:
1099		apm_lastreq_rejected();
1100		sc->sc_flags &= ~SCFLAG_OCTL;
1101		bzero(sc->event_filter, sizeof sc->event_filter);
1102		break;
1103	case APMDEV_NORMAL:
1104		sc->sc_flags &= ~SCFLAG_ONORMAL;
1105		break;
1106	}
1107	if ((sc->sc_flags & SCFLAG_OPEN) == 0) {
1108		sc->event_count = 0;
1109		sc->event_ptr = 0;
1110	}
1111	return 0;
1112}
1113
1114static int
1115apmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1116{
1117	struct apm_softc *sc = &apm_softc;
1118	struct apm_bios_arg *args;
1119	int error = 0;
1120	int ret;
1121	int newstate;
1122
1123	if (!sc->initialized)
1124		return (ENXIO);
1125#ifdef APM_DEBUG
1126	printf("APM ioctl: cmd = 0x%x\n", cmd);
1127#endif
1128	switch (cmd) {
1129	case APMIO_SUSPEND:
1130		if (sc->active)
1131			apm_suspend(PMST_SUSPEND);
1132		else
1133			error = EINVAL;
1134		break;
1135
1136	case APMIO_STANDBY:
1137		if (sc->active)
1138			apm_suspend(PMST_STANDBY);
1139		else
1140			error = EINVAL;
1141		break;
1142
1143	case APMIO_GETINFO_OLD:
1144		{
1145			struct apm_info info;
1146			apm_info_old_t aiop;
1147
1148			if (apm_get_info(&info))
1149				error = ENXIO;
1150			aiop = (apm_info_old_t)addr;
1151			aiop->ai_major = info.ai_major;
1152			aiop->ai_minor = info.ai_minor;
1153			aiop->ai_acline = info.ai_acline;
1154			aiop->ai_batt_stat = info.ai_batt_stat;
1155			aiop->ai_batt_life = info.ai_batt_life;
1156			aiop->ai_status = info.ai_status;
1157		}
1158		break;
1159	case APMIO_GETINFO:
1160		if (apm_get_info((apm_info_t)addr))
1161			error = ENXIO;
1162		break;
1163	case APMIO_ENABLE:
1164		apm_event_enable();
1165		break;
1166	case APMIO_DISABLE:
1167		apm_event_disable();
1168		break;
1169	case APMIO_HALTCPU:
1170		apm_halt_cpu();
1171		break;
1172	case APMIO_NOTHALTCPU:
1173		apm_not_halt_cpu();
1174		break;
1175	case APMIO_DISPLAY:
1176		newstate = *(int *)addr;
1177		if (apm_display(newstate))
1178			error = ENXIO;
1179		break;
1180	case APMIO_BIOS:
1181		/* XXX compatibility with the old interface */
1182		args = (struct apm_bios_arg *)addr;
1183		sc->bios.r.eax = args->eax;
1184		sc->bios.r.ebx = args->ebx;
1185		sc->bios.r.ecx = args->ecx;
1186		sc->bios.r.edx = args->edx;
1187		sc->bios.r.esi = args->esi;
1188		sc->bios.r.edi = args->edi;
1189		if ((ret = apm_bioscall())) {
1190			/*
1191			 * Return code 1 means bios call was unsuccessful.
1192			 * Error code is stored in %ah.
1193			 * Return code -1 means bios call was unsupported
1194			 * in the APM BIOS version.
1195			 */
1196			if (ret == -1) {
1197				error = EINVAL;
1198			}
1199		} else {
1200			/*
1201			 * Return code 0 means bios call was successful.
1202			 * We need only %al and can discard %ah.
1203			 */
1204			sc->bios.r.eax &= 0xff;
1205		}
1206		args->eax = sc->bios.r.eax;
1207		args->ebx = sc->bios.r.ebx;
1208		args->ecx = sc->bios.r.ecx;
1209		args->edx = sc->bios.r.edx;
1210		args->esi = sc->bios.r.esi;
1211		args->edi = sc->bios.r.edi;
1212		break;
1213	default:
1214		error = EINVAL;
1215		break;
1216	}
1217
1218	/* for /dev/apmctl */
1219	if (APMDEV(dev) == APMDEV_CTL) {
1220		struct apm_event_info *evp;
1221		int i;
1222
1223		error = 0;
1224		switch (cmd) {
1225		case APMIO_NEXTEVENT:
1226			if (!sc->event_count) {
1227				error = EAGAIN;
1228			} else {
1229				evp = (struct apm_event_info *)addr;
1230				i = sc->event_ptr + APM_NEVENTS - sc->event_count;
1231				i %= APM_NEVENTS;
1232				*evp = sc->event_list[i];
1233				sc->event_count--;
1234			}
1235			break;
1236		case APMIO_REJECTLASTREQ:
1237			if (apm_lastreq_rejected()) {
1238				error = EINVAL;
1239			}
1240			break;
1241		default:
1242			error = EINVAL;
1243			break;
1244		}
1245	}
1246
1247	return error;
1248}
1249
1250static int
1251apmwrite(dev_t dev, struct uio *uio, int ioflag)
1252{
1253	struct apm_softc *sc = &apm_softc;
1254	u_int event_type;
1255	int error;
1256	u_char enabled;
1257
1258	if (APMDEV(dev) != APMDEV_CTL)
1259		return(ENODEV);
1260	if (uio->uio_resid != sizeof(u_int))
1261		return(E2BIG);
1262
1263	if ((error = uiomove((caddr_t)&event_type, sizeof(u_int), uio)))
1264		return(error);
1265
1266	if (event_type < 0 || event_type >= APM_NPMEV)
1267		return(EINVAL);
1268
1269	if (sc->event_filter[event_type] == 0) {
1270		enabled = 1;
1271	} else {
1272		enabled = 0;
1273	}
1274	sc->event_filter[event_type] = enabled;
1275#ifdef APM_DEBUG
1276	printf("apmwrite: event 0x%x %s\n", event_type, is_enabled(enabled));
1277#endif
1278
1279	return uio->uio_resid;
1280}
1281
1282static int
1283apmpoll(dev_t dev, int events, struct proc *p)
1284{
1285	struct apm_softc *sc = &apm_softc;
1286	int revents = 0;
1287
1288	if (events & (POLLIN | POLLRDNORM)) {
1289		if (sc->event_count) {
1290			revents |= events & (POLLIN | POLLRDNORM);
1291		} else {
1292			selrecord(p, &sc->sc_rsel);
1293		}
1294	}
1295
1296	return (revents);
1297}
1298
1299static device_method_t apm_methods[] = {
1300	/* Device interface */
1301	DEVMETHOD(device_probe,		apm_probe),
1302	DEVMETHOD(device_attach,	apm_attach),
1303
1304	{ 0, 0 }
1305};
1306
1307static driver_t apm_driver = {
1308	"apm",
1309	apm_methods,
1310	1,			/* no softc (XXX) */
1311};
1312
1313static devclass_t apm_devclass;
1314
1315DEV_DRIVER_MODULE(apm, nexus, apm_driver, apm_devclass, apm_cdevsw, 0, 0);
1316