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