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