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