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