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