[POWERPC] PMU: Don't lock_kernel()
[safe/jmp/linux-2.6] / drivers / macintosh / via-pmu.c
1 /*
2  * Device driver for the via-pmu on Apple Powermacs.
3  *
4  * The VIA (versatile interface adapter) interfaces to the PMU,
5  * a 6805 microprocessor core whose primary function is to control
6  * battery charging and system power on the PowerBook 3400 and 2400.
7  * The PMU also controls the ADB (Apple Desktop Bus) which connects
8  * to the keyboard and mouse, as well as the non-volatile RAM
9  * and the RTC (real time clock) chip.
10  *
11  * Copyright (C) 1998 Paul Mackerras and Fabio Riccardi.
12  * Copyright (C) 2001-2002 Benjamin Herrenschmidt
13  *
14  * THIS DRIVER IS BECOMING A TOTAL MESS !
15  *  - Cleanup atomically disabling reply to PMU events after
16  *    a sleep or a freq. switch
17  *  - Move sleep code out of here to pmac_pm, merge into new
18  *    common PM infrastructure
19  *  - Save/Restore PCI space properly
20  *
21  */
22 #include <stdarg.h>
23 #include <linux/types.h>
24 #include <linux/errno.h>
25 #include <linux/kernel.h>
26 #include <linux/delay.h>
27 #include <linux/sched.h>
28 #include <linux/miscdevice.h>
29 #include <linux/blkdev.h>
30 #include <linux/pci.h>
31 #include <linux/slab.h>
32 #include <linux/poll.h>
33 #include <linux/adb.h>
34 #include <linux/pmu.h>
35 #include <linux/cuda.h>
36 #include <linux/module.h>
37 #include <linux/spinlock.h>
38 #include <linux/pm.h>
39 #include <linux/proc_fs.h>
40 #include <linux/init.h>
41 #include <linux/interrupt.h>
42 #include <linux/device.h>
43 #include <linux/sysdev.h>
44 #include <linux/freezer.h>
45 #include <linux/syscalls.h>
46 #include <linux/suspend.h>
47 #include <linux/cpu.h>
48 #include <asm/prom.h>
49 #include <asm/machdep.h>
50 #include <asm/io.h>
51 #include <asm/pgtable.h>
52 #include <asm/system.h>
53 #include <asm/sections.h>
54 #include <asm/irq.h>
55 #include <asm/pmac_feature.h>
56 #include <asm/pmac_pfunc.h>
57 #include <asm/pmac_low_i2c.h>
58 #include <asm/uaccess.h>
59 #include <asm/mmu_context.h>
60 #include <asm/cputable.h>
61 #include <asm/time.h>
62 #include <asm/backlight.h>
63
64 #include "via-pmu-event.h"
65
66 /* Some compile options */
67 #undef SUSPEND_USES_PMU
68 #define DEBUG_SLEEP
69 #undef HACKED_PCI_SAVE
70
71 /* Misc minor number allocated for /dev/pmu */
72 #define PMU_MINOR               154
73
74 /* How many iterations between battery polls */
75 #define BATTERY_POLLING_COUNT   2
76
77 static volatile unsigned char __iomem *via;
78
79 /* VIA registers - spaced 0x200 bytes apart */
80 #define RS              0x200           /* skip between registers */
81 #define B               0               /* B-side data */
82 #define A               RS              /* A-side data */
83 #define DIRB            (2*RS)          /* B-side direction (1=output) */
84 #define DIRA            (3*RS)          /* A-side direction (1=output) */
85 #define T1CL            (4*RS)          /* Timer 1 ctr/latch (low 8 bits) */
86 #define T1CH            (5*RS)          /* Timer 1 counter (high 8 bits) */
87 #define T1LL            (6*RS)          /* Timer 1 latch (low 8 bits) */
88 #define T1LH            (7*RS)          /* Timer 1 latch (high 8 bits) */
89 #define T2CL            (8*RS)          /* Timer 2 ctr/latch (low 8 bits) */
90 #define T2CH            (9*RS)          /* Timer 2 counter (high 8 bits) */
91 #define SR              (10*RS)         /* Shift register */
92 #define ACR             (11*RS)         /* Auxiliary control register */
93 #define PCR             (12*RS)         /* Peripheral control register */
94 #define IFR             (13*RS)         /* Interrupt flag register */
95 #define IER             (14*RS)         /* Interrupt enable register */
96 #define ANH             (15*RS)         /* A-side data, no handshake */
97
98 /* Bits in B data register: both active low */
99 #define TACK            0x08            /* Transfer acknowledge (input) */
100 #define TREQ            0x10            /* Transfer request (output) */
101
102 /* Bits in ACR */
103 #define SR_CTRL         0x1c            /* Shift register control bits */
104 #define SR_EXT          0x0c            /* Shift on external clock */
105 #define SR_OUT          0x10            /* Shift out if 1 */
106
107 /* Bits in IFR and IER */
108 #define IER_SET         0x80            /* set bits in IER */
109 #define IER_CLR         0               /* clear bits in IER */
110 #define SR_INT          0x04            /* Shift register full/empty */
111 #define CB2_INT         0x08
112 #define CB1_INT         0x10            /* transition on CB1 input */
113
114 static volatile enum pmu_state {
115         idle,
116         sending,
117         intack,
118         reading,
119         reading_intr,
120         locked,
121 } pmu_state;
122
123 static volatile enum int_data_state {
124         int_data_empty,
125         int_data_fill,
126         int_data_ready,
127         int_data_flush
128 } int_data_state[2] = { int_data_empty, int_data_empty };
129
130 static struct adb_request *current_req;
131 static struct adb_request *last_req;
132 static struct adb_request *req_awaiting_reply;
133 static unsigned char interrupt_data[2][32];
134 static int interrupt_data_len[2];
135 static int int_data_last;
136 static unsigned char *reply_ptr;
137 static int data_index;
138 static int data_len;
139 static volatile int adb_int_pending;
140 static volatile int disable_poll;
141 static struct device_node *vias;
142 static int pmu_kind = PMU_UNKNOWN;
143 static int pmu_fully_inited;
144 static int pmu_has_adb;
145 static struct device_node *gpio_node;
146 static unsigned char __iomem *gpio_reg;
147 static int gpio_irq = NO_IRQ;
148 static int gpio_irq_enabled = -1;
149 static volatile int pmu_suspended;
150 static spinlock_t pmu_lock;
151 static u8 pmu_intr_mask;
152 static int pmu_version;
153 static int drop_interrupts;
154 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
155 static int option_lid_wakeup = 1;
156 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
157 #if (defined(CONFIG_PM_SLEEP)&&defined(CONFIG_PPC32))||defined(CONFIG_PMAC_BACKLIGHT_LEGACY)
158 static int sleep_in_progress;
159 #endif
160 static unsigned long async_req_locks;
161 static unsigned int pmu_irq_stats[11];
162
163 static struct proc_dir_entry *proc_pmu_root;
164 static struct proc_dir_entry *proc_pmu_info;
165 static struct proc_dir_entry *proc_pmu_irqstats;
166 static struct proc_dir_entry *proc_pmu_options;
167 static int option_server_mode;
168
169 int pmu_battery_count;
170 int pmu_cur_battery;
171 unsigned int pmu_power_flags = PMU_PWR_AC_PRESENT;
172 struct pmu_battery_info pmu_batteries[PMU_MAX_BATTERIES];
173 static int query_batt_timer = BATTERY_POLLING_COUNT;
174 static struct adb_request batt_req;
175 static struct proc_dir_entry *proc_pmu_batt[PMU_MAX_BATTERIES];
176
177 int __fake_sleep;
178 int asleep;
179 BLOCKING_NOTIFIER_HEAD(sleep_notifier_list);
180
181 #ifdef CONFIG_ADB
182 static int adb_dev_map;
183 static int pmu_adb_flags;
184
185 static int pmu_probe(void);
186 static int pmu_init(void);
187 static int pmu_send_request(struct adb_request *req, int sync);
188 static int pmu_adb_autopoll(int devs);
189 static int pmu_adb_reset_bus(void);
190 #endif /* CONFIG_ADB */
191
192 static int init_pmu(void);
193 static void pmu_start(void);
194 static irqreturn_t via_pmu_interrupt(int irq, void *arg);
195 static irqreturn_t gpio1_interrupt(int irq, void *arg);
196 static int proc_get_info(char *page, char **start, off_t off,
197                           int count, int *eof, void *data);
198 static int proc_get_irqstats(char *page, char **start, off_t off,
199                           int count, int *eof, void *data);
200 static void pmu_pass_intr(unsigned char *data, int len);
201 static int proc_get_batt(char *page, char **start, off_t off,
202                         int count, int *eof, void *data);
203 static int proc_read_options(char *page, char **start, off_t off,
204                         int count, int *eof, void *data);
205 static int proc_write_options(struct file *file, const char __user *buffer,
206                         unsigned long count, void *data);
207
208 #ifdef CONFIG_ADB
209 struct adb_driver via_pmu_driver = {
210         "PMU",
211         pmu_probe,
212         pmu_init,
213         pmu_send_request,
214         pmu_adb_autopoll,
215         pmu_poll_adb,
216         pmu_adb_reset_bus
217 };
218 #endif /* CONFIG_ADB */
219
220 extern void low_sleep_handler(void);
221 extern void enable_kernel_altivec(void);
222 extern void enable_kernel_fp(void);
223
224 #ifdef DEBUG_SLEEP
225 int pmu_polled_request(struct adb_request *req);
226 int pmu_wink(struct adb_request *req);
227 #endif
228
229 /*
230  * This table indicates for each PMU opcode:
231  * - the number of data bytes to be sent with the command, or -1
232  *   if a length byte should be sent,
233  * - the number of response bytes which the PMU will return, or
234  *   -1 if it will send a length byte.
235  */
236 static const s8 pmu_data_len[256][2] = {
237 /*         0       1       2       3       4       5       6       7  */
238 /*00*/  {-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
239 /*08*/  {-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
240 /*10*/  { 1, 0},{ 1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
241 /*18*/  { 0, 1},{ 0, 1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{ 0, 0},
242 /*20*/  {-1, 0},{ 0, 0},{ 2, 0},{ 1, 0},{ 1, 0},{-1, 0},{-1, 0},{-1, 0},
243 /*28*/  { 0,-1},{ 0,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{ 0,-1},
244 /*30*/  { 4, 0},{20, 0},{-1, 0},{ 3, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
245 /*38*/  { 0, 4},{ 0,20},{ 2,-1},{ 2, 1},{ 3,-1},{-1,-1},{-1,-1},{ 4, 0},
246 /*40*/  { 1, 0},{ 1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
247 /*48*/  { 0, 1},{ 0, 1},{-1,-1},{ 1, 0},{ 1, 0},{-1,-1},{-1,-1},{-1,-1},
248 /*50*/  { 1, 0},{ 0, 0},{ 2, 0},{ 2, 0},{-1, 0},{ 1, 0},{ 3, 0},{ 1, 0},
249 /*58*/  { 0, 1},{ 1, 0},{ 0, 2},{ 0, 2},{ 0,-1},{-1,-1},{-1,-1},{-1,-1},
250 /*60*/  { 2, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
251 /*68*/  { 0, 3},{ 0, 3},{ 0, 2},{ 0, 8},{ 0,-1},{ 0,-1},{-1,-1},{-1,-1},
252 /*70*/  { 1, 0},{ 1, 0},{ 1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
253 /*78*/  { 0,-1},{ 0,-1},{-1,-1},{-1,-1},{-1,-1},{ 5, 1},{ 4, 1},{ 4, 1},
254 /*80*/  { 4, 0},{-1, 0},{ 0, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
255 /*88*/  { 0, 5},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
256 /*90*/  { 1, 0},{ 2, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
257 /*98*/  { 0, 1},{ 0, 1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
258 /*a0*/  { 2, 0},{ 2, 0},{ 2, 0},{ 4, 0},{-1, 0},{ 0, 0},{-1, 0},{-1, 0},
259 /*a8*/  { 1, 1},{ 1, 0},{ 3, 0},{ 2, 0},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
260 /*b0*/  {-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
261 /*b8*/  {-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
262 /*c0*/  {-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
263 /*c8*/  {-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
264 /*d0*/  { 0, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
265 /*d8*/  { 1, 1},{ 1, 1},{-1,-1},{-1,-1},{ 0, 1},{ 0,-1},{-1,-1},{-1,-1},
266 /*e0*/  {-1, 0},{ 4, 0},{ 0, 1},{-1, 0},{-1, 0},{ 4, 0},{-1, 0},{-1, 0},
267 /*e8*/  { 3,-1},{-1,-1},{ 0, 1},{-1,-1},{ 0,-1},{-1,-1},{-1,-1},{ 0, 0},
268 /*f0*/  {-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},{-1, 0},
269 /*f8*/  {-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1},
270 };
271
272 static char *pbook_type[] = {
273         "Unknown PowerBook",
274         "PowerBook 2400/3400/3500(G3)",
275         "PowerBook G3 Series",
276         "1999 PowerBook G3",
277         "Core99"
278 };
279
280 int __init find_via_pmu(void)
281 {
282         u64 taddr;
283         const u32 *reg;
284
285         if (via != 0)
286                 return 1;
287         vias = of_find_node_by_name(NULL, "via-pmu");
288         if (vias == NULL)
289                 return 0;
290
291         reg = of_get_property(vias, "reg", NULL);
292         if (reg == NULL) {
293                 printk(KERN_ERR "via-pmu: No \"reg\" property !\n");
294                 goto fail;
295         }
296         taddr = of_translate_address(vias, reg);
297         if (taddr == OF_BAD_ADDR) {
298                 printk(KERN_ERR "via-pmu: Can't translate address !\n");
299                 goto fail;
300         }
301
302         spin_lock_init(&pmu_lock);
303
304         pmu_has_adb = 1;
305
306         pmu_intr_mask = PMU_INT_PCEJECT |
307                         PMU_INT_SNDBRT |
308                         PMU_INT_ADB |
309                         PMU_INT_TICK;
310         
311         if (vias->parent->name && ((strcmp(vias->parent->name, "ohare") == 0)
312             || of_device_is_compatible(vias->parent, "ohare")))
313                 pmu_kind = PMU_OHARE_BASED;
314         else if (of_device_is_compatible(vias->parent, "paddington"))
315                 pmu_kind = PMU_PADDINGTON_BASED;
316         else if (of_device_is_compatible(vias->parent, "heathrow"))
317                 pmu_kind = PMU_HEATHROW_BASED;
318         else if (of_device_is_compatible(vias->parent, "Keylargo")
319                  || of_device_is_compatible(vias->parent, "K2-Keylargo")) {
320                 struct device_node *gpiop;
321                 struct device_node *adbp;
322                 u64 gaddr = OF_BAD_ADDR;
323
324                 pmu_kind = PMU_KEYLARGO_BASED;
325                 adbp = of_find_node_by_type(NULL, "adb");
326                 pmu_has_adb = (adbp != NULL);
327                 of_node_put(adbp);
328                 pmu_intr_mask = PMU_INT_PCEJECT |
329                                 PMU_INT_SNDBRT |
330                                 PMU_INT_ADB |
331                                 PMU_INT_TICK |
332                                 PMU_INT_ENVIRONMENT;
333                 
334                 gpiop = of_find_node_by_name(NULL, "gpio");
335                 if (gpiop) {
336                         reg = of_get_property(gpiop, "reg", NULL);
337                         if (reg)
338                                 gaddr = of_translate_address(gpiop, reg);
339                         if (gaddr != OF_BAD_ADDR)
340                                 gpio_reg = ioremap(gaddr, 0x10);
341                 }
342                 if (gpio_reg == NULL) {
343                         printk(KERN_ERR "via-pmu: Can't find GPIO reg !\n");
344                         goto fail_gpio;
345                 }
346         } else
347                 pmu_kind = PMU_UNKNOWN;
348
349         via = ioremap(taddr, 0x2000);
350         if (via == NULL) {
351                 printk(KERN_ERR "via-pmu: Can't map address !\n");
352                 goto fail;
353         }
354         
355         out_8(&via[IER], IER_CLR | 0x7f);       /* disable all intrs */
356         out_8(&via[IFR], 0x7f);                 /* clear IFR */
357
358         pmu_state = idle;
359
360         if (!init_pmu()) {
361                 via = NULL;
362                 return 0;
363         }
364
365         printk(KERN_INFO "PMU driver v%d initialized for %s, firmware: %02x\n",
366                PMU_DRIVER_VERSION, pbook_type[pmu_kind], pmu_version);
367                
368         sys_ctrler = SYS_CTRLER_PMU;
369         
370         return 1;
371  fail:
372         of_node_put(vias);
373         iounmap(gpio_reg);
374         gpio_reg = NULL;
375  fail_gpio:
376         vias = NULL;
377         return 0;
378 }
379
380 #ifdef CONFIG_ADB
381 static int pmu_probe(void)
382 {
383         return vias == NULL? -ENODEV: 0;
384 }
385
386 static int __init pmu_init(void)
387 {
388         if (vias == NULL)
389                 return -ENODEV;
390         return 0;
391 }
392 #endif /* CONFIG_ADB */
393
394 /*
395  * We can't wait until pmu_init gets called, that happens too late.
396  * It happens after IDE and SCSI initialization, which can take a few
397  * seconds, and by that time the PMU could have given up on us and
398  * turned us off.
399  * Thus this is called with arch_initcall rather than device_initcall.
400  */
401 static int __init via_pmu_start(void)
402 {
403         unsigned int irq;
404
405         if (vias == NULL)
406                 return -ENODEV;
407
408         batt_req.complete = 1;
409
410         irq = irq_of_parse_and_map(vias, 0);
411         if (irq == NO_IRQ) {
412                 printk(KERN_ERR "via-pmu: can't map interrupt\n");
413                 return -ENODEV;
414         }
415         if (request_irq(irq, via_pmu_interrupt, 0, "VIA-PMU", (void *)0)) {
416                 printk(KERN_ERR "via-pmu: can't request irq %d\n", irq);
417                 return -ENODEV;
418         }
419
420         if (pmu_kind == PMU_KEYLARGO_BASED) {
421                 gpio_node = of_find_node_by_name(NULL, "extint-gpio1");
422                 if (gpio_node == NULL)
423                         gpio_node = of_find_node_by_name(NULL,
424                                                          "pmu-interrupt");
425                 if (gpio_node)
426                         gpio_irq = irq_of_parse_and_map(gpio_node, 0);
427
428                 if (gpio_irq != NO_IRQ) {
429                         if (request_irq(gpio_irq, gpio1_interrupt, 0,
430                                         "GPIO1 ADB", (void *)0))
431                                 printk(KERN_ERR "pmu: can't get irq %d"
432                                        " (GPIO1)\n", gpio_irq);
433                         else
434                                 gpio_irq_enabled = 1;
435                 }
436         }
437
438         /* Enable interrupts */
439         out_8(&via[IER], IER_SET | SR_INT | CB1_INT);
440
441         pmu_fully_inited = 1;
442
443         /* Make sure PMU settle down before continuing. This is _very_ important
444          * since the IDE probe may shut interrupts down for quite a bit of time. If
445          * a PMU communication is pending while this happens, the PMU may timeout
446          * Not that on Core99 machines, the PMU keeps sending us environement
447          * messages, we should find a way to either fix IDE or make it call
448          * pmu_suspend() before masking interrupts. This can also happens while
449          * scolling with some fbdevs.
450          */
451         do {
452                 pmu_poll();
453         } while (pmu_state != idle);
454
455         return 0;
456 }
457
458 arch_initcall(via_pmu_start);
459
460 /*
461  * This has to be done after pci_init, which is a subsys_initcall.
462  */
463 static int __init via_pmu_dev_init(void)
464 {
465         if (vias == NULL)
466                 return -ENODEV;
467
468 #ifdef CONFIG_PMAC_BACKLIGHT
469         /* Initialize backlight */
470         pmu_backlight_init();
471 #endif
472
473 #ifdef CONFIG_PPC32
474         if (machine_is_compatible("AAPL,3400/2400") ||
475                 machine_is_compatible("AAPL,3500")) {
476                 int mb = pmac_call_feature(PMAC_FTR_GET_MB_INFO,
477                         NULL, PMAC_MB_INFO_MODEL, 0);
478                 pmu_battery_count = 1;
479                 if (mb == PMAC_TYPE_COMET)
480                         pmu_batteries[0].flags |= PMU_BATT_TYPE_COMET;
481                 else
482                         pmu_batteries[0].flags |= PMU_BATT_TYPE_HOOPER;
483         } else if (machine_is_compatible("AAPL,PowerBook1998") ||
484                 machine_is_compatible("PowerBook1,1")) {
485                 pmu_battery_count = 2;
486                 pmu_batteries[0].flags |= PMU_BATT_TYPE_SMART;
487                 pmu_batteries[1].flags |= PMU_BATT_TYPE_SMART;
488         } else {
489                 struct device_node* prim =
490                         of_find_node_by_name(NULL, "power-mgt");
491                 const u32 *prim_info = NULL;
492                 if (prim)
493                         prim_info = of_get_property(prim, "prim-info", NULL);
494                 if (prim_info) {
495                         /* Other stuffs here yet unknown */
496                         pmu_battery_count = (prim_info[6] >> 16) & 0xff;
497                         pmu_batteries[0].flags |= PMU_BATT_TYPE_SMART;
498                         if (pmu_battery_count > 1)
499                                 pmu_batteries[1].flags |= PMU_BATT_TYPE_SMART;
500                 }
501                 of_node_put(prim);
502         }
503 #endif /* CONFIG_PPC32 */
504
505         /* Create /proc/pmu */
506         proc_pmu_root = proc_mkdir("pmu", NULL);
507         if (proc_pmu_root) {
508                 long i;
509
510                 for (i=0; i<pmu_battery_count; i++) {
511                         char title[16];
512                         sprintf(title, "battery_%ld", i);
513                         proc_pmu_batt[i] = create_proc_read_entry(title, 0, proc_pmu_root,
514                                                 proc_get_batt, (void *)i);
515                 }
516
517                 proc_pmu_info = create_proc_read_entry("info", 0, proc_pmu_root,
518                                         proc_get_info, NULL);
519                 proc_pmu_irqstats = create_proc_read_entry("interrupts", 0, proc_pmu_root,
520                                         proc_get_irqstats, NULL);
521                 proc_pmu_options = create_proc_entry("options", 0600, proc_pmu_root);
522                 if (proc_pmu_options) {
523                         proc_pmu_options->read_proc = proc_read_options;
524                         proc_pmu_options->write_proc = proc_write_options;
525                 }
526         }
527         return 0;
528 }
529
530 device_initcall(via_pmu_dev_init);
531
532 static int
533 init_pmu(void)
534 {
535         int timeout;
536         struct adb_request req;
537
538         out_8(&via[B], via[B] | TREQ);                  /* negate TREQ */
539         out_8(&via[DIRB], (via[DIRB] | TREQ) & ~TACK);  /* TACK in, TREQ out */
540
541         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, pmu_intr_mask);
542         timeout =  100000;
543         while (!req.complete) {
544                 if (--timeout < 0) {
545                         printk(KERN_ERR "init_pmu: no response from PMU\n");
546                         return 0;
547                 }
548                 udelay(10);
549                 pmu_poll();
550         }
551
552         /* ack all pending interrupts */
553         timeout = 100000;
554         interrupt_data[0][0] = 1;
555         while (interrupt_data[0][0] || pmu_state != idle) {
556                 if (--timeout < 0) {
557                         printk(KERN_ERR "init_pmu: timed out acking intrs\n");
558                         return 0;
559                 }
560                 if (pmu_state == idle)
561                         adb_int_pending = 1;
562                 via_pmu_interrupt(0, NULL);
563                 udelay(10);
564         }
565
566         /* Tell PMU we are ready.  */
567         if (pmu_kind == PMU_KEYLARGO_BASED) {
568                 pmu_request(&req, NULL, 2, PMU_SYSTEM_READY, 2);
569                 while (!req.complete)
570                         pmu_poll();
571         }
572
573         /* Read PMU version */
574         pmu_request(&req, NULL, 1, PMU_GET_VERSION);
575         pmu_wait_complete(&req);
576         if (req.reply_len > 0)
577                 pmu_version = req.reply[0];
578         
579         /* Read server mode setting */
580         if (pmu_kind == PMU_KEYLARGO_BASED) {
581                 pmu_request(&req, NULL, 2, PMU_POWER_EVENTS,
582                             PMU_PWR_GET_POWERUP_EVENTS);
583                 pmu_wait_complete(&req);
584                 if (req.reply_len == 2) {
585                         if (req.reply[1] & PMU_PWR_WAKEUP_AC_INSERT)
586                                 option_server_mode = 1;
587                         printk(KERN_INFO "via-pmu: Server Mode is %s\n",
588                                option_server_mode ? "enabled" : "disabled");
589                 }
590         }
591         return 1;
592 }
593
594 int
595 pmu_get_model(void)
596 {
597         return pmu_kind;
598 }
599
600 static void pmu_set_server_mode(int server_mode)
601 {
602         struct adb_request req;
603
604         if (pmu_kind != PMU_KEYLARGO_BASED)
605                 return;
606
607         option_server_mode = server_mode;
608         pmu_request(&req, NULL, 2, PMU_POWER_EVENTS, PMU_PWR_GET_POWERUP_EVENTS);
609         pmu_wait_complete(&req);
610         if (req.reply_len < 2)
611                 return;
612         if (server_mode)
613                 pmu_request(&req, NULL, 4, PMU_POWER_EVENTS,
614                             PMU_PWR_SET_POWERUP_EVENTS,
615                             req.reply[0], PMU_PWR_WAKEUP_AC_INSERT); 
616         else
617                 pmu_request(&req, NULL, 4, PMU_POWER_EVENTS,
618                             PMU_PWR_CLR_POWERUP_EVENTS,
619                             req.reply[0], PMU_PWR_WAKEUP_AC_INSERT); 
620         pmu_wait_complete(&req);
621 }
622
623 /* This new version of the code for 2400/3400/3500 powerbooks
624  * is inspired from the implementation in gkrellm-pmu
625  */
626 static void
627 done_battery_state_ohare(struct adb_request* req)
628 {
629         /* format:
630          *  [0]    :  flags
631          *    0x01 :  AC indicator
632          *    0x02 :  charging
633          *    0x04 :  battery exist
634          *    0x08 :  
635          *    0x10 :  
636          *    0x20 :  full charged
637          *    0x40 :  pcharge reset
638          *    0x80 :  battery exist
639          *
640          *  [1][2] :  battery voltage
641          *  [3]    :  CPU temperature
642          *  [4]    :  battery temperature
643          *  [5]    :  current
644          *  [6][7] :  pcharge
645          *              --tkoba
646          */
647         unsigned int bat_flags = PMU_BATT_TYPE_HOOPER;
648         long pcharge, charge, vb, vmax, lmax;
649         long vmax_charging, vmax_charged;
650         long amperage, voltage, time, max;
651         int mb = pmac_call_feature(PMAC_FTR_GET_MB_INFO,
652                         NULL, PMAC_MB_INFO_MODEL, 0);
653
654         if (req->reply[0] & 0x01)
655                 pmu_power_flags |= PMU_PWR_AC_PRESENT;
656         else
657                 pmu_power_flags &= ~PMU_PWR_AC_PRESENT;
658         
659         if (mb == PMAC_TYPE_COMET) {
660                 vmax_charged = 189;
661                 vmax_charging = 213;
662                 lmax = 6500;
663         } else {
664                 vmax_charged = 330;
665                 vmax_charging = 330;
666                 lmax = 6500;
667         }
668         vmax = vmax_charged;
669
670         /* If battery installed */
671         if (req->reply[0] & 0x04) {
672                 bat_flags |= PMU_BATT_PRESENT;
673                 if (req->reply[0] & 0x02)
674                         bat_flags |= PMU_BATT_CHARGING;
675                 vb = (req->reply[1] << 8) | req->reply[2];
676                 voltage = (vb * 265 + 72665) / 10;
677                 amperage = req->reply[5];
678                 if ((req->reply[0] & 0x01) == 0) {
679                         if (amperage > 200)
680                                 vb += ((amperage - 200) * 15)/100;
681                 } else if (req->reply[0] & 0x02) {
682                         vb = (vb * 97) / 100;
683                         vmax = vmax_charging;
684                 }
685                 charge = (100 * vb) / vmax;
686                 if (req->reply[0] & 0x40) {
687                         pcharge = (req->reply[6] << 8) + req->reply[7];
688                         if (pcharge > lmax)
689                                 pcharge = lmax;
690                         pcharge *= 100;
691                         pcharge = 100 - pcharge / lmax;
692                         if (pcharge < charge)
693                                 charge = pcharge;
694                 }
695                 if (amperage > 0)
696                         time = (charge * 16440) / amperage;
697                 else
698                         time = 0;
699                 max = 100;
700                 amperage = -amperage;
701         } else
702                 charge = max = amperage = voltage = time = 0;
703
704         pmu_batteries[pmu_cur_battery].flags = bat_flags;
705         pmu_batteries[pmu_cur_battery].charge = charge;
706         pmu_batteries[pmu_cur_battery].max_charge = max;
707         pmu_batteries[pmu_cur_battery].amperage = amperage;
708         pmu_batteries[pmu_cur_battery].voltage = voltage;
709         pmu_batteries[pmu_cur_battery].time_remaining = time;
710
711         clear_bit(0, &async_req_locks);
712 }
713
714 static void
715 done_battery_state_smart(struct adb_request* req)
716 {
717         /* format:
718          *  [0] : format of this structure (known: 3,4,5)
719          *  [1] : flags
720          *  
721          *  format 3 & 4:
722          *  
723          *  [2] : charge
724          *  [3] : max charge
725          *  [4] : current
726          *  [5] : voltage
727          *  
728          *  format 5:
729          *  
730          *  [2][3] : charge
731          *  [4][5] : max charge
732          *  [6][7] : current
733          *  [8][9] : voltage
734          */
735          
736         unsigned int bat_flags = PMU_BATT_TYPE_SMART;
737         int amperage;
738         unsigned int capa, max, voltage;
739         
740         if (req->reply[1] & 0x01)
741                 pmu_power_flags |= PMU_PWR_AC_PRESENT;
742         else
743                 pmu_power_flags &= ~PMU_PWR_AC_PRESENT;
744
745
746         capa = max = amperage = voltage = 0;
747         
748         if (req->reply[1] & 0x04) {
749                 bat_flags |= PMU_BATT_PRESENT;
750                 switch(req->reply[0]) {
751                         case 3:
752                         case 4: capa = req->reply[2];
753                                 max = req->reply[3];
754                                 amperage = *((signed char *)&req->reply[4]);
755                                 voltage = req->reply[5];
756                                 break;
757                         case 5: capa = (req->reply[2] << 8) | req->reply[3];
758                                 max = (req->reply[4] << 8) | req->reply[5];
759                                 amperage = *((signed short *)&req->reply[6]);
760                                 voltage = (req->reply[8] << 8) | req->reply[9];
761                                 break;
762                         default:
763                                 printk(KERN_WARNING "pmu.c : unrecognized battery info, len: %d, %02x %02x %02x %02x\n",
764                                         req->reply_len, req->reply[0], req->reply[1], req->reply[2], req->reply[3]);
765                                 break;
766                 }
767         }
768
769         if ((req->reply[1] & 0x01) && (amperage > 0))
770                 bat_flags |= PMU_BATT_CHARGING;
771
772         pmu_batteries[pmu_cur_battery].flags = bat_flags;
773         pmu_batteries[pmu_cur_battery].charge = capa;
774         pmu_batteries[pmu_cur_battery].max_charge = max;
775         pmu_batteries[pmu_cur_battery].amperage = amperage;
776         pmu_batteries[pmu_cur_battery].voltage = voltage;
777         if (amperage) {
778                 if ((req->reply[1] & 0x01) && (amperage > 0))
779                         pmu_batteries[pmu_cur_battery].time_remaining
780                                 = ((max-capa) * 3600) / amperage;
781                 else
782                         pmu_batteries[pmu_cur_battery].time_remaining
783                                 = (capa * 3600) / (-amperage);
784         } else
785                 pmu_batteries[pmu_cur_battery].time_remaining = 0;
786
787         pmu_cur_battery = (pmu_cur_battery + 1) % pmu_battery_count;
788
789         clear_bit(0, &async_req_locks);
790 }
791
792 static void
793 query_battery_state(void)
794 {
795         if (test_and_set_bit(0, &async_req_locks))
796                 return;
797         if (pmu_kind == PMU_OHARE_BASED)
798                 pmu_request(&batt_req, done_battery_state_ohare,
799                         1, PMU_BATTERY_STATE);
800         else
801                 pmu_request(&batt_req, done_battery_state_smart,
802                         2, PMU_SMART_BATTERY_STATE, pmu_cur_battery+1);
803 }
804
805 static int
806 proc_get_info(char *page, char **start, off_t off,
807                 int count, int *eof, void *data)
808 {
809         char* p = page;
810
811         p += sprintf(p, "PMU driver version     : %d\n", PMU_DRIVER_VERSION);
812         p += sprintf(p, "PMU firmware version   : %02x\n", pmu_version);
813         p += sprintf(p, "AC Power               : %d\n",
814                 ((pmu_power_flags & PMU_PWR_AC_PRESENT) != 0) || pmu_battery_count == 0);
815         p += sprintf(p, "Battery count          : %d\n", pmu_battery_count);
816
817         return p - page;
818 }
819
820 static int
821 proc_get_irqstats(char *page, char **start, off_t off,
822                   int count, int *eof, void *data)
823 {
824         int i;
825         char* p = page;
826         static const char *irq_names[] = {
827                 "Total CB1 triggered events",
828                 "Total GPIO1 triggered events",
829                 "PC-Card eject button",
830                 "Sound/Brightness button",
831                 "ADB message",
832                 "Battery state change",
833                 "Environment interrupt",
834                 "Tick timer",
835                 "Ghost interrupt (zero len)",
836                 "Empty interrupt (empty mask)",
837                 "Max irqs in a row"
838         };
839
840         for (i=0; i<11; i++) {
841                 p += sprintf(p, " %2u: %10u (%s)\n",
842                              i, pmu_irq_stats[i], irq_names[i]);
843         }
844         return p - page;
845 }
846
847 static int
848 proc_get_batt(char *page, char **start, off_t off,
849                 int count, int *eof, void *data)
850 {
851         long batnum = (long)data;
852         char *p = page;
853         
854         p += sprintf(p, "\n");
855         p += sprintf(p, "flags      : %08x\n",
856                 pmu_batteries[batnum].flags);
857         p += sprintf(p, "charge     : %d\n",
858                 pmu_batteries[batnum].charge);
859         p += sprintf(p, "max_charge : %d\n",
860                 pmu_batteries[batnum].max_charge);
861         p += sprintf(p, "current    : %d\n",
862                 pmu_batteries[batnum].amperage);
863         p += sprintf(p, "voltage    : %d\n",
864                 pmu_batteries[batnum].voltage);
865         p += sprintf(p, "time rem.  : %d\n",
866                 pmu_batteries[batnum].time_remaining);
867
868         return p - page;
869 }
870
871 static int
872 proc_read_options(char *page, char **start, off_t off,
873                         int count, int *eof, void *data)
874 {
875         char *p = page;
876
877 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
878         if (pmu_kind == PMU_KEYLARGO_BASED &&
879             pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,-1) >= 0)
880                 p += sprintf(p, "lid_wakeup=%d\n", option_lid_wakeup);
881 #endif
882         if (pmu_kind == PMU_KEYLARGO_BASED)
883                 p += sprintf(p, "server_mode=%d\n", option_server_mode);
884
885         return p - page;
886 }
887                         
888 static int
889 proc_write_options(struct file *file, const char __user *buffer,
890                         unsigned long count, void *data)
891 {
892         char tmp[33];
893         char *label, *val;
894         unsigned long fcount = count;
895         
896         if (!count)
897                 return -EINVAL;
898         if (count > 32)
899                 count = 32;
900         if (copy_from_user(tmp, buffer, count))
901                 return -EFAULT;
902         tmp[count] = 0;
903
904         label = tmp;
905         while(*label == ' ')
906                 label++;
907         val = label;
908         while(*val && (*val != '=')) {
909                 if (*val == ' ')
910                         *val = 0;
911                 val++;
912         }
913         if ((*val) == 0)
914                 return -EINVAL;
915         *(val++) = 0;
916         while(*val == ' ')
917                 val++;
918 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
919         if (pmu_kind == PMU_KEYLARGO_BASED &&
920             pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,-1) >= 0)
921                 if (!strcmp(label, "lid_wakeup"))
922                         option_lid_wakeup = ((*val) == '1');
923 #endif
924         if (pmu_kind == PMU_KEYLARGO_BASED && !strcmp(label, "server_mode")) {
925                 int new_value;
926                 new_value = ((*val) == '1');
927                 if (new_value != option_server_mode)
928                         pmu_set_server_mode(new_value);
929         }
930         return fcount;
931 }
932
933 #ifdef CONFIG_ADB
934 /* Send an ADB command */
935 static int
936 pmu_send_request(struct adb_request *req, int sync)
937 {
938         int i, ret;
939
940         if ((vias == NULL) || (!pmu_fully_inited)) {
941                 req->complete = 1;
942                 return -ENXIO;
943         }
944
945         ret = -EINVAL;
946
947         switch (req->data[0]) {
948         case PMU_PACKET:
949                 for (i = 0; i < req->nbytes - 1; ++i)
950                         req->data[i] = req->data[i+1];
951                 --req->nbytes;
952                 if (pmu_data_len[req->data[0]][1] != 0) {
953                         req->reply[0] = ADB_RET_OK;
954                         req->reply_len = 1;
955                 } else
956                         req->reply_len = 0;
957                 ret = pmu_queue_request(req);
958                 break;
959         case CUDA_PACKET:
960                 switch (req->data[1]) {
961                 case CUDA_GET_TIME:
962                         if (req->nbytes != 2)
963                                 break;
964                         req->data[0] = PMU_READ_RTC;
965                         req->nbytes = 1;
966                         req->reply_len = 3;
967                         req->reply[0] = CUDA_PACKET;
968                         req->reply[1] = 0;
969                         req->reply[2] = CUDA_GET_TIME;
970                         ret = pmu_queue_request(req);
971                         break;
972                 case CUDA_SET_TIME:
973                         if (req->nbytes != 6)
974                                 break;
975                         req->data[0] = PMU_SET_RTC;
976                         req->nbytes = 5;
977                         for (i = 1; i <= 4; ++i)
978                                 req->data[i] = req->data[i+1];
979                         req->reply_len = 3;
980                         req->reply[0] = CUDA_PACKET;
981                         req->reply[1] = 0;
982                         req->reply[2] = CUDA_SET_TIME;
983                         ret = pmu_queue_request(req);
984                         break;
985                 }
986                 break;
987         case ADB_PACKET:
988                 if (!pmu_has_adb)
989                         return -ENXIO;
990                 for (i = req->nbytes - 1; i > 1; --i)
991                         req->data[i+2] = req->data[i];
992                 req->data[3] = req->nbytes - 2;
993                 req->data[2] = pmu_adb_flags;
994                 /*req->data[1] = req->data[1];*/
995                 req->data[0] = PMU_ADB_CMD;
996                 req->nbytes += 2;
997                 req->reply_expected = 1;
998                 req->reply_len = 0;
999                 ret = pmu_queue_request(req);
1000                 break;
1001         }
1002         if (ret) {
1003                 req->complete = 1;
1004                 return ret;
1005         }
1006
1007         if (sync)
1008                 while (!req->complete)
1009                         pmu_poll();
1010
1011         return 0;
1012 }
1013
1014 /* Enable/disable autopolling */
1015 static int
1016 pmu_adb_autopoll(int devs)
1017 {
1018         struct adb_request req;
1019
1020         if ((vias == NULL) || (!pmu_fully_inited) || !pmu_has_adb)
1021                 return -ENXIO;
1022
1023         if (devs) {
1024                 adb_dev_map = devs;
1025                 pmu_request(&req, NULL, 5, PMU_ADB_CMD, 0, 0x86,
1026                             adb_dev_map >> 8, adb_dev_map);
1027                 pmu_adb_flags = 2;
1028         } else {
1029                 pmu_request(&req, NULL, 1, PMU_ADB_POLL_OFF);
1030                 pmu_adb_flags = 0;
1031         }
1032         while (!req.complete)
1033                 pmu_poll();
1034         return 0;
1035 }
1036
1037 /* Reset the ADB bus */
1038 static int
1039 pmu_adb_reset_bus(void)
1040 {
1041         struct adb_request req;
1042         int save_autopoll = adb_dev_map;
1043
1044         if ((vias == NULL) || (!pmu_fully_inited) || !pmu_has_adb)
1045                 return -ENXIO;
1046
1047         /* anyone got a better idea?? */
1048         pmu_adb_autopoll(0);
1049
1050         req.nbytes = 5;
1051         req.done = NULL;
1052         req.data[0] = PMU_ADB_CMD;
1053         req.data[1] = 0;
1054         req.data[2] = ADB_BUSRESET;
1055         req.data[3] = 0;
1056         req.data[4] = 0;
1057         req.reply_len = 0;
1058         req.reply_expected = 1;
1059         if (pmu_queue_request(&req) != 0) {
1060                 printk(KERN_ERR "pmu_adb_reset_bus: pmu_queue_request failed\n");
1061                 return -EIO;
1062         }
1063         pmu_wait_complete(&req);
1064
1065         if (save_autopoll != 0)
1066                 pmu_adb_autopoll(save_autopoll);
1067
1068         return 0;
1069 }
1070 #endif /* CONFIG_ADB */
1071
1072 /* Construct and send a pmu request */
1073 int
1074 pmu_request(struct adb_request *req, void (*done)(struct adb_request *),
1075             int nbytes, ...)
1076 {
1077         va_list list;
1078         int i;
1079
1080         if (vias == NULL)
1081                 return -ENXIO;
1082
1083         if (nbytes < 0 || nbytes > 32) {
1084                 printk(KERN_ERR "pmu_request: bad nbytes (%d)\n", nbytes);
1085                 req->complete = 1;
1086                 return -EINVAL;
1087         }
1088         req->nbytes = nbytes;
1089         req->done = done;
1090         va_start(list, nbytes);
1091         for (i = 0; i < nbytes; ++i)
1092                 req->data[i] = va_arg(list, int);
1093         va_end(list);
1094         req->reply_len = 0;
1095         req->reply_expected = 0;
1096         return pmu_queue_request(req);
1097 }
1098
1099 int
1100 pmu_queue_request(struct adb_request *req)
1101 {
1102         unsigned long flags;
1103         int nsend;
1104
1105         if (via == NULL) {
1106                 req->complete = 1;
1107                 return -ENXIO;
1108         }
1109         if (req->nbytes <= 0) {
1110                 req->complete = 1;
1111                 return 0;
1112         }
1113         nsend = pmu_data_len[req->data[0]][0];
1114         if (nsend >= 0 && req->nbytes != nsend + 1) {
1115                 req->complete = 1;
1116                 return -EINVAL;
1117         }
1118
1119         req->next = NULL;
1120         req->sent = 0;
1121         req->complete = 0;
1122
1123         spin_lock_irqsave(&pmu_lock, flags);
1124         if (current_req != 0) {
1125                 last_req->next = req;
1126                 last_req = req;
1127         } else {
1128                 current_req = req;
1129                 last_req = req;
1130                 if (pmu_state == idle)
1131                         pmu_start();
1132         }
1133         spin_unlock_irqrestore(&pmu_lock, flags);
1134
1135         return 0;
1136 }
1137
1138 static inline void
1139 wait_for_ack(void)
1140 {
1141         /* Sightly increased the delay, I had one occurrence of the message
1142          * reported
1143          */
1144         int timeout = 4000;
1145         while ((in_8(&via[B]) & TACK) == 0) {
1146                 if (--timeout < 0) {
1147                         printk(KERN_ERR "PMU not responding (!ack)\n");
1148                         return;
1149                 }
1150                 udelay(10);
1151         }
1152 }
1153
1154 /* New PMU seems to be very sensitive to those timings, so we make sure
1155  * PCI is flushed immediately */
1156 static inline void
1157 send_byte(int x)
1158 {
1159         volatile unsigned char __iomem *v = via;
1160
1161         out_8(&v[ACR], in_8(&v[ACR]) | SR_OUT | SR_EXT);
1162         out_8(&v[SR], x);
1163         out_8(&v[B], in_8(&v[B]) & ~TREQ);              /* assert TREQ */
1164         (void)in_8(&v[B]);
1165 }
1166
1167 static inline void
1168 recv_byte(void)
1169 {
1170         volatile unsigned char __iomem *v = via;
1171
1172         out_8(&v[ACR], (in_8(&v[ACR]) & ~SR_OUT) | SR_EXT);
1173         in_8(&v[SR]);           /* resets SR */
1174         out_8(&v[B], in_8(&v[B]) & ~TREQ);
1175         (void)in_8(&v[B]);
1176 }
1177
1178 static inline void
1179 pmu_done(struct adb_request *req)
1180 {
1181         void (*done)(struct adb_request *) = req->done;
1182         mb();
1183         req->complete = 1;
1184         /* Here, we assume that if the request has a done member, the
1185          * struct request will survive to setting req->complete to 1
1186          */
1187         if (done)
1188                 (*done)(req);
1189 }
1190
1191 static void
1192 pmu_start(void)
1193 {
1194         struct adb_request *req;
1195
1196         /* assert pmu_state == idle */
1197         /* get the packet to send */
1198         req = current_req;
1199         if (req == 0 || pmu_state != idle
1200             || (/*req->reply_expected && */req_awaiting_reply))
1201                 return;
1202
1203         pmu_state = sending;
1204         data_index = 1;
1205         data_len = pmu_data_len[req->data[0]][0];
1206
1207         /* Sounds safer to make sure ACK is high before writing. This helped
1208          * kill a problem with ADB and some iBooks
1209          */
1210         wait_for_ack();
1211         /* set the shift register to shift out and send a byte */
1212         send_byte(req->data[0]);
1213 }
1214
1215 void
1216 pmu_poll(void)
1217 {
1218         if (!via)
1219                 return;
1220         if (disable_poll)
1221                 return;
1222         via_pmu_interrupt(0, NULL);
1223 }
1224
1225 void
1226 pmu_poll_adb(void)
1227 {
1228         if (!via)
1229                 return;
1230         if (disable_poll)
1231                 return;
1232         /* Kicks ADB read when PMU is suspended */
1233         adb_int_pending = 1;
1234         do {
1235                 via_pmu_interrupt(0, NULL);
1236         } while (pmu_suspended && (adb_int_pending || pmu_state != idle
1237                 || req_awaiting_reply));
1238 }
1239
1240 void
1241 pmu_wait_complete(struct adb_request *req)
1242 {
1243         if (!via)
1244                 return;
1245         while((pmu_state != idle && pmu_state != locked) || !req->complete)
1246                 via_pmu_interrupt(0, NULL);
1247 }
1248
1249 /* This function loops until the PMU is idle and prevents it from
1250  * anwsering to ADB interrupts. pmu_request can still be called.
1251  * This is done to avoid spurrious shutdowns when we know we'll have
1252  * interrupts switched off for a long time
1253  */
1254 void
1255 pmu_suspend(void)
1256 {
1257         unsigned long flags;
1258 #ifdef SUSPEND_USES_PMU
1259         struct adb_request *req;
1260 #endif
1261         if (!via)
1262                 return;
1263         
1264         spin_lock_irqsave(&pmu_lock, flags);
1265         pmu_suspended++;
1266         if (pmu_suspended > 1) {
1267                 spin_unlock_irqrestore(&pmu_lock, flags);
1268                 return;
1269         }
1270
1271         do {
1272                 spin_unlock_irqrestore(&pmu_lock, flags);
1273                 if (req_awaiting_reply)
1274                         adb_int_pending = 1;
1275                 via_pmu_interrupt(0, NULL);
1276                 spin_lock_irqsave(&pmu_lock, flags);
1277                 if (!adb_int_pending && pmu_state == idle && !req_awaiting_reply) {
1278 #ifdef SUSPEND_USES_PMU
1279                         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, 0);
1280                         spin_unlock_irqrestore(&pmu_lock, flags);
1281                         while(!req.complete)
1282                                 pmu_poll();
1283 #else /* SUSPEND_USES_PMU */
1284                         if (gpio_irq >= 0)
1285                                 disable_irq_nosync(gpio_irq);
1286                         out_8(&via[IER], CB1_INT | IER_CLR);
1287                         spin_unlock_irqrestore(&pmu_lock, flags);
1288 #endif /* SUSPEND_USES_PMU */
1289                         break;
1290                 }
1291         } while (1);
1292 }
1293
1294 void
1295 pmu_resume(void)
1296 {
1297         unsigned long flags;
1298
1299         if (!via || (pmu_suspended < 1))
1300                 return;
1301
1302         spin_lock_irqsave(&pmu_lock, flags);
1303         pmu_suspended--;
1304         if (pmu_suspended > 0) {
1305                 spin_unlock_irqrestore(&pmu_lock, flags);
1306                 return;
1307         }
1308         adb_int_pending = 1;
1309 #ifdef SUSPEND_USES_PMU
1310         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, pmu_intr_mask);
1311         spin_unlock_irqrestore(&pmu_lock, flags);
1312         while(!req.complete)
1313                 pmu_poll();
1314 #else /* SUSPEND_USES_PMU */
1315         if (gpio_irq >= 0)
1316                 enable_irq(gpio_irq);
1317         out_8(&via[IER], CB1_INT | IER_SET);
1318         spin_unlock_irqrestore(&pmu_lock, flags);
1319         pmu_poll();
1320 #endif /* SUSPEND_USES_PMU */
1321 }
1322
1323 /* Interrupt data could be the result data from an ADB cmd */
1324 static void
1325 pmu_handle_data(unsigned char *data, int len)
1326 {
1327         unsigned char ints, pirq;
1328         int i = 0;
1329
1330         asleep = 0;
1331         if (drop_interrupts || len < 1) {
1332                 adb_int_pending = 0;
1333                 pmu_irq_stats[8]++;
1334                 return;
1335         }
1336
1337         /* Get PMU interrupt mask */
1338         ints = data[0];
1339
1340         /* Record zero interrupts for stats */
1341         if (ints == 0)
1342                 pmu_irq_stats[9]++;
1343
1344         /* Hack to deal with ADB autopoll flag */
1345         if (ints & PMU_INT_ADB)
1346                 ints &= ~(PMU_INT_ADB_AUTO | PMU_INT_AUTO_SRQ_POLL);
1347
1348 next:
1349
1350         if (ints == 0) {
1351                 if (i > pmu_irq_stats[10])
1352                         pmu_irq_stats[10] = i;
1353                 return;
1354         }
1355
1356         for (pirq = 0; pirq < 8; pirq++)
1357                 if (ints & (1 << pirq))
1358                         break;
1359         pmu_irq_stats[pirq]++;
1360         i++;
1361         ints &= ~(1 << pirq);
1362
1363         /* Note: for some reason, we get an interrupt with len=1,
1364          * data[0]==0 after each normal ADB interrupt, at least
1365          * on the Pismo. Still investigating...  --BenH
1366          */
1367         if ((1 << pirq) & PMU_INT_ADB) {
1368                 if ((data[0] & PMU_INT_ADB_AUTO) == 0) {
1369                         struct adb_request *req = req_awaiting_reply;
1370                         if (req == 0) {
1371                                 printk(KERN_ERR "PMU: extra ADB reply\n");
1372                                 return;
1373                         }
1374                         req_awaiting_reply = NULL;
1375                         if (len <= 2)
1376                                 req->reply_len = 0;
1377                         else {
1378                                 memcpy(req->reply, data + 1, len - 1);
1379                                 req->reply_len = len - 1;
1380                         }
1381                         pmu_done(req);
1382                 } else {
1383                         if (len == 4 && data[1] == 0x2c) {
1384                                 extern int xmon_wants_key, xmon_adb_keycode;
1385                                 if (xmon_wants_key) {
1386                                         xmon_adb_keycode = data[2];
1387                                         return;
1388                                 }
1389                         }
1390 #ifdef CONFIG_ADB
1391                         /*
1392                          * XXX On the [23]400 the PMU gives us an up
1393                          * event for keycodes 0x74 or 0x75 when the PC
1394                          * card eject buttons are released, so we
1395                          * ignore those events.
1396                          */
1397                         if (!(pmu_kind == PMU_OHARE_BASED && len == 4
1398                               && data[1] == 0x2c && data[3] == 0xff
1399                               && (data[2] & ~1) == 0xf4))
1400                                 adb_input(data+1, len-1, 1);
1401 #endif /* CONFIG_ADB */         
1402                 }
1403         }
1404         /* Sound/brightness button pressed */
1405         else if ((1 << pirq) & PMU_INT_SNDBRT) {
1406 #ifdef CONFIG_PMAC_BACKLIGHT
1407                 if (len == 3)
1408                         pmac_backlight_set_legacy_brightness_pmu(data[1] >> 4);
1409 #endif
1410         }
1411         /* Tick interrupt */
1412         else if ((1 << pirq) & PMU_INT_TICK) {
1413                 /* Environement or tick interrupt, query batteries */
1414                 if (pmu_battery_count) {
1415                         if ((--query_batt_timer) == 0) {
1416                                 query_battery_state();
1417                                 query_batt_timer = BATTERY_POLLING_COUNT;
1418                         }
1419                 }
1420         }
1421         else if ((1 << pirq) & PMU_INT_ENVIRONMENT) {
1422                 if (pmu_battery_count)
1423                         query_battery_state();
1424                 pmu_pass_intr(data, len);
1425                 /* len == 6 is probably a bad check. But how do I
1426                  * know what PMU versions send what events here? */
1427                 if (len == 6) {
1428                         via_pmu_event(PMU_EVT_POWER, !!(data[1]&8));
1429                         via_pmu_event(PMU_EVT_LID, data[1]&1);
1430                 }
1431         } else {
1432                pmu_pass_intr(data, len);
1433         }
1434         goto next;
1435 }
1436
1437 static struct adb_request*
1438 pmu_sr_intr(void)
1439 {
1440         struct adb_request *req;
1441         int bite = 0;
1442
1443         if (via[B] & TREQ) {
1444                 printk(KERN_ERR "PMU: spurious SR intr (%x)\n", via[B]);
1445                 out_8(&via[IFR], SR_INT);
1446                 return NULL;
1447         }
1448         /* The ack may not yet be low when we get the interrupt */
1449         while ((in_8(&via[B]) & TACK) != 0)
1450                         ;
1451
1452         /* if reading grab the byte, and reset the interrupt */
1453         if (pmu_state == reading || pmu_state == reading_intr)
1454                 bite = in_8(&via[SR]);
1455
1456         /* reset TREQ and wait for TACK to go high */
1457         out_8(&via[B], in_8(&via[B]) | TREQ);
1458         wait_for_ack();
1459
1460         switch (pmu_state) {
1461         case sending:
1462                 req = current_req;
1463                 if (data_len < 0) {
1464                         data_len = req->nbytes - 1;
1465                         send_byte(data_len);
1466                         break;
1467                 }
1468                 if (data_index <= data_len) {
1469                         send_byte(req->data[data_index++]);
1470                         break;
1471                 }
1472                 req->sent = 1;
1473                 data_len = pmu_data_len[req->data[0]][1];
1474                 if (data_len == 0) {
1475                         pmu_state = idle;
1476                         current_req = req->next;
1477                         if (req->reply_expected)
1478                                 req_awaiting_reply = req;
1479                         else
1480                                 return req;
1481                 } else {
1482                         pmu_state = reading;
1483                         data_index = 0;
1484                         reply_ptr = req->reply + req->reply_len;
1485                         recv_byte();
1486                 }
1487                 break;
1488
1489         case intack:
1490                 data_index = 0;
1491                 data_len = -1;
1492                 pmu_state = reading_intr;
1493                 reply_ptr = interrupt_data[int_data_last];
1494                 recv_byte();
1495                 if (gpio_irq >= 0 && !gpio_irq_enabled) {
1496                         enable_irq(gpio_irq);
1497                         gpio_irq_enabled = 1;
1498                 }
1499                 break;
1500
1501         case reading:
1502         case reading_intr:
1503                 if (data_len == -1) {
1504                         data_len = bite;
1505                         if (bite > 32)
1506                                 printk(KERN_ERR "PMU: bad reply len %d\n", bite);
1507                 } else if (data_index < 32) {
1508                         reply_ptr[data_index++] = bite;
1509                 }
1510                 if (data_index < data_len) {
1511                         recv_byte();
1512                         break;
1513                 }
1514
1515                 if (pmu_state == reading_intr) {
1516                         pmu_state = idle;
1517                         int_data_state[int_data_last] = int_data_ready;
1518                         interrupt_data_len[int_data_last] = data_len;
1519                 } else {
1520                         req = current_req;
1521                         /* 
1522                          * For PMU sleep and freq change requests, we lock the
1523                          * PMU until it's explicitly unlocked. This avoids any
1524                          * spurrious event polling getting in
1525                          */
1526                         current_req = req->next;
1527                         req->reply_len += data_index;
1528                         if (req->data[0] == PMU_SLEEP || req->data[0] == PMU_CPU_SPEED)
1529                                 pmu_state = locked;
1530                         else
1531                                 pmu_state = idle;
1532                         return req;
1533                 }
1534                 break;
1535
1536         default:
1537                 printk(KERN_ERR "via_pmu_interrupt: unknown state %d?\n",
1538                        pmu_state);
1539         }
1540         return NULL;
1541 }
1542
1543 static irqreturn_t
1544 via_pmu_interrupt(int irq, void *arg)
1545 {
1546         unsigned long flags;
1547         int intr;
1548         int nloop = 0;
1549         int int_data = -1;
1550         struct adb_request *req = NULL;
1551         int handled = 0;
1552
1553         /* This is a bit brutal, we can probably do better */
1554         spin_lock_irqsave(&pmu_lock, flags);
1555         ++disable_poll;
1556         
1557         for (;;) {
1558                 intr = in_8(&via[IFR]) & (SR_INT | CB1_INT);
1559                 if (intr == 0)
1560                         break;
1561                 handled = 1;
1562                 if (++nloop > 1000) {
1563                         printk(KERN_DEBUG "PMU: stuck in intr loop, "
1564                                "intr=%x, ier=%x pmu_state=%d\n",
1565                                intr, in_8(&via[IER]), pmu_state);
1566                         break;
1567                 }
1568                 out_8(&via[IFR], intr);
1569                 if (intr & CB1_INT) {
1570                         adb_int_pending = 1;
1571                         pmu_irq_stats[0]++;
1572                 }
1573                 if (intr & SR_INT) {
1574                         req = pmu_sr_intr();
1575                         if (req)
1576                                 break;
1577                 }
1578         }
1579
1580 recheck:
1581         if (pmu_state == idle) {
1582                 if (adb_int_pending) {
1583                         if (int_data_state[0] == int_data_empty)
1584                                 int_data_last = 0;
1585                         else if (int_data_state[1] == int_data_empty)
1586                                 int_data_last = 1;
1587                         else
1588                                 goto no_free_slot;
1589                         pmu_state = intack;
1590                         int_data_state[int_data_last] = int_data_fill;
1591                         /* Sounds safer to make sure ACK is high before writing.
1592                          * This helped kill a problem with ADB and some iBooks
1593                          */
1594                         wait_for_ack();
1595                         send_byte(PMU_INT_ACK);
1596                         adb_int_pending = 0;
1597                 } else if (current_req)
1598                         pmu_start();
1599         }
1600 no_free_slot:                   
1601         /* Mark the oldest buffer for flushing */
1602         if (int_data_state[!int_data_last] == int_data_ready) {
1603                 int_data_state[!int_data_last] = int_data_flush;
1604                 int_data = !int_data_last;
1605         } else if (int_data_state[int_data_last] == int_data_ready) {
1606                 int_data_state[int_data_last] = int_data_flush;
1607                 int_data = int_data_last;
1608         }
1609         --disable_poll;
1610         spin_unlock_irqrestore(&pmu_lock, flags);
1611
1612         /* Deal with completed PMU requests outside of the lock */
1613         if (req) {
1614                 pmu_done(req);
1615                 req = NULL;
1616         }
1617                 
1618         /* Deal with interrupt datas outside of the lock */
1619         if (int_data >= 0) {
1620                 pmu_handle_data(interrupt_data[int_data], interrupt_data_len[int_data]);
1621                 spin_lock_irqsave(&pmu_lock, flags);
1622                 ++disable_poll;
1623                 int_data_state[int_data] = int_data_empty;
1624                 int_data = -1;
1625                 goto recheck;
1626         }
1627
1628         return IRQ_RETVAL(handled);
1629 }
1630
1631 void
1632 pmu_unlock(void)
1633 {
1634         unsigned long flags;
1635
1636         spin_lock_irqsave(&pmu_lock, flags);
1637         if (pmu_state == locked)
1638                 pmu_state = idle;
1639         adb_int_pending = 1;
1640         spin_unlock_irqrestore(&pmu_lock, flags);
1641 }
1642
1643
1644 static irqreturn_t
1645 gpio1_interrupt(int irq, void *arg)
1646 {
1647         unsigned long flags;
1648
1649         if ((in_8(gpio_reg + 0x9) & 0x02) == 0) {
1650                 spin_lock_irqsave(&pmu_lock, flags);
1651                 if (gpio_irq_enabled > 0) {
1652                         disable_irq_nosync(gpio_irq);
1653                         gpio_irq_enabled = 0;
1654                 }
1655                 pmu_irq_stats[1]++;
1656                 adb_int_pending = 1;
1657                 spin_unlock_irqrestore(&pmu_lock, flags);
1658                 via_pmu_interrupt(0, NULL);
1659                 return IRQ_HANDLED;
1660         }
1661         return IRQ_NONE;
1662 }
1663
1664 void
1665 pmu_enable_irled(int on)
1666 {
1667         struct adb_request req;
1668
1669         if (vias == NULL)
1670                 return ;
1671         if (pmu_kind == PMU_KEYLARGO_BASED)
1672                 return ;
1673
1674         pmu_request(&req, NULL, 2, PMU_POWER_CTRL, PMU_POW_IRLED |
1675             (on ? PMU_POW_ON : PMU_POW_OFF));
1676         pmu_wait_complete(&req);
1677 }
1678
1679 void
1680 pmu_restart(void)
1681 {
1682         struct adb_request req;
1683
1684         if (via == NULL)
1685                 return;
1686
1687         local_irq_disable();
1688
1689         drop_interrupts = 1;
1690         
1691         if (pmu_kind != PMU_KEYLARGO_BASED) {
1692                 pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, PMU_INT_ADB |
1693                                                 PMU_INT_TICK );
1694                 while(!req.complete)
1695                         pmu_poll();
1696         }
1697
1698         pmu_request(&req, NULL, 1, PMU_RESET);
1699         pmu_wait_complete(&req);
1700         for (;;)
1701                 ;
1702 }
1703
1704 void
1705 pmu_shutdown(void)
1706 {
1707         struct adb_request req;
1708
1709         if (via == NULL)
1710                 return;
1711
1712         local_irq_disable();
1713
1714         drop_interrupts = 1;
1715
1716         if (pmu_kind != PMU_KEYLARGO_BASED) {
1717                 pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, PMU_INT_ADB |
1718                                                 PMU_INT_TICK );
1719                 pmu_wait_complete(&req);
1720         } else {
1721                 /* Disable server mode on shutdown or we'll just
1722                  * wake up again
1723                  */
1724                 pmu_set_server_mode(0);
1725         }
1726
1727         pmu_request(&req, NULL, 5, PMU_SHUTDOWN,
1728                     'M', 'A', 'T', 'T');
1729         pmu_wait_complete(&req);
1730         for (;;)
1731                 ;
1732 }
1733
1734 int
1735 pmu_present(void)
1736 {
1737         return via != 0;
1738 }
1739
1740 #ifdef CONFIG_PM_SLEEP
1741
1742 static LIST_HEAD(sleep_notifiers);
1743
1744 int
1745 pmu_register_sleep_notifier(struct pmu_sleep_notifier *n)
1746 {
1747         struct list_head *list;
1748         struct pmu_sleep_notifier *notifier;
1749
1750         for (list = sleep_notifiers.next; list != &sleep_notifiers;
1751              list = list->next) {
1752                 notifier = list_entry(list, struct pmu_sleep_notifier, list);
1753                 if (n->priority > notifier->priority)
1754                         break;
1755         }
1756         __list_add(&n->list, list->prev, list);
1757         return 0;
1758 }
1759 EXPORT_SYMBOL(pmu_register_sleep_notifier);
1760
1761 int
1762 pmu_unregister_sleep_notifier(struct pmu_sleep_notifier* n)
1763 {
1764         if (n->list.next == 0)
1765                 return -ENOENT;
1766         list_del(&n->list);
1767         n->list.next = NULL;
1768         return 0;
1769 }
1770 EXPORT_SYMBOL(pmu_unregister_sleep_notifier);
1771 #endif /* CONFIG_PM_SLEEP */
1772
1773 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
1774
1775 /* Sleep is broadcast last-to-first */
1776 static void broadcast_sleep(int when)
1777 {
1778         struct list_head *list;
1779         struct pmu_sleep_notifier *notifier;
1780
1781         for (list = sleep_notifiers.prev; list != &sleep_notifiers;
1782              list = list->prev) {
1783                 notifier = list_entry(list, struct pmu_sleep_notifier, list);
1784                 notifier->notifier_call(notifier, when);
1785         }
1786 }
1787
1788 /* Wake is broadcast first-to-last */
1789 static void broadcast_wake(void)
1790 {
1791         struct list_head *list;
1792         struct pmu_sleep_notifier *notifier;
1793
1794         for (list = sleep_notifiers.next; list != &sleep_notifiers;
1795              list = list->next) {
1796                 notifier = list_entry(list, struct pmu_sleep_notifier, list);
1797                 notifier->notifier_call(notifier, PBOOK_WAKE);
1798         }
1799 }
1800
1801 /*
1802  * This struct is used to store config register values for
1803  * PCI devices which may get powered off when we sleep.
1804  */
1805 static struct pci_save {
1806 #ifndef HACKED_PCI_SAVE
1807         u16     command;
1808         u16     cache_lat;
1809         u16     intr;
1810         u32     rom_address;
1811 #else
1812         u32     config[16];
1813 #endif  
1814 } *pbook_pci_saves;
1815 static int pbook_npci_saves;
1816
1817 static void
1818 pbook_alloc_pci_save(void)
1819 {
1820         int npci;
1821         struct pci_dev *pd = NULL;
1822
1823         npci = 0;
1824         while ((pd = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pd)) != NULL) {
1825                 ++npci;
1826         }
1827         if (npci == 0)
1828                 return;
1829         pbook_pci_saves = (struct pci_save *)
1830                 kmalloc(npci * sizeof(struct pci_save), GFP_KERNEL);
1831         pbook_npci_saves = npci;
1832 }
1833
1834 static void
1835 pbook_free_pci_save(void)
1836 {
1837         if (pbook_pci_saves == NULL)
1838                 return;
1839         kfree(pbook_pci_saves);
1840         pbook_pci_saves = NULL;
1841         pbook_npci_saves = 0;
1842 }
1843
1844 static void
1845 pbook_pci_save(void)
1846 {
1847         struct pci_save *ps = pbook_pci_saves;
1848         struct pci_dev *pd = NULL;
1849         int npci = pbook_npci_saves;
1850         
1851         if (ps == NULL)
1852                 return;
1853
1854         while ((pd = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pd)) != NULL) {
1855                 if (npci-- == 0) {
1856                         pci_dev_put(pd);
1857                         return;
1858                 }
1859 #ifndef HACKED_PCI_SAVE
1860                 pci_read_config_word(pd, PCI_COMMAND, &ps->command);
1861                 pci_read_config_word(pd, PCI_CACHE_LINE_SIZE, &ps->cache_lat);
1862                 pci_read_config_word(pd, PCI_INTERRUPT_LINE, &ps->intr);
1863                 pci_read_config_dword(pd, PCI_ROM_ADDRESS, &ps->rom_address);
1864 #else
1865                 int i;
1866                 for (i=1;i<16;i++)
1867                         pci_read_config_dword(pd, i<<4, &ps->config[i]);
1868 #endif
1869                 ++ps;
1870         }
1871 }
1872
1873 /* For this to work, we must take care of a few things: If gmac was enabled
1874  * during boot, it will be in the pci dev list. If it's disabled at this point
1875  * (and it will probably be), then you can't access it's config space.
1876  */
1877 static void
1878 pbook_pci_restore(void)
1879 {
1880         u16 cmd;
1881         struct pci_save *ps = pbook_pci_saves - 1;
1882         struct pci_dev *pd = NULL;
1883         int npci = pbook_npci_saves;
1884         int j;
1885
1886         while ((pd = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pd)) != NULL) {
1887 #ifdef HACKED_PCI_SAVE
1888                 int i;
1889                 if (npci-- == 0) {
1890                         pci_dev_put(pd);
1891                         return;
1892                 }
1893                 ps++;
1894                 for (i=2;i<16;i++)
1895                         pci_write_config_dword(pd, i<<4, ps->config[i]);
1896                 pci_write_config_dword(pd, 4, ps->config[1]);
1897 #else
1898                 if (npci-- == 0)
1899                         return;
1900                 ps++;
1901                 if (ps->command == 0)
1902                         continue;
1903                 pci_read_config_word(pd, PCI_COMMAND, &cmd);
1904                 if ((ps->command & ~cmd) == 0)
1905                         continue;
1906                 switch (pd->hdr_type) {
1907                 case PCI_HEADER_TYPE_NORMAL:
1908                         for (j = 0; j < 6; ++j)
1909                                 pci_write_config_dword(pd,
1910                                         PCI_BASE_ADDRESS_0 + j*4,
1911                                         pd->resource[j].start);
1912                         pci_write_config_dword(pd, PCI_ROM_ADDRESS,
1913                                 ps->rom_address);
1914                         pci_write_config_word(pd, PCI_CACHE_LINE_SIZE,
1915                                 ps->cache_lat);
1916                         pci_write_config_word(pd, PCI_INTERRUPT_LINE,
1917                                 ps->intr);
1918                         pci_write_config_word(pd, PCI_COMMAND, ps->command);
1919                         break;
1920                 }
1921 #endif  
1922         }
1923 }
1924
1925 #ifdef DEBUG_SLEEP
1926 /* N.B. This doesn't work on the 3400 */
1927 void 
1928 pmu_blink(int n)
1929 {
1930         struct adb_request req;
1931
1932         memset(&req, 0, sizeof(req));
1933
1934         for (; n > 0; --n) {
1935                 req.nbytes = 4;
1936                 req.done = NULL;
1937                 req.data[0] = 0xee;
1938                 req.data[1] = 4;
1939                 req.data[2] = 0;
1940                 req.data[3] = 1;
1941                 req.reply[0] = ADB_RET_OK;
1942                 req.reply_len = 1;
1943                 req.reply_expected = 0;
1944                 pmu_polled_request(&req);
1945                 mdelay(50);
1946                 req.nbytes = 4;
1947                 req.done = NULL;
1948                 req.data[0] = 0xee;
1949                 req.data[1] = 4;
1950                 req.data[2] = 0;
1951                 req.data[3] = 0;
1952                 req.reply[0] = ADB_RET_OK;
1953                 req.reply_len = 1;
1954                 req.reply_expected = 0;
1955                 pmu_polled_request(&req);
1956                 mdelay(50);
1957         }
1958         mdelay(50);
1959 }
1960 #endif
1961
1962 /*
1963  * Put the powerbook to sleep.
1964  */
1965  
1966 static u32 save_via[8];
1967
1968 static void
1969 save_via_state(void)
1970 {
1971         save_via[0] = in_8(&via[ANH]);
1972         save_via[1] = in_8(&via[DIRA]);
1973         save_via[2] = in_8(&via[B]);
1974         save_via[3] = in_8(&via[DIRB]);
1975         save_via[4] = in_8(&via[PCR]);
1976         save_via[5] = in_8(&via[ACR]);
1977         save_via[6] = in_8(&via[T1CL]);
1978         save_via[7] = in_8(&via[T1CH]);
1979 }
1980 static void
1981 restore_via_state(void)
1982 {
1983         out_8(&via[ANH], save_via[0]);
1984         out_8(&via[DIRA], save_via[1]);
1985         out_8(&via[B], save_via[2]);
1986         out_8(&via[DIRB], save_via[3]);
1987         out_8(&via[PCR], save_via[4]);
1988         out_8(&via[ACR], save_via[5]);
1989         out_8(&via[T1CL], save_via[6]);
1990         out_8(&via[T1CH], save_via[7]);
1991         out_8(&via[IER], IER_CLR | 0x7f);       /* disable all intrs */
1992         out_8(&via[IFR], 0x7f);                         /* clear IFR */
1993         out_8(&via[IER], IER_SET | SR_INT | CB1_INT);
1994 }
1995
1996 extern void pmu_backlight_set_sleep(int sleep);
1997
1998 static int
1999 pmac_suspend_devices(void)
2000 {
2001         int ret;
2002
2003         pm_prepare_console();
2004         
2005         /* Notify old-style device drivers */
2006         broadcast_sleep(PBOOK_SLEEP_REQUEST);
2007
2008         /* Sync the disks. */
2009         /* XXX It would be nice to have some way to ensure that
2010          * nobody is dirtying any new buffers while we wait. That
2011          * could be achieved using the refrigerator for processes
2012          * that swsusp uses
2013          */
2014         sys_sync();
2015
2016         broadcast_sleep(PBOOK_SLEEP_NOW);
2017
2018         /* Send suspend call to devices, hold the device core's dpm_sem */
2019         ret = device_suspend(PMSG_SUSPEND);
2020         if (ret) {
2021                 broadcast_wake();
2022                 printk(KERN_ERR "Driver sleep failed\n");
2023                 return -EBUSY;
2024         }
2025
2026 #ifdef CONFIG_PMAC_BACKLIGHT
2027         /* Tell backlight code not to muck around with the chip anymore */
2028         pmu_backlight_set_sleep(1);
2029 #endif
2030
2031         /* Call platform functions marked "on sleep" */
2032         pmac_pfunc_i2c_suspend();
2033         pmac_pfunc_base_suspend();
2034
2035         /* Stop preemption */
2036         preempt_disable();
2037
2038         /* Make sure the decrementer won't interrupt us */
2039         asm volatile("mtdec %0" : : "r" (0x7fffffff));
2040         /* Make sure any pending DEC interrupt occurring while we did
2041          * the above didn't re-enable the DEC */
2042         mb();
2043         asm volatile("mtdec %0" : : "r" (0x7fffffff));
2044
2045         /* We can now disable MSR_EE. This code of course works properly only
2046          * on UP machines... For SMP, if we ever implement sleep, we'll have to
2047          * stop the "other" CPUs way before we do all that stuff.
2048          */
2049         local_irq_disable();
2050
2051         /* Broadcast power down irq
2052          * This isn't that useful in most cases (only directly wired devices can
2053          * use this but still... This will take care of sysdev's as well, so
2054          * we exit from here with local irqs disabled and PIC off.
2055          */
2056         ret = device_power_down(PMSG_SUSPEND);
2057         if (ret) {
2058                 wakeup_decrementer();
2059                 local_irq_enable();
2060                 preempt_enable();
2061                 device_resume();
2062                 broadcast_wake();
2063                 printk(KERN_ERR "Driver powerdown failed\n");
2064                 return -EBUSY;
2065         }
2066
2067         /* Wait for completion of async requests */
2068         while (!batt_req.complete)
2069                 pmu_poll();
2070
2071         /* Giveup the lazy FPU & vec so we don't have to back them
2072          * up from the low level code
2073          */
2074         enable_kernel_fp();
2075
2076 #ifdef CONFIG_ALTIVEC
2077         if (cpu_has_feature(CPU_FTR_ALTIVEC))
2078                 enable_kernel_altivec();
2079 #endif /* CONFIG_ALTIVEC */
2080
2081         return 0;
2082 }
2083
2084 static int
2085 pmac_wakeup_devices(void)
2086 {
2087         mdelay(100);
2088
2089 #ifdef CONFIG_PMAC_BACKLIGHT
2090         /* Tell backlight code it can use the chip again */
2091         pmu_backlight_set_sleep(0);
2092 #endif
2093
2094         /* Power back up system devices (including the PIC) */
2095         device_power_up();
2096
2097         /* Force a poll of ADB interrupts */
2098         adb_int_pending = 1;
2099         via_pmu_interrupt(0, NULL);
2100
2101         /* Restart jiffies & scheduling */
2102         wakeup_decrementer();
2103
2104         /* Re-enable local CPU interrupts */
2105         local_irq_enable();
2106         mdelay(10);
2107         preempt_enable();
2108
2109         /* Call platform functions marked "on wake" */
2110         pmac_pfunc_base_resume();
2111         pmac_pfunc_i2c_resume();
2112
2113         /* Resume devices */
2114         device_resume();
2115
2116         /* Notify old style drivers */
2117         broadcast_wake();
2118
2119         pm_restore_console();
2120
2121         return 0;
2122 }
2123
2124 #define GRACKLE_PM      (1<<7)
2125 #define GRACKLE_DOZE    (1<<5)
2126 #define GRACKLE_NAP     (1<<4)
2127 #define GRACKLE_SLEEP   (1<<3)
2128
2129 static int powerbook_sleep_grackle(void)
2130 {
2131         unsigned long save_l2cr;
2132         unsigned short pmcr1;
2133         struct adb_request req;
2134         int ret;
2135         struct pci_dev *grackle;
2136
2137         grackle = pci_get_bus_and_slot(0, 0);
2138         if (!grackle)
2139                 return -ENODEV;
2140
2141         ret = pmac_suspend_devices();
2142         if (ret) {
2143                 printk(KERN_ERR "Sleep rejected by devices\n");
2144                 return ret;
2145         }
2146         
2147         /* Turn off various things. Darwin does some retry tests here... */
2148         pmu_request(&req, NULL, 2, PMU_POWER_CTRL0, PMU_POW0_OFF|PMU_POW0_HARD_DRIVE);
2149         pmu_wait_complete(&req);
2150         pmu_request(&req, NULL, 2, PMU_POWER_CTRL,
2151                 PMU_POW_OFF|PMU_POW_BACKLIGHT|PMU_POW_IRLED|PMU_POW_MEDIABAY);
2152         pmu_wait_complete(&req);
2153
2154         /* For 750, save backside cache setting and disable it */
2155         save_l2cr = _get_L2CR();        /* (returns -1 if not available) */
2156
2157         if (!__fake_sleep) {
2158                 /* Ask the PMU to put us to sleep */
2159                 pmu_request(&req, NULL, 5, PMU_SLEEP, 'M', 'A', 'T', 'T');
2160                 pmu_wait_complete(&req);
2161         }
2162
2163         /* The VIA is supposed not to be restored correctly*/
2164         save_via_state();
2165         /* We shut down some HW */
2166         pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,1);
2167
2168         pci_read_config_word(grackle, 0x70, &pmcr1);
2169         /* Apparently, MacOS uses NAP mode for Grackle ??? */
2170         pmcr1 &= ~(GRACKLE_DOZE|GRACKLE_SLEEP); 
2171         pmcr1 |= GRACKLE_PM|GRACKLE_NAP;
2172         pci_write_config_word(grackle, 0x70, pmcr1);
2173
2174         /* Call low-level ASM sleep handler */
2175         if (__fake_sleep)
2176                 mdelay(5000);
2177         else
2178                 low_sleep_handler();
2179
2180         /* We're awake again, stop grackle PM */
2181         pci_read_config_word(grackle, 0x70, &pmcr1);
2182         pmcr1 &= ~(GRACKLE_PM|GRACKLE_DOZE|GRACKLE_SLEEP|GRACKLE_NAP); 
2183         pci_write_config_word(grackle, 0x70, pmcr1);
2184
2185         pci_dev_put(grackle);
2186
2187         /* Make sure the PMU is idle */
2188         pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,0);
2189         restore_via_state();
2190         
2191         /* Restore L2 cache */
2192         if (save_l2cr != 0xffffffff && (save_l2cr & L2CR_L2E) != 0)
2193                 _set_L2CR(save_l2cr);
2194         
2195         /* Restore userland MMU context */
2196         set_context(current->active_mm->context.id, current->active_mm->pgd);
2197
2198         /* Power things up */
2199         pmu_unlock();
2200         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, pmu_intr_mask);
2201         pmu_wait_complete(&req);
2202         pmu_request(&req, NULL, 2, PMU_POWER_CTRL0,
2203                         PMU_POW0_ON|PMU_POW0_HARD_DRIVE);
2204         pmu_wait_complete(&req);
2205         pmu_request(&req, NULL, 2, PMU_POWER_CTRL,
2206                         PMU_POW_ON|PMU_POW_BACKLIGHT|PMU_POW_CHARGER|PMU_POW_IRLED|PMU_POW_MEDIABAY);
2207         pmu_wait_complete(&req);
2208
2209         pmac_wakeup_devices();
2210
2211         return 0;
2212 }
2213
2214 static int
2215 powerbook_sleep_Core99(void)
2216 {
2217         unsigned long save_l2cr;
2218         unsigned long save_l3cr;
2219         struct adb_request req;
2220         int ret;
2221         
2222         if (pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,-1) < 0) {
2223                 printk(KERN_ERR "Sleep mode not supported on this machine\n");
2224                 return -ENOSYS;
2225         }
2226
2227         if (num_online_cpus() > 1 || cpu_is_offline(0))
2228                 return -EAGAIN;
2229
2230         ret = pmac_suspend_devices();
2231         if (ret) {
2232                 printk(KERN_ERR "Sleep rejected by devices\n");
2233                 return ret;
2234         }
2235
2236         /* Stop environment and ADB interrupts */
2237         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, 0);
2238         pmu_wait_complete(&req);
2239
2240         /* Tell PMU what events will wake us up */
2241         pmu_request(&req, NULL, 4, PMU_POWER_EVENTS, PMU_PWR_CLR_WAKEUP_EVENTS,
2242                 0xff, 0xff);
2243         pmu_wait_complete(&req);
2244         pmu_request(&req, NULL, 4, PMU_POWER_EVENTS, PMU_PWR_SET_WAKEUP_EVENTS,
2245                 0, PMU_PWR_WAKEUP_KEY |
2246                 (option_lid_wakeup ? PMU_PWR_WAKEUP_LID_OPEN : 0));
2247         pmu_wait_complete(&req);
2248
2249         /* Save the state of the L2 and L3 caches */
2250         save_l3cr = _get_L3CR();        /* (returns -1 if not available) */
2251         save_l2cr = _get_L2CR();        /* (returns -1 if not available) */
2252
2253         if (!__fake_sleep) {
2254                 /* Ask the PMU to put us to sleep */
2255                 pmu_request(&req, NULL, 5, PMU_SLEEP, 'M', 'A', 'T', 'T');
2256                 pmu_wait_complete(&req);
2257         }
2258
2259         /* The VIA is supposed not to be restored correctly*/
2260         save_via_state();
2261
2262         /* Shut down various ASICs. There's a chance that we can no longer
2263          * talk to the PMU after this, so I moved it to _after_ sending the
2264          * sleep command to it. Still need to be checked.
2265          */
2266         pmac_call_feature(PMAC_FTR_SLEEP_STATE, NULL, 0, 1);
2267
2268         /* Call low-level ASM sleep handler */
2269         if (__fake_sleep)
2270                 mdelay(5000);
2271         else
2272                 low_sleep_handler();
2273
2274         /* Restore Apple core ASICs state */
2275         pmac_call_feature(PMAC_FTR_SLEEP_STATE, NULL, 0, 0);
2276
2277         /* Restore VIA */
2278         restore_via_state();
2279
2280         /* tweak LPJ before cpufreq is there */
2281         loops_per_jiffy *= 2;
2282
2283         /* Restore video */
2284         pmac_call_early_video_resume();
2285
2286         /* Restore L2 cache */
2287         if (save_l2cr != 0xffffffff && (save_l2cr & L2CR_L2E) != 0)
2288                 _set_L2CR(save_l2cr);
2289         /* Restore L3 cache */
2290         if (save_l3cr != 0xffffffff && (save_l3cr & L3CR_L3E) != 0)
2291                 _set_L3CR(save_l3cr);
2292         
2293         /* Restore userland MMU context */
2294         set_context(current->active_mm->context.id, current->active_mm->pgd);
2295
2296         /* Tell PMU we are ready */
2297         pmu_unlock();
2298         pmu_request(&req, NULL, 2, PMU_SYSTEM_READY, 2);
2299         pmu_wait_complete(&req);
2300         pmu_request(&req, NULL, 2, PMU_SET_INTR_MASK, pmu_intr_mask);
2301         pmu_wait_complete(&req);
2302
2303         /* Restore LPJ, cpufreq will adjust the cpu frequency */
2304         loops_per_jiffy /= 2;
2305
2306         pmac_wakeup_devices();
2307
2308         return 0;
2309 }
2310
2311 #define PB3400_MEM_CTRL         0xf8000000
2312 #define PB3400_MEM_CTRL_SLEEP   0x70
2313
2314 static int
2315 powerbook_sleep_3400(void)
2316 {
2317         int ret, i, x;
2318         unsigned int hid0;
2319         unsigned long p;
2320         struct adb_request sleep_req;
2321         void __iomem *mem_ctrl;
2322         unsigned int __iomem *mem_ctrl_sleep;
2323
2324         /* first map in the memory controller registers */
2325         mem_ctrl = ioremap(PB3400_MEM_CTRL, 0x100);
2326         if (mem_ctrl == NULL) {
2327                 printk("powerbook_sleep_3400: ioremap failed\n");
2328                 return -ENOMEM;
2329         }
2330         mem_ctrl_sleep = mem_ctrl + PB3400_MEM_CTRL_SLEEP;
2331
2332         /* Allocate room for PCI save */
2333         pbook_alloc_pci_save();
2334
2335         ret = pmac_suspend_devices();
2336         if (ret) {
2337                 pbook_free_pci_save();
2338                 printk(KERN_ERR "Sleep rejected by devices\n");
2339                 return ret;
2340         }
2341
2342         /* Save the state of PCI config space for some slots */
2343         pbook_pci_save();
2344
2345         /* Set the memory controller to keep the memory refreshed
2346            while we're asleep */
2347         for (i = 0x403f; i >= 0x4000; --i) {
2348                 out_be32(mem_ctrl_sleep, i);
2349                 do {
2350                         x = (in_be32(mem_ctrl_sleep) >> 16) & 0x3ff;
2351                 } while (x == 0);
2352                 if (x >= 0x100)
2353                         break;
2354         }
2355
2356         /* Ask the PMU to put us to sleep */
2357         pmu_request(&sleep_req, NULL, 5, PMU_SLEEP, 'M', 'A', 'T', 'T');
2358         while (!sleep_req.complete)
2359                 mb();
2360
2361         pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,1);
2362
2363         /* displacement-flush the L2 cache - necessary? */
2364         for (p = KERNELBASE; p < KERNELBASE + 0x100000; p += 0x1000)
2365                 i = *(volatile int *)p;
2366         asleep = 1;
2367
2368         /* Put the CPU into sleep mode */
2369         hid0 = mfspr(SPRN_HID0);
2370         hid0 = (hid0 & ~(HID0_NAP | HID0_DOZE)) | HID0_SLEEP;
2371         mtspr(SPRN_HID0, hid0);
2372         mtmsr(mfmsr() | MSR_POW | MSR_EE);
2373         udelay(10);
2374
2375         /* OK, we're awake again, start restoring things */
2376         out_be32(mem_ctrl_sleep, 0x3f);
2377         pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,0);
2378         pbook_pci_restore();
2379         pmu_unlock();
2380
2381         /* wait for the PMU interrupt sequence to complete */
2382         while (asleep)
2383                 mb();
2384
2385         pmac_wakeup_devices();
2386         pbook_free_pci_save();
2387         iounmap(mem_ctrl);
2388
2389         return 0;
2390 }
2391
2392 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
2393
2394 /*
2395  * Support for /dev/pmu device
2396  */
2397 #define RB_SIZE         0x10
2398 struct pmu_private {
2399         struct list_head list;
2400         int     rb_get;
2401         int     rb_put;
2402         struct rb_entry {
2403                 unsigned short len;
2404                 unsigned char data[16];
2405         }       rb_buf[RB_SIZE];
2406         wait_queue_head_t wait;
2407         spinlock_t lock;
2408 #if defined(CONFIG_INPUT_ADBHID) && defined(CONFIG_PMAC_BACKLIGHT)
2409         int     backlight_locker;
2410 #endif
2411 };
2412
2413 static LIST_HEAD(all_pmu_pvt);
2414 static DEFINE_SPINLOCK(all_pvt_lock);
2415
2416 static void
2417 pmu_pass_intr(unsigned char *data, int len)
2418 {
2419         struct pmu_private *pp;
2420         struct list_head *list;
2421         int i;
2422         unsigned long flags;
2423
2424         if (len > sizeof(pp->rb_buf[0].data))
2425                 len = sizeof(pp->rb_buf[0].data);
2426         spin_lock_irqsave(&all_pvt_lock, flags);
2427         for (list = &all_pmu_pvt; (list = list->next) != &all_pmu_pvt; ) {
2428                 pp = list_entry(list, struct pmu_private, list);
2429                 spin_lock(&pp->lock);
2430                 i = pp->rb_put + 1;
2431                 if (i >= RB_SIZE)
2432                         i = 0;
2433                 if (i != pp->rb_get) {
2434                         struct rb_entry *rp = &pp->rb_buf[pp->rb_put];
2435                         rp->len = len;
2436                         memcpy(rp->data, data, len);
2437                         pp->rb_put = i;
2438                         wake_up_interruptible(&pp->wait);
2439                 }
2440                 spin_unlock(&pp->lock);
2441         }
2442         spin_unlock_irqrestore(&all_pvt_lock, flags);
2443 }
2444
2445 static int
2446 pmu_open(struct inode *inode, struct file *file)
2447 {
2448         struct pmu_private *pp;
2449         unsigned long flags;
2450
2451         pp = kmalloc(sizeof(struct pmu_private), GFP_KERNEL);
2452         if (pp == 0)
2453                 return -ENOMEM;
2454         pp->rb_get = pp->rb_put = 0;
2455         spin_lock_init(&pp->lock);
2456         init_waitqueue_head(&pp->wait);
2457         spin_lock_irqsave(&all_pvt_lock, flags);
2458 #if defined(CONFIG_INPUT_ADBHID) && defined(CONFIG_PMAC_BACKLIGHT)
2459         pp->backlight_locker = 0;
2460 #endif
2461         list_add(&pp->list, &all_pmu_pvt);
2462         spin_unlock_irqrestore(&all_pvt_lock, flags);
2463         file->private_data = pp;
2464         return 0;
2465 }
2466
2467 static ssize_t 
2468 pmu_read(struct file *file, char __user *buf,
2469                         size_t count, loff_t *ppos)
2470 {
2471         struct pmu_private *pp = file->private_data;
2472         DECLARE_WAITQUEUE(wait, current);
2473         unsigned long flags;
2474         int ret = 0;
2475
2476         if (count < 1 || pp == 0)
2477                 return -EINVAL;
2478         if (!access_ok(VERIFY_WRITE, buf, count))
2479                 return -EFAULT;
2480
2481         spin_lock_irqsave(&pp->lock, flags);
2482         add_wait_queue(&pp->wait, &wait);
2483         current->state = TASK_INTERRUPTIBLE;
2484
2485         for (;;) {
2486                 ret = -EAGAIN;
2487                 if (pp->rb_get != pp->rb_put) {
2488                         int i = pp->rb_get;
2489                         struct rb_entry *rp = &pp->rb_buf[i];
2490                         ret = rp->len;
2491                         spin_unlock_irqrestore(&pp->lock, flags);
2492                         if (ret > count)
2493                                 ret = count;
2494                         if (ret > 0 && copy_to_user(buf, rp->data, ret))
2495                                 ret = -EFAULT;
2496                         if (++i >= RB_SIZE)
2497                                 i = 0;
2498                         spin_lock_irqsave(&pp->lock, flags);
2499                         pp->rb_get = i;
2500                 }
2501                 if (ret >= 0)
2502                         break;
2503                 if (file->f_flags & O_NONBLOCK)
2504                         break;
2505                 ret = -ERESTARTSYS;
2506                 if (signal_pending(current))
2507                         break;
2508                 spin_unlock_irqrestore(&pp->lock, flags);
2509                 schedule();
2510                 spin_lock_irqsave(&pp->lock, flags);
2511         }
2512         current->state = TASK_RUNNING;
2513         remove_wait_queue(&pp->wait, &wait);
2514         spin_unlock_irqrestore(&pp->lock, flags);
2515         
2516         return ret;
2517 }
2518
2519 static ssize_t
2520 pmu_write(struct file *file, const char __user *buf,
2521                          size_t count, loff_t *ppos)
2522 {
2523         return 0;
2524 }
2525
2526 static unsigned int
2527 pmu_fpoll(struct file *filp, poll_table *wait)
2528 {
2529         struct pmu_private *pp = filp->private_data;
2530         unsigned int mask = 0;
2531         unsigned long flags;
2532         
2533         if (pp == 0)
2534                 return 0;
2535         poll_wait(filp, &pp->wait, wait);
2536         spin_lock_irqsave(&pp->lock, flags);
2537         if (pp->rb_get != pp->rb_put)
2538                 mask |= POLLIN;
2539         spin_unlock_irqrestore(&pp->lock, flags);
2540         return mask;
2541 }
2542
2543 static int
2544 pmu_release(struct inode *inode, struct file *file)
2545 {
2546         struct pmu_private *pp = file->private_data;
2547         unsigned long flags;
2548
2549         if (pp != 0) {
2550                 file->private_data = NULL;
2551                 spin_lock_irqsave(&all_pvt_lock, flags);
2552                 list_del(&pp->list);
2553                 spin_unlock_irqrestore(&all_pvt_lock, flags);
2554
2555 #if defined(CONFIG_INPUT_ADBHID) && defined(CONFIG_PMAC_BACKLIGHT)
2556                 if (pp->backlight_locker)
2557                         pmac_backlight_enable();
2558 #endif
2559
2560                 kfree(pp);
2561         }
2562         return 0;
2563 }
2564
2565 static int
2566 pmu_ioctl(struct inode * inode, struct file *filp,
2567                      u_int cmd, u_long arg)
2568 {
2569         __u32 __user *argp = (__u32 __user *)arg;
2570         int error = -EINVAL;
2571
2572         switch (cmd) {
2573 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
2574         case PMU_IOC_SLEEP:
2575                 if (!capable(CAP_SYS_ADMIN))
2576                         return -EACCES;
2577                 if (sleep_in_progress)
2578                         return -EBUSY;
2579                 sleep_in_progress = 1;
2580                 switch (pmu_kind) {
2581                 case PMU_OHARE_BASED:
2582                         error = powerbook_sleep_3400();
2583                         break;
2584                 case PMU_HEATHROW_BASED:
2585                 case PMU_PADDINGTON_BASED:
2586                         error = powerbook_sleep_grackle();
2587                         break;
2588                 case PMU_KEYLARGO_BASED:
2589                         error = powerbook_sleep_Core99();
2590                         break;
2591                 default:
2592                         error = -ENOSYS;
2593                 }
2594                 sleep_in_progress = 0;
2595                 break;
2596         case PMU_IOC_CAN_SLEEP:
2597                 if (pmac_call_feature(PMAC_FTR_SLEEP_STATE,NULL,0,-1) < 0)
2598                         return put_user(0, argp);
2599                 else
2600                         return put_user(1, argp);
2601 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
2602
2603 #ifdef CONFIG_PMAC_BACKLIGHT_LEGACY
2604         /* Compatibility ioctl's for backlight */
2605         case PMU_IOC_GET_BACKLIGHT:
2606         {
2607                 int brightness;
2608
2609                 if (sleep_in_progress)
2610                         return -EBUSY;
2611
2612                 brightness = pmac_backlight_get_legacy_brightness();
2613                 if (brightness < 0)
2614                         return brightness;
2615                 else
2616                         return put_user(brightness, argp);
2617
2618         }
2619         case PMU_IOC_SET_BACKLIGHT:
2620         {
2621                 int brightness;
2622
2623                 if (sleep_in_progress)
2624                         return -EBUSY;
2625
2626                 error = get_user(brightness, argp);
2627                 if (error)
2628                         return error;
2629
2630                 return pmac_backlight_set_legacy_brightness(brightness);
2631         }
2632 #ifdef CONFIG_INPUT_ADBHID
2633         case PMU_IOC_GRAB_BACKLIGHT: {
2634                 struct pmu_private *pp = filp->private_data;
2635
2636                 if (pp->backlight_locker)
2637                         return 0;
2638
2639                 pp->backlight_locker = 1;
2640                 pmac_backlight_disable();
2641
2642                 return 0;
2643         }
2644 #endif /* CONFIG_INPUT_ADBHID */
2645 #endif /* CONFIG_PMAC_BACKLIGHT_LEGACY */
2646
2647         case PMU_IOC_GET_MODEL:
2648                 return put_user(pmu_kind, argp);
2649         case PMU_IOC_HAS_ADB:
2650                 return put_user(pmu_has_adb, argp);
2651         }
2652         return error;
2653 }
2654
2655 static const struct file_operations pmu_device_fops = {
2656         .read           = pmu_read,
2657         .write          = pmu_write,
2658         .poll           = pmu_fpoll,
2659         .ioctl          = pmu_ioctl,
2660         .open           = pmu_open,
2661         .release        = pmu_release,
2662 };
2663
2664 static struct miscdevice pmu_device = {
2665         PMU_MINOR, "pmu", &pmu_device_fops
2666 };
2667
2668 static int pmu_device_init(void)
2669 {
2670         if (!via)
2671                 return 0;
2672         if (misc_register(&pmu_device) < 0)
2673                 printk(KERN_ERR "via-pmu: cannot register misc device.\n");
2674         return 0;
2675 }
2676 device_initcall(pmu_device_init);
2677
2678
2679 #ifdef DEBUG_SLEEP
2680 static inline void 
2681 polled_handshake(volatile unsigned char __iomem *via)
2682 {
2683         via[B] &= ~TREQ; eieio();
2684         while ((via[B] & TACK) != 0)
2685                 ;
2686         via[B] |= TREQ; eieio();
2687         while ((via[B] & TACK) == 0)
2688                 ;
2689 }
2690
2691 static inline void 
2692 polled_send_byte(volatile unsigned char __iomem *via, int x)
2693 {
2694         via[ACR] |= SR_OUT | SR_EXT; eieio();
2695         via[SR] = x; eieio();
2696         polled_handshake(via);
2697 }
2698
2699 static inline int
2700 polled_recv_byte(volatile unsigned char __iomem *via)
2701 {
2702         int x;
2703
2704         via[ACR] = (via[ACR] & ~SR_OUT) | SR_EXT; eieio();
2705         x = via[SR]; eieio();
2706         polled_handshake(via);
2707         x = via[SR]; eieio();
2708         return x;
2709 }
2710
2711 int
2712 pmu_polled_request(struct adb_request *req)
2713 {
2714         unsigned long flags;
2715         int i, l, c;
2716         volatile unsigned char __iomem *v = via;
2717
2718         req->complete = 1;
2719         c = req->data[0];
2720         l = pmu_data_len[c][0];
2721         if (l >= 0 && req->nbytes != l + 1)
2722                 return -EINVAL;
2723
2724         local_irq_save(flags);
2725         while (pmu_state != idle)
2726                 pmu_poll();
2727
2728         while ((via[B] & TACK) == 0)
2729                 ;
2730         polled_send_byte(v, c);
2731         if (l < 0) {
2732                 l = req->nbytes - 1;
2733                 polled_send_byte(v, l);
2734         }
2735         for (i = 1; i <= l; ++i)
2736                 polled_send_byte(v, req->data[i]);
2737
2738         l = pmu_data_len[c][1];
2739         if (l < 0)
2740                 l = polled_recv_byte(v);
2741         for (i = 0; i < l; ++i)
2742                 req->reply[i + req->reply_len] = polled_recv_byte(v);
2743
2744         if (req->done)
2745                 (*req->done)(req);
2746
2747         local_irq_restore(flags);
2748         return 0;
2749 }
2750 #endif /* DEBUG_SLEEP */
2751
2752
2753 /* FIXME: This is a temporary set of callbacks to enable us
2754  * to do suspend-to-disk.
2755  */
2756
2757 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
2758
2759 int pmu_sys_suspended;
2760
2761 static int pmu_sys_suspend(struct sys_device *sysdev, pm_message_t state)
2762 {
2763         if (state.event != PM_EVENT_SUSPEND || pmu_sys_suspended)
2764                 return 0;
2765
2766         /* Suspend PMU event interrupts */
2767         pmu_suspend();
2768
2769         pmu_sys_suspended = 1;
2770         return 0;
2771 }
2772
2773 static int pmu_sys_resume(struct sys_device *sysdev)
2774 {
2775         struct adb_request req;
2776
2777         if (!pmu_sys_suspended)
2778                 return 0;
2779
2780         /* Tell PMU we are ready */
2781         pmu_request(&req, NULL, 2, PMU_SYSTEM_READY, 2);
2782         pmu_wait_complete(&req);
2783
2784         /* Resume PMU event interrupts */
2785         pmu_resume();
2786
2787         pmu_sys_suspended = 0;
2788
2789         return 0;
2790 }
2791
2792 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
2793
2794 static struct sysdev_class pmu_sysclass = {
2795         set_kset_name("pmu"),
2796 };
2797
2798 static struct sys_device device_pmu = {
2799         .cls            = &pmu_sysclass,
2800 };
2801
2802 static struct sysdev_driver driver_pmu = {
2803 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
2804         .suspend        = &pmu_sys_suspend,
2805         .resume         = &pmu_sys_resume,
2806 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
2807 };
2808
2809 static int __init init_pmu_sysfs(void)
2810 {
2811         int rc;
2812
2813         rc = sysdev_class_register(&pmu_sysclass);
2814         if (rc) {
2815                 printk(KERN_ERR "Failed registering PMU sys class\n");
2816                 return -ENODEV;
2817         }
2818         rc = sysdev_register(&device_pmu);
2819         if (rc) {
2820                 printk(KERN_ERR "Failed registering PMU sys device\n");
2821                 return -ENODEV;
2822         }
2823         rc = sysdev_driver_register(&pmu_sysclass, &driver_pmu);
2824         if (rc) {
2825                 printk(KERN_ERR "Failed registering PMU sys driver\n");
2826                 return -ENODEV;
2827         }
2828         return 0;
2829 }
2830
2831 subsys_initcall(init_pmu_sysfs);
2832
2833 EXPORT_SYMBOL(pmu_request);
2834 EXPORT_SYMBOL(pmu_queue_request);
2835 EXPORT_SYMBOL(pmu_poll);
2836 EXPORT_SYMBOL(pmu_poll_adb);
2837 EXPORT_SYMBOL(pmu_wait_complete);
2838 EXPORT_SYMBOL(pmu_suspend);
2839 EXPORT_SYMBOL(pmu_resume);
2840 EXPORT_SYMBOL(pmu_unlock);
2841 #if defined(CONFIG_PM_SLEEP) && defined(CONFIG_PPC32)
2842 EXPORT_SYMBOL(pmu_enable_irled);
2843 EXPORT_SYMBOL(pmu_battery_count);
2844 EXPORT_SYMBOL(pmu_batteries);
2845 EXPORT_SYMBOL(pmu_power_flags);
2846 #endif /* CONFIG_PM_SLEEP && CONFIG_PPC32 */
2847