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