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