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