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