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