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