doc: fix broken references
[linux-2.6.git] / drivers / char / apm-emulation.c
1 /*
2  * bios-less APM driver for ARM Linux
3  *  Jamey Hicks <jamey@crl.dec.com>
4  *  adapted from the APM BIOS driver for Linux by Stephen Rothwell (sfr@linuxcare.com)
5  *
6  * APM 1.2 Reference:
7  *   Intel Corporation, Microsoft Corporation. Advanced Power Management
8  *   (APM) BIOS Interface Specification, Revision 1.2, February 1996.
9  *
10  * This document is available from Microsoft at:
11  *    http://www.microsoft.com/whdc/archive/amp_12.mspx
12  */
13 #include <linux/module.h>
14 #include <linux/poll.h>
15 #include <linux/slab.h>
16 #include <linux/mutex.h>
17 #include <linux/proc_fs.h>
18 #include <linux/seq_file.h>
19 #include <linux/miscdevice.h>
20 #include <linux/apm_bios.h>
21 #include <linux/capability.h>
22 #include <linux/sched.h>
23 #include <linux/suspend.h>
24 #include <linux/apm-emulation.h>
25 #include <linux/freezer.h>
26 #include <linux/device.h>
27 #include <linux/kernel.h>
28 #include <linux/list.h>
29 #include <linux/init.h>
30 #include <linux/completion.h>
31 #include <linux/kthread.h>
32 #include <linux/delay.h>
33
34 #include <asm/system.h>
35
36 /*
37  * The apm_bios device is one of the misc char devices.
38  * This is its minor number.
39  */
40 #define APM_MINOR_DEV   134
41
42 /*
43  * One option can be changed at boot time as follows:
44  *      apm=on/off                      enable/disable APM
45  */
46
47 /*
48  * Maximum number of events stored
49  */
50 #define APM_MAX_EVENTS          16
51
52 struct apm_queue {
53         unsigned int            event_head;
54         unsigned int            event_tail;
55         apm_event_t             events[APM_MAX_EVENTS];
56 };
57
58 /*
59  * thread states (for threads using a writable /dev/apm_bios fd):
60  *
61  * SUSPEND_NONE:        nothing happening
62  * SUSPEND_PENDING:     suspend event queued for thread and pending to be read
63  * SUSPEND_READ:        suspend event read, pending acknowledgement
64  * SUSPEND_ACKED:       acknowledgement received from thread (via ioctl),
65  *                      waiting for resume
66  * SUSPEND_ACKTO:       acknowledgement timeout
67  * SUSPEND_DONE:        thread had acked suspend and is now notified of
68  *                      resume
69  *
70  * SUSPEND_WAIT:        this thread invoked suspend and is waiting for resume
71  *
72  * A thread migrates in one of three paths:
73  *      NONE -1-> PENDING -2-> READ -3-> ACKED -4-> DONE -5-> NONE
74  *                                  -6-> ACKTO -7-> NONE
75  *      NONE -8-> WAIT -9-> NONE
76  *
77  * While in PENDING or READ, the thread is accounted for in the
78  * suspend_acks_pending counter.
79  *
80  * The transitions are invoked as follows:
81  *      1: suspend event is signalled from the core PM code
82  *      2: the suspend event is read from the fd by the userspace thread
83  *      3: userspace thread issues the APM_IOC_SUSPEND ioctl (as ack)
84  *      4: core PM code signals that we have resumed
85  *      5: APM_IOC_SUSPEND ioctl returns
86  *
87  *      6: the notifier invoked from the core PM code timed out waiting
88  *         for all relevant threds to enter ACKED state and puts those
89  *         that haven't into ACKTO
90  *      7: those threads issue APM_IOC_SUSPEND ioctl too late,
91  *         get an error
92  *
93  *      8: userspace thread issues the APM_IOC_SUSPEND ioctl (to suspend),
94  *         ioctl code invokes pm_suspend()
95  *      9: pm_suspend() returns indicating resume
96  */
97 enum apm_suspend_state {
98         SUSPEND_NONE,
99         SUSPEND_PENDING,
100         SUSPEND_READ,
101         SUSPEND_ACKED,
102         SUSPEND_ACKTO,
103         SUSPEND_WAIT,
104         SUSPEND_DONE,
105 };
106
107 /*
108  * The per-file APM data
109  */
110 struct apm_user {
111         struct list_head        list;
112
113         unsigned int            suser: 1;
114         unsigned int            writer: 1;
115         unsigned int            reader: 1;
116
117         int                     suspend_result;
118         enum apm_suspend_state  suspend_state;
119
120         struct apm_queue        queue;
121 };
122
123 /*
124  * Local variables
125  */
126 static atomic_t suspend_acks_pending = ATOMIC_INIT(0);
127 static atomic_t userspace_notification_inhibit = ATOMIC_INIT(0);
128 static int apm_disabled;
129 static struct task_struct *kapmd_tsk;
130
131 static DECLARE_WAIT_QUEUE_HEAD(apm_waitqueue);
132 static DECLARE_WAIT_QUEUE_HEAD(apm_suspend_waitqueue);
133
134 /*
135  * This is a list of everyone who has opened /dev/apm_bios
136  */
137 static DECLARE_RWSEM(user_list_lock);
138 static LIST_HEAD(apm_user_list);
139
140 /*
141  * kapmd info.  kapmd provides us a process context to handle
142  * "APM" events within - specifically necessary if we're going
143  * to be suspending the system.
144  */
145 static DECLARE_WAIT_QUEUE_HEAD(kapmd_wait);
146 static DEFINE_SPINLOCK(kapmd_queue_lock);
147 static struct apm_queue kapmd_queue;
148
149 static DEFINE_MUTEX(state_lock);
150
151 static const char driver_version[] = "1.13";    /* no spaces */
152
153
154
155 /*
156  * Compatibility cruft until the IPAQ people move over to the new
157  * interface.
158  */
159 static void __apm_get_power_status(struct apm_power_info *info)
160 {
161 }
162
163 /*
164  * This allows machines to provide their own "apm get power status" function.
165  */
166 void (*apm_get_power_status)(struct apm_power_info *) = __apm_get_power_status;
167 EXPORT_SYMBOL(apm_get_power_status);
168
169
170 /*
171  * APM event queue management.
172  */
173 static inline int queue_empty(struct apm_queue *q)
174 {
175         return q->event_head == q->event_tail;
176 }
177
178 static inline apm_event_t queue_get_event(struct apm_queue *q)
179 {
180         q->event_tail = (q->event_tail + 1) % APM_MAX_EVENTS;
181         return q->events[q->event_tail];
182 }
183
184 static void queue_add_event(struct apm_queue *q, apm_event_t event)
185 {
186         q->event_head = (q->event_head + 1) % APM_MAX_EVENTS;
187         if (q->event_head == q->event_tail) {
188                 static int notified;
189
190                 if (notified++ == 0)
191                     printk(KERN_ERR "apm: an event queue overflowed\n");
192                 q->event_tail = (q->event_tail + 1) % APM_MAX_EVENTS;
193         }
194         q->events[q->event_head] = event;
195 }
196
197 static void queue_event(apm_event_t event)
198 {
199         struct apm_user *as;
200
201         down_read(&user_list_lock);
202         list_for_each_entry(as, &apm_user_list, list) {
203                 if (as->reader)
204                         queue_add_event(&as->queue, event);
205         }
206         up_read(&user_list_lock);
207         wake_up_interruptible(&apm_waitqueue);
208 }
209
210 static ssize_t apm_read(struct file *fp, char __user *buf, size_t count, loff_t *ppos)
211 {
212         struct apm_user *as = fp->private_data;
213         apm_event_t event;
214         int i = count, ret = 0;
215
216         if (count < sizeof(apm_event_t))
217                 return -EINVAL;
218
219         if (queue_empty(&as->queue) && fp->f_flags & O_NONBLOCK)
220                 return -EAGAIN;
221
222         wait_event_interruptible(apm_waitqueue, !queue_empty(&as->queue));
223
224         while ((i >= sizeof(event)) && !queue_empty(&as->queue)) {
225                 event = queue_get_event(&as->queue);
226
227                 ret = -EFAULT;
228                 if (copy_to_user(buf, &event, sizeof(event)))
229                         break;
230
231                 mutex_lock(&state_lock);
232                 if (as->suspend_state == SUSPEND_PENDING &&
233                     (event == APM_SYS_SUSPEND || event == APM_USER_SUSPEND))
234                         as->suspend_state = SUSPEND_READ;
235                 mutex_unlock(&state_lock);
236
237                 buf += sizeof(event);
238                 i -= sizeof(event);
239         }
240
241         if (i < count)
242                 ret = count - i;
243
244         return ret;
245 }
246
247 static unsigned int apm_poll(struct file *fp, poll_table * wait)
248 {
249         struct apm_user *as = fp->private_data;
250
251         poll_wait(fp, &apm_waitqueue, wait);
252         return queue_empty(&as->queue) ? 0 : POLLIN | POLLRDNORM;
253 }
254
255 /*
256  * apm_ioctl - handle APM ioctl
257  *
258  * APM_IOC_SUSPEND
259  *   This IOCTL is overloaded, and performs two functions.  It is used to:
260  *     - initiate a suspend
261  *     - acknowledge a suspend read from /dev/apm_bios.
262  *   Only when everyone who has opened /dev/apm_bios with write permission
263  *   has acknowledge does the actual suspend happen.
264  */
265 static long
266 apm_ioctl(struct file *filp, u_int cmd, u_long arg)
267 {
268         struct apm_user *as = filp->private_data;
269         int err = -EINVAL;
270
271         if (!as->suser || !as->writer)
272                 return -EPERM;
273
274         switch (cmd) {
275         case APM_IOC_SUSPEND:
276                 mutex_lock(&state_lock);
277
278                 as->suspend_result = -EINTR;
279
280                 switch (as->suspend_state) {
281                 case SUSPEND_READ:
282                         /*
283                          * If we read a suspend command from /dev/apm_bios,
284                          * then the corresponding APM_IOC_SUSPEND ioctl is
285                          * interpreted as an acknowledge.
286                          */
287                         as->suspend_state = SUSPEND_ACKED;
288                         atomic_dec(&suspend_acks_pending);
289                         mutex_unlock(&state_lock);
290
291                         /*
292                          * suspend_acks_pending changed, the notifier needs to
293                          * be woken up for this
294                          */
295                         wake_up(&apm_suspend_waitqueue);
296
297                         /*
298                          * Wait for the suspend/resume to complete.  If there
299                          * are pending acknowledges, we wait here for them.
300                          */
301                         freezer_do_not_count();
302
303                         wait_event(apm_suspend_waitqueue,
304                                    as->suspend_state == SUSPEND_DONE);
305
306                         /*
307                          * Since we are waiting until the suspend is done, the
308                          * try_to_freeze() in freezer_count() will not trigger
309                          */
310                         freezer_count();
311                         break;
312                 case SUSPEND_ACKTO:
313                         as->suspend_result = -ETIMEDOUT;
314                         mutex_unlock(&state_lock);
315                         break;
316                 default:
317                         as->suspend_state = SUSPEND_WAIT;
318                         mutex_unlock(&state_lock);
319
320                         /*
321                          * Otherwise it is a request to suspend the system.
322                          * Just invoke pm_suspend(), we'll handle it from
323                          * there via the notifier.
324                          */
325                         as->suspend_result = pm_suspend(PM_SUSPEND_MEM);
326                 }
327
328                 mutex_lock(&state_lock);
329                 err = as->suspend_result;
330                 as->suspend_state = SUSPEND_NONE;
331                 mutex_unlock(&state_lock);
332                 break;
333         }
334
335         return err;
336 }
337
338 static int apm_release(struct inode * inode, struct file * filp)
339 {
340         struct apm_user *as = filp->private_data;
341
342         filp->private_data = NULL;
343
344         down_write(&user_list_lock);
345         list_del(&as->list);
346         up_write(&user_list_lock);
347
348         /*
349          * We are now unhooked from the chain.  As far as new
350          * events are concerned, we no longer exist.
351          */
352         mutex_lock(&state_lock);
353         if (as->suspend_state == SUSPEND_PENDING ||
354             as->suspend_state == SUSPEND_READ)
355                 atomic_dec(&suspend_acks_pending);
356         mutex_unlock(&state_lock);
357
358         wake_up(&apm_suspend_waitqueue);
359
360         kfree(as);
361         return 0;
362 }
363
364 static int apm_open(struct inode * inode, struct file * filp)
365 {
366         struct apm_user *as;
367
368         as = kzalloc(sizeof(*as), GFP_KERNEL);
369         if (as) {
370                 /*
371                  * XXX - this is a tiny bit broken, when we consider BSD
372                  * process accounting. If the device is opened by root, we
373                  * instantly flag that we used superuser privs. Who knows,
374                  * we might close the device immediately without doing a
375                  * privileged operation -- cevans
376                  */
377                 as->suser = capable(CAP_SYS_ADMIN);
378                 as->writer = (filp->f_mode & FMODE_WRITE) == FMODE_WRITE;
379                 as->reader = (filp->f_mode & FMODE_READ) == FMODE_READ;
380
381                 down_write(&user_list_lock);
382                 list_add(&as->list, &apm_user_list);
383                 up_write(&user_list_lock);
384
385                 filp->private_data = as;
386         }
387
388         return as ? 0 : -ENOMEM;
389 }
390
391 static const struct file_operations apm_bios_fops = {
392         .owner          = THIS_MODULE,
393         .read           = apm_read,
394         .poll           = apm_poll,
395         .unlocked_ioctl = apm_ioctl,
396         .open           = apm_open,
397         .release        = apm_release,
398         .llseek         = noop_llseek,
399 };
400
401 static struct miscdevice apm_device = {
402         .minor          = APM_MINOR_DEV,
403         .name           = "apm_bios",
404         .fops           = &apm_bios_fops
405 };
406
407
408 #ifdef CONFIG_PROC_FS
409 /*
410  * Arguments, with symbols from linux/apm_bios.h.
411  *
412  *   0) Linux driver version (this will change if format changes)
413  *   1) APM BIOS Version.  Usually 1.0, 1.1 or 1.2.
414  *   2) APM flags from APM Installation Check (0x00):
415  *      bit 0: APM_16_BIT_SUPPORT
416  *      bit 1: APM_32_BIT_SUPPORT
417  *      bit 2: APM_IDLE_SLOWS_CLOCK
418  *      bit 3: APM_BIOS_DISABLED
419  *      bit 4: APM_BIOS_DISENGAGED
420  *   3) AC line status
421  *      0x00: Off-line
422  *      0x01: On-line
423  *      0x02: On backup power (BIOS >= 1.1 only)
424  *      0xff: Unknown
425  *   4) Battery status
426  *      0x00: High
427  *      0x01: Low
428  *      0x02: Critical
429  *      0x03: Charging
430  *      0x04: Selected battery not present (BIOS >= 1.2 only)
431  *      0xff: Unknown
432  *   5) Battery flag
433  *      bit 0: High
434  *      bit 1: Low
435  *      bit 2: Critical
436  *      bit 3: Charging
437  *      bit 7: No system battery
438  *      0xff: Unknown
439  *   6) Remaining battery life (percentage of charge):
440  *      0-100: valid
441  *      -1: Unknown
442  *   7) Remaining battery life (time units):
443  *      Number of remaining minutes or seconds
444  *      -1: Unknown
445  *   8) min = minutes; sec = seconds
446  */
447 static int proc_apm_show(struct seq_file *m, void *v)
448 {
449         struct apm_power_info info;
450         char *units;
451
452         info.ac_line_status = 0xff;
453         info.battery_status = 0xff;
454         info.battery_flag   = 0xff;
455         info.battery_life   = -1;
456         info.time           = -1;
457         info.units          = -1;
458
459         if (apm_get_power_status)
460                 apm_get_power_status(&info);
461
462         switch (info.units) {
463         default:        units = "?";    break;
464         case 0:         units = "min";  break;
465         case 1:         units = "sec";  break;
466         }
467
468         seq_printf(m, "%s 1.2 0x%02x 0x%02x 0x%02x 0x%02x %d%% %d %s\n",
469                      driver_version, APM_32_BIT_SUPPORT,
470                      info.ac_line_status, info.battery_status,
471                      info.battery_flag, info.battery_life,
472                      info.time, units);
473
474         return 0;
475 }
476
477 static int proc_apm_open(struct inode *inode, struct file *file)
478 {
479         return single_open(file, proc_apm_show, NULL);
480 }
481
482 static const struct file_operations apm_proc_fops = {
483         .owner          = THIS_MODULE,
484         .open           = proc_apm_open,
485         .read           = seq_read,
486         .llseek         = seq_lseek,
487         .release        = single_release,
488 };
489 #endif
490
491 static int kapmd(void *arg)
492 {
493         do {
494                 apm_event_t event;
495
496                 wait_event_interruptible(kapmd_wait,
497                                 !queue_empty(&kapmd_queue) || kthread_should_stop());
498
499                 if (kthread_should_stop())
500                         break;
501
502                 spin_lock_irq(&kapmd_queue_lock);
503                 event = 0;
504                 if (!queue_empty(&kapmd_queue))
505                         event = queue_get_event(&kapmd_queue);
506                 spin_unlock_irq(&kapmd_queue_lock);
507
508                 switch (event) {
509                 case 0:
510                         break;
511
512                 case APM_LOW_BATTERY:
513                 case APM_POWER_STATUS_CHANGE:
514                         queue_event(event);
515                         break;
516
517                 case APM_USER_SUSPEND:
518                 case APM_SYS_SUSPEND:
519                         pm_suspend(PM_SUSPEND_MEM);
520                         break;
521
522                 case APM_CRITICAL_SUSPEND:
523                         atomic_inc(&userspace_notification_inhibit);
524                         pm_suspend(PM_SUSPEND_MEM);
525                         atomic_dec(&userspace_notification_inhibit);
526                         break;
527                 }
528         } while (1);
529
530         return 0;
531 }
532
533 static int apm_suspend_notifier(struct notifier_block *nb,
534                                 unsigned long event,
535                                 void *dummy)
536 {
537         struct apm_user *as;
538         int err;
539
540         /* short-cut emergency suspends */
541         if (atomic_read(&userspace_notification_inhibit))
542                 return NOTIFY_DONE;
543
544         switch (event) {
545         case PM_SUSPEND_PREPARE:
546                 /*
547                  * Queue an event to all "writer" users that we want
548                  * to suspend and need their ack.
549                  */
550                 mutex_lock(&state_lock);
551                 down_read(&user_list_lock);
552
553                 list_for_each_entry(as, &apm_user_list, list) {
554                         if (as->suspend_state != SUSPEND_WAIT && as->reader &&
555                             as->writer && as->suser) {
556                                 as->suspend_state = SUSPEND_PENDING;
557                                 atomic_inc(&suspend_acks_pending);
558                                 queue_add_event(&as->queue, APM_USER_SUSPEND);
559                         }
560                 }
561
562                 up_read(&user_list_lock);
563                 mutex_unlock(&state_lock);
564                 wake_up_interruptible(&apm_waitqueue);
565
566                 /*
567                  * Wait for the the suspend_acks_pending variable to drop to
568                  * zero, meaning everybody acked the suspend event (or the
569                  * process was killed.)
570                  *
571                  * If the app won't answer within a short while we assume it
572                  * locked up and ignore it.
573                  */
574                 err = wait_event_interruptible_timeout(
575                         apm_suspend_waitqueue,
576                         atomic_read(&suspend_acks_pending) == 0,
577                         5*HZ);
578
579                 /* timed out */
580                 if (err == 0) {
581                         /*
582                          * Move anybody who timed out to "ack timeout" state.
583                          *
584                          * We could time out and the userspace does the ACK
585                          * right after we time out but before we enter the
586                          * locked section here, but that's fine.
587                          */
588                         mutex_lock(&state_lock);
589                         down_read(&user_list_lock);
590                         list_for_each_entry(as, &apm_user_list, list) {
591                                 if (as->suspend_state == SUSPEND_PENDING ||
592                                     as->suspend_state == SUSPEND_READ) {
593                                         as->suspend_state = SUSPEND_ACKTO;
594                                         atomic_dec(&suspend_acks_pending);
595                                 }
596                         }
597                         up_read(&user_list_lock);
598                         mutex_unlock(&state_lock);
599                 }
600
601                 /* let suspend proceed */
602                 if (err >= 0)
603                         return NOTIFY_OK;
604
605                 /* interrupted by signal */
606                 return notifier_from_errno(err);
607
608         case PM_POST_SUSPEND:
609                 /*
610                  * Anyone on the APM queues will think we're still suspended.
611                  * Send a message so everyone knows we're now awake again.
612                  */
613                 queue_event(APM_NORMAL_RESUME);
614
615                 /*
616                  * Finally, wake up anyone who is sleeping on the suspend.
617                  */
618                 mutex_lock(&state_lock);
619                 down_read(&user_list_lock);
620                 list_for_each_entry(as, &apm_user_list, list) {
621                         if (as->suspend_state == SUSPEND_ACKED) {
622                                 /*
623                                  * TODO: maybe grab error code, needs core
624                                  * changes to push the error to the notifier
625                                  * chain (could use the second parameter if
626                                  * implemented)
627                                  */
628                                 as->suspend_result = 0;
629                                 as->suspend_state = SUSPEND_DONE;
630                         }
631                 }
632                 up_read(&user_list_lock);
633                 mutex_unlock(&state_lock);
634
635                 wake_up(&apm_suspend_waitqueue);
636                 return NOTIFY_OK;
637
638         default:
639                 return NOTIFY_DONE;
640         }
641 }
642
643 static struct notifier_block apm_notif_block = {
644         .notifier_call = apm_suspend_notifier,
645 };
646
647 static int __init apm_init(void)
648 {
649         int ret;
650
651         if (apm_disabled) {
652                 printk(KERN_NOTICE "apm: disabled on user request.\n");
653                 return -ENODEV;
654         }
655
656         kapmd_tsk = kthread_create(kapmd, NULL, "kapmd");
657         if (IS_ERR(kapmd_tsk)) {
658                 ret = PTR_ERR(kapmd_tsk);
659                 kapmd_tsk = NULL;
660                 goto out;
661         }
662         wake_up_process(kapmd_tsk);
663
664 #ifdef CONFIG_PROC_FS
665         proc_create("apm", 0, NULL, &apm_proc_fops);
666 #endif
667
668         ret = misc_register(&apm_device);
669         if (ret)
670                 goto out_stop;
671
672         ret = register_pm_notifier(&apm_notif_block);
673         if (ret)
674                 goto out_unregister;
675
676         return 0;
677
678  out_unregister:
679         misc_deregister(&apm_device);
680  out_stop:
681         remove_proc_entry("apm", NULL);
682         kthread_stop(kapmd_tsk);
683  out:
684         return ret;
685 }
686
687 static void __exit apm_exit(void)
688 {
689         unregister_pm_notifier(&apm_notif_block);
690         misc_deregister(&apm_device);
691         remove_proc_entry("apm", NULL);
692
693         kthread_stop(kapmd_tsk);
694 }
695
696 module_init(apm_init);
697 module_exit(apm_exit);
698
699 MODULE_AUTHOR("Stephen Rothwell");
700 MODULE_DESCRIPTION("Advanced Power Management");
701 MODULE_LICENSE("GPL");
702
703 #ifndef MODULE
704 static int __init apm_setup(char *str)
705 {
706         while ((str != NULL) && (*str != '\0')) {
707                 if (strncmp(str, "off", 3) == 0)
708                         apm_disabled = 1;
709                 if (strncmp(str, "on", 2) == 0)
710                         apm_disabled = 0;
711                 str = strchr(str, ',');
712                 if (str != NULL)
713                         str += strspn(str, ", \t");
714         }
715         return 1;
716 }
717
718 __setup("apm=", apm_setup);
719 #endif
720
721 /**
722  * apm_queue_event - queue an APM event for kapmd
723  * @event: APM event
724  *
725  * Queue an APM event for kapmd to process and ultimately take the
726  * appropriate action.  Only a subset of events are handled:
727  *   %APM_LOW_BATTERY
728  *   %APM_POWER_STATUS_CHANGE
729  *   %APM_USER_SUSPEND
730  *   %APM_SYS_SUSPEND
731  *   %APM_CRITICAL_SUSPEND
732  */
733 void apm_queue_event(apm_event_t event)
734 {
735         unsigned long flags;
736
737         spin_lock_irqsave(&kapmd_queue_lock, flags);
738         queue_add_event(&kapmd_queue, event);
739         spin_unlock_irqrestore(&kapmd_queue_lock, flags);
740
741         wake_up_interruptible(&kapmd_wait);
742 }
743 EXPORT_SYMBOL(apm_queue_event);