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