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