apm.c revision 49179
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.91 1999/07/22 14:45:22 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
745 */
746
747static int
748apm_probe(device_t dev)
749{
750	struct vm86frame	vmf;
751	int			i;
752	int			disabled, flags;
753
754	if (resource_int_value("apm", 0, "disabled", &disabled) == 0
755	    && disabled != 0)
756		return ENXIO;
757
758	device_set_desc(dev, "APM BIOS");
759
760	if ( device_get_unit(dev) > 0 ) {
761		printf("apm: Only one APM driver supported.\n");
762		return ENXIO;
763	}
764
765	if (resource_int_value("apm", 0, "flags", &flags) != 0)
766		flags = 0;
767
768	bzero(&vmf, sizeof(struct vm86frame));		/* safety */
769	vmf.vmf_ax = (APM_BIOS << 8) | APM_INSTCHECK;
770	vmf.vmf_bx = 0;
771	if (((i = vm86_intcall(SYSTEM_BIOS, &vmf)) == 0) &&
772	    !(vmf.vmf_eflags & PSL_C) &&
773	    (vmf.vmf_bx == 0x504d)) {
774
775		apm_version   = vmf.vmf_ax;
776		apm_flags     = vmf.vmf_cx;
777
778		vmf.vmf_ax = (APM_BIOS << 8) | APM_PROT32CONNECT;
779		vmf.vmf_bx = 0;
780		if (((i = vm86_intcall(SYSTEM_BIOS, &vmf)) == 0) &&
781		    !(vmf.vmf_eflags & PSL_C)) {
782
783			apm_cs32_base = vmf.vmf_ax;
784			apm_cs_entry  = vmf.vmf_ebx;
785			apm_cs16_base = vmf.vmf_cx;
786			apm_ds_base   = vmf.vmf_dx;
787			apm_cs32_limit  = vmf.vmf_si;
788			if (apm_version >= 0x0102)
789				apm_cs16_limit = (vmf.esi.r_ex >> 16);
790			apm_ds_limit  = vmf.vmf_di;
791#ifdef APM_DEBUG
792			printf("apm: BIOS probe/32-bit connect successful\n");
793#endif
794		} else {
795			/* XXX constant typo! */
796			if (vmf.vmf_ah == APME_PROT32NOTDUPPORTED) {
797				apm_version = APMINI_NOT32BIT;
798			} else {
799				apm_version = APMINI_CONNECTERR;
800			}
801#ifdef APM_DEBUG
802			printf("apm: BIOS 32-bit connect failed: error 0x%x  carry %d  ah 0x%x\n",
803			       i, (vmf.vmf_eflags & PSL_C) ? 1 : 0, vmf.vmf_ah);
804#endif
805		}
806	} else {
807		apm_version = APMINI_CANTFIND;
808#ifdef APM_DEBUG
809		printf("apm: BIOS probe failed: error 0x%x  carry %d  bx 0x%x\n",
810		       i, (vmf.vmf_eflags & PSL_C) ? 1 : 0, vmf.vmf_bx);
811#endif
812	}
813
814	bzero(&apm_softc, sizeof(apm_softc));
815
816	switch (apm_version) {
817	case APMINI_CANTFIND:
818		/* silent */
819		return ENXIO;
820	case APMINI_NOT32BIT:
821		printf("apm: 32bit connection is not supported.\n");
822		return ENXIO;
823	case APMINI_CONNECTERR:
824		printf("apm: 32-bit connection error.\n");
825		return ENXIO;
826	}
827	if (flags & 0x20)
828		statclock_disable = 1;
829	return 0;
830}
831
832/*
833 * return 0 if the user will notice and handle the event,
834 * return 1 if the kernel driver should do so.
835 */
836static int
837apm_record_event(struct apm_softc *sc, u_int event_type)
838{
839	struct apm_event_info *evp;
840
841	if ((sc->sc_flags & SCFLAG_OPEN) == 0)
842		return 1;		/* no user waiting */
843	if (sc->event_count == APM_NEVENTS)
844		return 1;			/* overflow */
845	if (sc->event_filter[event_type] == 0)
846		return 1;		/* not registered */
847	evp = &sc->event_list[sc->event_ptr];
848	sc->event_count++;
849	sc->event_ptr++;
850	sc->event_ptr %= APM_NEVENTS;
851	evp->type = event_type;
852	evp->index = ++apm_evindex;
853	selwakeup(&sc->sc_rsel);
854	return (sc->sc_flags & SCFLAG_OCTL) ? 0 : 1; /* user may handle */
855}
856
857/* Process APM event */
858static void
859apm_processevent(void)
860{
861	int apm_event;
862	struct apm_softc *sc = &apm_softc;
863
864#ifdef APM_DEBUG
865#  define OPMEV_DEBUGMESSAGE(symbol) case symbol: \
866	printf("Received APM Event: " #symbol "\n");
867#else
868#  define OPMEV_DEBUGMESSAGE(symbol) case symbol:
869#endif
870	do {
871		apm_event = apm_getevent();
872		switch (apm_event) {
873		    OPMEV_DEBUGMESSAGE(PMEV_STANDBYREQ);
874			if (apm_op_inprog == 0) {
875			    apm_op_inprog++;
876			    if (apm_record_event(sc, apm_event)) {
877				apm_suspend(PMST_STANDBY);
878			    }
879			}
880			break;
881		    OPMEV_DEBUGMESSAGE(PMEV_SUSPENDREQ);
882 			apm_lastreq_notify();
883			if (apm_op_inprog == 0) {
884			    apm_op_inprog++;
885			    if (apm_record_event(sc, apm_event)) {
886				apm_suspend(PMST_SUSPEND);
887			    }
888			}
889			return; /* XXX skip the rest */
890		    OPMEV_DEBUGMESSAGE(PMEV_USERSUSPENDREQ);
891 			apm_lastreq_notify();
892			if (apm_op_inprog == 0) {
893			    apm_op_inprog++;
894			    if (apm_record_event(sc, apm_event)) {
895				apm_suspend(PMST_SUSPEND);
896			    }
897			}
898			return; /* XXX skip the rest */
899		    OPMEV_DEBUGMESSAGE(PMEV_CRITSUSPEND);
900			apm_suspend(PMST_SUSPEND);
901			break;
902		    OPMEV_DEBUGMESSAGE(PMEV_NORMRESUME);
903			apm_record_event(sc, apm_event);
904			apm_resume();
905			break;
906		    OPMEV_DEBUGMESSAGE(PMEV_CRITRESUME);
907			apm_record_event(sc, apm_event);
908			apm_resume();
909			break;
910		    OPMEV_DEBUGMESSAGE(PMEV_STANDBYRESUME);
911			apm_record_event(sc, apm_event);
912			apm_resume();
913			break;
914		    OPMEV_DEBUGMESSAGE(PMEV_BATTERYLOW);
915			if (apm_record_event(sc, apm_event)) {
916			    apm_battery_low();
917			    apm_suspend(PMST_SUSPEND);
918			}
919			break;
920		    OPMEV_DEBUGMESSAGE(PMEV_POWERSTATECHANGE);
921			apm_record_event(sc, apm_event);
922			break;
923		    OPMEV_DEBUGMESSAGE(PMEV_UPDATETIME);
924			apm_record_event(sc, apm_event);
925			inittodr(0);	/* adjust time to RTC */
926			break;
927		    case PMEV_NOEVENT:
928			break;
929		    default:
930			printf("Unknown Original APM Event 0x%x\n", apm_event);
931			    break;
932		}
933	} while (apm_event != PMEV_NOEVENT);
934}
935
936/*
937 * Attach APM:
938 *
939 * Initialize APM driver
940 */
941
942static int
943apm_attach(device_t dev)
944{
945#define APM_KERNBASE	KERNBASE
946	struct apm_softc	*sc = &apm_softc;
947	int			flags;
948
949	if (resource_int_value("apm", 0, "flags", &flags) != 0)
950		flags = 0;
951
952	sc->initialized = 0;
953
954	/* Must be externally enabled */
955	sc->active = 0;
956
957	/* setup APM parameters */
958	sc->cs16_base = (apm_cs16_base << 4) + APM_KERNBASE;
959	sc->cs32_base = (apm_cs32_base << 4) + APM_KERNBASE;
960	sc->ds_base = (apm_ds_base << 4) + APM_KERNBASE;
961	sc->cs32_limit = apm_cs32_limit - 1;
962	if (apm_cs16_limit == 0)
963	    apm_cs16_limit = apm_cs32_limit;
964	sc->cs16_limit = apm_cs16_limit - 1;
965	sc->ds_limit = apm_ds_limit - 1;
966	sc->cs_entry = apm_cs_entry;
967
968	/* Always call HLT in idle loop */
969	sc->always_halt_cpu = 1;
970
971	sc->slow_idle_cpu = ((apm_flags & APM_CPUIDLE_SLOW) != 0);
972	sc->disabled = ((apm_flags & APM_DISABLED) != 0);
973	sc->disengaged = ((apm_flags & APM_DISENGAGED) != 0);
974
975	/* print bootstrap messages */
976#ifdef APM_DEBUG
977	printf("apm: APM BIOS version %04x\n",  apm_version);
978	printf("apm: Code32 0x%08x, Code16 0x%08x, Data 0x%08x\n",
979		sc->cs32_base, sc->cs16_base, sc->ds_base);
980	printf("apm: Code entry 0x%08x, Idling CPU %s, Management %s\n",
981		sc->cs_entry, is_enabled(sc->slow_idle_cpu),
982		is_enabled(!sc->disabled));
983	printf("apm: CS32_limit=0x%x, CS16_limit=0x%x, DS_limit=0x%x\n",
984		(u_short)sc->cs32_limit, (u_short)sc->cs16_limit, (u_short)sc->ds_limit);
985#endif /* APM_DEBUG */
986
987#if 0
988	/* Workaround for some buggy APM BIOS implementations */
989	sc->cs_limit = 0xffff;
990	sc->ds_limit = 0xffff;
991#endif
992
993	/* setup GDT */
994	setup_apm_gdt(sc->cs32_base, sc->cs16_base, sc->ds_base,
995			sc->cs32_limit, sc->cs16_limit, sc->ds_limit);
996
997	/* setup entry point 48bit pointer */
998	apm_addr.segment = GSEL(GAPMCODE32_SEL, SEL_KPL);
999	apm_addr.offset  = sc->cs_entry;
1000
1001	if ((flags & 0x10)) {
1002		if ((flags & 0xf) >= 0x2) {
1003			apm_driver_version(0x102);
1004		}
1005		if (!apm_version && (flags & 0xf) >= 0x1) {
1006			apm_driver_version(0x101);
1007		}
1008	} else {
1009		apm_driver_version(0x102);
1010		if (!apm_version)
1011			apm_driver_version(0x101);
1012	}
1013	if (!apm_version)
1014		apm_version = 0x100;
1015
1016	sc->minorversion = ((apm_version & 0x00f0) >>  4) * 10 +
1017			((apm_version & 0x000f) >> 0);
1018	sc->majorversion = ((apm_version & 0xf000) >> 12) * 10 +
1019			((apm_version & 0x0f00) >> 8);
1020
1021	sc->intversion = INTVERSION(sc->majorversion, sc->minorversion);
1022
1023#ifdef APM_DEBUG
1024	if (sc->intversion >= INTVERSION(1, 1))
1025		printf("apm: Engaged control %s\n", is_enabled(!sc->disengaged));
1026#endif
1027
1028	printf("apm: found APM BIOS version %d.%d\n",
1029		sc->majorversion, sc->minorversion);
1030
1031#ifdef APM_DEBUG
1032	printf("apm: Slow Idling CPU %s\n", is_enabled(sc->slow_idle_cpu));
1033#endif
1034
1035	/* enable power management */
1036	if (sc->disabled) {
1037		if (apm_enable_disable_pm(1)) {
1038#ifdef APM_DEBUG
1039			printf("apm: *Warning* enable function failed! [%x]\n",
1040				apm_errno);
1041#endif
1042		}
1043	}
1044
1045	/* engage power managment (APM 1.1 or later) */
1046	if (sc->intversion >= INTVERSION(1, 1) && sc->disengaged) {
1047		if (apm_engage_disengage_pm(1)) {
1048#ifdef APM_DEBUG
1049			printf("apm: *Warning* engage function failed err=[%x]",
1050				apm_errno);
1051			printf(" (Docked or using external power?).\n");
1052#endif
1053		}
1054	}
1055
1056        /* default suspend hook */
1057        sc->sc_suspend.ah_fun = apm_default_suspend;
1058        sc->sc_suspend.ah_arg = sc;
1059        sc->sc_suspend.ah_name = "default suspend";
1060        sc->sc_suspend.ah_order = APM_MAX_ORDER;
1061
1062        /* default resume hook */
1063        sc->sc_resume.ah_fun = apm_default_resume;
1064        sc->sc_resume.ah_arg = sc;
1065        sc->sc_resume.ah_name = "default resume";
1066        sc->sc_resume.ah_order = APM_MIN_ORDER;
1067
1068        apm_hook_establish(APM_HOOK_SUSPEND, &sc->sc_suspend);
1069        apm_hook_establish(APM_HOOK_RESUME , &sc->sc_resume);
1070
1071	apm_event_enable();
1072
1073	/* Power the system off using APM */
1074	at_shutdown_pri(apm_power_off, NULL, SHUTDOWN_FINAL, SHUTDOWN_PRI_LAST);
1075
1076	sc->initialized = 1;
1077
1078#ifdef DEVFS
1079	sc->sc_devfs_token =
1080		devfs_add_devswf(&apm_cdevsw, 0, DV_CHR, 0, 0, 0600, "apm");
1081#endif
1082	return 0;
1083}
1084
1085static int
1086apmopen(dev_t dev, int flag, int fmt, struct proc *p)
1087{
1088	struct apm_softc *sc = &apm_softc;
1089	int ctl = APMDEV(dev);
1090
1091	if (!sc->initialized)
1092		return (ENXIO);
1093
1094	switch (ctl) {
1095	case APMDEV_CTL:
1096		if (!(flag & FWRITE))
1097			return EINVAL;
1098		if (sc->sc_flags & SCFLAG_OCTL)
1099			return EBUSY;
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	default:
1107		return ENXIO;
1108		break;
1109	}
1110	return 0;
1111}
1112
1113static int
1114apmclose(dev_t dev, int flag, int fmt, struct proc *p)
1115{
1116	struct apm_softc *sc = &apm_softc;
1117	int ctl = APMDEV(dev);
1118
1119	switch (ctl) {
1120	case APMDEV_CTL:
1121		apm_lastreq_rejected();
1122		sc->sc_flags &= ~SCFLAG_OCTL;
1123		bzero(sc->event_filter, sizeof sc->event_filter);
1124		break;
1125	case APMDEV_NORMAL:
1126		sc->sc_flags &= ~SCFLAG_ONORMAL;
1127		break;
1128	}
1129	if ((sc->sc_flags & SCFLAG_OPEN) == 0) {
1130		sc->event_count = 0;
1131		sc->event_ptr = 0;
1132	}
1133	return 0;
1134}
1135
1136static int
1137apmioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
1138{
1139	struct apm_softc *sc = &apm_softc;
1140	int error = 0;
1141	int newstate;
1142
1143	if (!sc->initialized)
1144		return (ENXIO);
1145#ifdef APM_DEBUG
1146	printf("APM ioctl: cmd = 0x%x\n", cmd);
1147#endif
1148	switch (cmd) {
1149	case APMIO_SUSPEND:
1150		if (sc->active)
1151			apm_suspend(PMST_SUSPEND);
1152		else
1153			error = EINVAL;
1154		break;
1155
1156	case APMIO_STANDBY:
1157		if (sc->active)
1158			apm_suspend(PMST_STANDBY);
1159		else
1160			error = EINVAL;
1161		break;
1162
1163	case APMIO_GETINFO_OLD:
1164		{
1165			struct apm_info info;
1166			apm_info_old_t aiop;
1167
1168			if (apm_get_info(&info))
1169				error = ENXIO;
1170			aiop = (apm_info_old_t)addr;
1171			aiop->ai_major = info.ai_major;
1172			aiop->ai_minor = info.ai_minor;
1173			aiop->ai_acline = info.ai_acline;
1174			aiop->ai_batt_stat = info.ai_batt_stat;
1175			aiop->ai_batt_life = info.ai_batt_life;
1176			aiop->ai_status = info.ai_status;
1177		}
1178		break;
1179	case APMIO_GETINFO:
1180		if (apm_get_info((apm_info_t)addr))
1181			error = ENXIO;
1182		break;
1183	case APMIO_ENABLE:
1184		apm_event_enable();
1185		break;
1186	case APMIO_DISABLE:
1187		apm_event_disable();
1188		break;
1189	case APMIO_HALTCPU:
1190		apm_halt_cpu();
1191		break;
1192	case APMIO_NOTHALTCPU:
1193		apm_not_halt_cpu();
1194		break;
1195	case APMIO_DISPLAY:
1196		newstate = *(int *)addr;
1197		if (apm_display(newstate))
1198			error = ENXIO;
1199		break;
1200	case APMIO_BIOS:
1201		if (apm_bios_call((struct apm_bios_arg*)addr) == 0)
1202			((struct apm_bios_arg*)addr)->eax &= 0xff;
1203		break;
1204	default:
1205		error = EINVAL;
1206		break;
1207	}
1208
1209	/* for /dev/apmctl */
1210	if (APMDEV(dev) == APMDEV_CTL) {
1211		struct apm_event_info *evp;
1212		int i;
1213
1214		error = 0;
1215		switch (cmd) {
1216		case APMIO_NEXTEVENT:
1217			if (!sc->event_count) {
1218				error = EAGAIN;
1219			} else {
1220				evp = (struct apm_event_info *)addr;
1221				i = sc->event_ptr + APM_NEVENTS - sc->event_count;
1222				i %= APM_NEVENTS;
1223				*evp = sc->event_list[i];
1224				sc->event_count--;
1225			}
1226			break;
1227		case APMIO_REJECTLASTREQ:
1228			if (apm_lastreq_rejected()) {
1229				error = EINVAL;
1230			}
1231			break;
1232		default:
1233			error = EINVAL;
1234			break;
1235		}
1236	}
1237
1238	return error;
1239}
1240
1241static int
1242apmwrite(dev_t dev, struct uio *uio, int ioflag)
1243{
1244	struct apm_softc *sc = &apm_softc;
1245	u_int event_type;
1246	int error;
1247	u_char enabled;
1248
1249	if (APMDEV(dev) != APMDEV_CTL)
1250		return(ENODEV);
1251	if (uio->uio_resid != sizeof(u_int))
1252		return(E2BIG);
1253
1254	if ((error = uiomove((caddr_t)&event_type, sizeof(u_int), uio)))
1255		return(error);
1256
1257	if (event_type < 0 || event_type >= APM_NPMEV)
1258		return(EINVAL);
1259
1260	if (sc->event_filter[event_type] == 0) {
1261		enabled = 1;
1262	} else {
1263		enabled = 0;
1264	}
1265	sc->event_filter[event_type] = enabled;
1266#ifdef APM_DEBUG
1267	printf("apmwrite: event 0x%x %s\n", event_type, is_enabled(enabled));
1268#endif
1269
1270	return uio->uio_resid;
1271}
1272
1273static int
1274apmpoll(dev_t dev, int events, struct proc *p)
1275{
1276	struct apm_softc *sc = &apm_softc;
1277	int revents = 0;
1278
1279	if (events & (POLLIN | POLLRDNORM)) {
1280		if (sc->event_count) {
1281			revents |= events & (POLLIN | POLLRDNORM);
1282		} else {
1283			selrecord(p, &sc->sc_rsel);
1284		}
1285	}
1286
1287	return (revents);
1288}
1289
1290static device_method_t apm_methods[] = {
1291	/* Device interface */
1292	DEVMETHOD(device_probe,		apm_probe),
1293	DEVMETHOD(device_attach,	apm_attach),
1294
1295	{ 0, 0 }
1296};
1297
1298static driver_t apm_driver = {
1299	"apm",
1300	apm_methods,
1301	1,			/* no softc (XXX) */
1302};
1303
1304static devclass_t apm_devclass;
1305
1306DEV_DRIVER_MODULE(apm, nexus, apm_driver, apm_devclass, apm_cdevsw, 0, 0);
1307