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