Merge branch 'for-linus' of git://git.o-hand.com/linux-rpurdie-backlight
[linux-2.6] / drivers / platform / x86 / thinkpad_acpi.c
1 /*
2  *  thinkpad_acpi.c - ThinkPad ACPI Extras
3  *
4  *
5  *  Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net>
6  *  Copyright (C) 2006-2008 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  *  02110-1301, USA.
22  */
23
24 #define TPACPI_VERSION "0.21"
25 #define TPACPI_SYSFS_VERSION 0x020200
26
27 /*
28  *  Changelog:
29  *  2007-10-20          changelog trimmed down
30  *
31  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
32  *                      drivers/misc.
33  *
34  *  2006-11-22  0.13    new maintainer
35  *                      changelog now lives in git commit history, and will
36  *                      not be updated further in-file.
37  *
38  *  2005-03-17  0.11    support for 600e, 770x
39  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
40  *
41  *  2005-01-16  0.9     use MODULE_VERSION
42  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
43  *                      fix parameter passing on module loading
44  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
45  *                          thanks to Jim Radford <radford@blackbean.org>
46  *  2004-11-08  0.8     fix init error case, don't return from a macro
47  *                          thanks to Chris Wright <chrisw@osdl.org>
48  */
49
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/init.h>
53 #include <linux/types.h>
54 #include <linux/string.h>
55 #include <linux/list.h>
56 #include <linux/mutex.h>
57 #include <linux/kthread.h>
58 #include <linux/freezer.h>
59 #include <linux/delay.h>
60
61 #include <linux/nvram.h>
62 #include <linux/proc_fs.h>
63 #include <linux/sysfs.h>
64 #include <linux/backlight.h>
65 #include <linux/fb.h>
66 #include <linux/platform_device.h>
67 #include <linux/hwmon.h>
68 #include <linux/hwmon-sysfs.h>
69 #include <linux/input.h>
70 #include <linux/leds.h>
71 #include <linux/rfkill.h>
72 #include <asm/uaccess.h>
73
74 #include <linux/dmi.h>
75 #include <linux/jiffies.h>
76 #include <linux/workqueue.h>
77
78 #include <acpi/acpi_drivers.h>
79
80 #include <linux/pci_ids.h>
81
82
83 /* ThinkPad CMOS commands */
84 #define TP_CMOS_VOLUME_DOWN     0
85 #define TP_CMOS_VOLUME_UP       1
86 #define TP_CMOS_VOLUME_MUTE     2
87 #define TP_CMOS_BRIGHTNESS_UP   4
88 #define TP_CMOS_BRIGHTNESS_DOWN 5
89 #define TP_CMOS_THINKLIGHT_ON   12
90 #define TP_CMOS_THINKLIGHT_OFF  13
91
92 /* NVRAM Addresses */
93 enum tp_nvram_addr {
94         TP_NVRAM_ADDR_HK2               = 0x57,
95         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
96         TP_NVRAM_ADDR_VIDEO             = 0x59,
97         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
98         TP_NVRAM_ADDR_MIXER             = 0x60,
99 };
100
101 /* NVRAM bit masks */
102 enum {
103         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
104         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
105         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
106         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
107         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
108         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
109         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
110         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
111         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
112         TP_NVRAM_MASK_MUTE              = 0x40,
113         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
114         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
115         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
116 };
117
118 /* ACPI HIDs */
119 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
120
121 /* Input IDs */
122 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
123 #define TPACPI_HKEY_INPUT_VERSION       0x4101
124
125
126 /****************************************************************************
127  * Main driver
128  */
129
130 #define TPACPI_NAME "thinkpad"
131 #define TPACPI_DESC "ThinkPad ACPI Extras"
132 #define TPACPI_FILE TPACPI_NAME "_acpi"
133 #define TPACPI_URL "http://ibm-acpi.sf.net/"
134 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
135
136 #define TPACPI_PROC_DIR "ibm"
137 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
138 #define TPACPI_DRVR_NAME TPACPI_FILE
139 #define TPACPI_DRVR_SHORTNAME "tpacpi"
140 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
141
142 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
143 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
144
145 #define TPACPI_MAX_ACPI_ARGS 3
146
147 /* rfkill switches */
148 enum {
149         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
150         TPACPI_RFK_WWAN_SW_ID,
151 };
152
153 /* Debugging */
154 #define TPACPI_LOG TPACPI_FILE ": "
155 #define TPACPI_ERR         KERN_ERR    TPACPI_LOG
156 #define TPACPI_NOTICE KERN_NOTICE TPACPI_LOG
157 #define TPACPI_INFO   KERN_INFO   TPACPI_LOG
158 #define TPACPI_DEBUG  KERN_DEBUG  TPACPI_LOG
159
160 #define TPACPI_DBG_ALL          0xffff
161 #define TPACPI_DBG_INIT         0x0001
162 #define TPACPI_DBG_EXIT         0x0002
163 #define dbg_printk(a_dbg_level, format, arg...) \
164         do { if (dbg_level & a_dbg_level) \
165                 printk(TPACPI_DEBUG "%s: " format, __func__ , ## arg); \
166         } while (0)
167 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
168 #define vdbg_printk(a_dbg_level, format, arg...) \
169         dbg_printk(a_dbg_level, format, ## arg)
170 static const char *str_supported(int is_supported);
171 #else
172 #define vdbg_printk(a_dbg_level, format, arg...)
173 #endif
174
175 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off")
176 #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled")
177 #define strlencmp(a, b) (strncmp((a), (b), strlen(b)))
178
179
180 /****************************************************************************
181  * Driver-wide structs and misc. variables
182  */
183
184 struct ibm_struct;
185
186 struct tp_acpi_drv_struct {
187         const struct acpi_device_id *hid;
188         struct acpi_driver *driver;
189
190         void (*notify) (struct ibm_struct *, u32);
191         acpi_handle *handle;
192         u32 type;
193         struct acpi_device *device;
194 };
195
196 struct ibm_struct {
197         char *name;
198
199         int (*read) (char *);
200         int (*write) (char *);
201         void (*exit) (void);
202         void (*resume) (void);
203         void (*suspend) (pm_message_t state);
204
205         struct list_head all_drivers;
206
207         struct tp_acpi_drv_struct *acpi;
208
209         struct {
210                 u8 acpi_driver_registered:1;
211                 u8 acpi_notify_installed:1;
212                 u8 proc_created:1;
213                 u8 init_called:1;
214                 u8 experimental:1;
215         } flags;
216 };
217
218 struct ibm_init_struct {
219         char param[32];
220
221         int (*init) (struct ibm_init_struct *);
222         struct ibm_struct *data;
223 };
224
225 static struct {
226 #ifdef CONFIG_THINKPAD_ACPI_BAY
227         u32 bay_status:1;
228         u32 bay_eject:1;
229         u32 bay_status2:1;
230         u32 bay_eject2:1;
231 #endif
232         u32 bluetooth:1;
233         u32 hotkey:1;
234         u32 hotkey_mask:1;
235         u32 hotkey_wlsw:1;
236         u32 hotkey_tablet:1;
237         u32 light:1;
238         u32 light_status:1;
239         u32 bright_16levels:1;
240         u32 bright_acpimode:1;
241         u32 wan:1;
242         u32 fan_ctrl_status_undef:1;
243         u32 input_device_registered:1;
244         u32 platform_drv_registered:1;
245         u32 platform_drv_attrs_registered:1;
246         u32 sensors_pdrv_registered:1;
247         u32 sensors_pdrv_attrs_registered:1;
248         u32 sensors_pdev_attrs_registered:1;
249         u32 hotkey_poll_active:1;
250 } tp_features;
251
252 static struct {
253         u16 hotkey_mask_ff:1;
254         u16 bright_cmos_ec_unsync:1;
255 } tp_warned;
256
257 struct thinkpad_id_data {
258         unsigned int vendor;    /* ThinkPad vendor:
259                                  * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */
260
261         char *bios_version_str; /* Something like 1ZET51WW (1.03z) */
262         char *ec_version_str;   /* Something like 1ZHT51WW-1.04a */
263
264         u16 bios_model;         /* Big Endian, TP-1Y = 0x5931, 0 = unknown */
265         u16 ec_model;
266
267         char *model_str;        /* ThinkPad T43 */
268         char *nummodel_str;     /* 9384A9C for a 9384-A9C model */
269 };
270 static struct thinkpad_id_data thinkpad_id;
271
272 static enum {
273         TPACPI_LIFE_INIT = 0,
274         TPACPI_LIFE_RUNNING,
275         TPACPI_LIFE_EXITING,
276 } tpacpi_lifecycle;
277
278 static int experimental;
279 static u32 dbg_level;
280
281 static struct workqueue_struct *tpacpi_wq;
282
283 /* Special LED class that can defer work */
284 struct tpacpi_led_classdev {
285         struct led_classdev led_classdev;
286         struct work_struct work;
287         enum led_brightness new_brightness;
288         unsigned int led;
289 };
290
291 /****************************************************************************
292  ****************************************************************************
293  *
294  * ACPI Helpers and device model
295  *
296  ****************************************************************************
297  ****************************************************************************/
298
299 /*************************************************************************
300  * ACPI basic handles
301  */
302
303 static acpi_handle root_handle;
304
305 #define TPACPI_HANDLE(object, parent, paths...)                 \
306         static acpi_handle  object##_handle;                    \
307         static acpi_handle *object##_parent = &parent##_handle; \
308         static char        *object##_path;                      \
309         static char        *object##_paths[] = { paths }
310
311 TPACPI_HANDLE(ec, root, "\\_SB.PCI0.ISA.EC0",   /* 240, 240x */
312            "\\_SB.PCI.ISA.EC",  /* 570 */
313            "\\_SB.PCI0.ISA0.EC0",       /* 600e/x, 770e, 770x */
314            "\\_SB.PCI0.ISA.EC", /* A21e, A2xm/p, T20-22, X20-21 */
315            "\\_SB.PCI0.AD4S.EC0",       /* i1400, R30 */
316            "\\_SB.PCI0.ICH3.EC0",       /* R31 */
317            "\\_SB.PCI0.LPC.EC", /* all others */
318            );
319
320 TPACPI_HANDLE(ecrd, ec, "ECRD");        /* 570 */
321 TPACPI_HANDLE(ecwr, ec, "ECWR");        /* 570 */
322
323 TPACPI_HANDLE(cmos, root, "\\UCMS",     /* R50, R50e, R50p, R51, */
324                                         /* T4x, X31, X40 */
325            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
326            "\\CMS",             /* R40, R40e */
327            );                   /* all others */
328
329 TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY",   /* 600e/x, 770e, 770x */
330            "^HKEY",             /* R30, R31 */
331            "HKEY",              /* all others */
332            );                   /* 570 */
333
334 TPACPI_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA",   /* 570 */
335            "\\_SB.PCI0.AGP0.VID0",      /* 600e/x, 770x */
336            "\\_SB.PCI0.VID0",   /* 770e */
337            "\\_SB.PCI0.VID",    /* A21e, G4x, R50e, X30, X40 */
338            "\\_SB.PCI0.AGP.VID",        /* all others */
339            );                           /* R30, R31 */
340
341
342 /*************************************************************************
343  * ACPI helpers
344  */
345
346 static int acpi_evalf(acpi_handle handle,
347                       void *res, char *method, char *fmt, ...)
348 {
349         char *fmt0 = fmt;
350         struct acpi_object_list params;
351         union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS];
352         struct acpi_buffer result, *resultp;
353         union acpi_object out_obj;
354         acpi_status status;
355         va_list ap;
356         char res_type;
357         int success;
358         int quiet;
359
360         if (!*fmt) {
361                 printk(TPACPI_ERR "acpi_evalf() called with empty format\n");
362                 return 0;
363         }
364
365         if (*fmt == 'q') {
366                 quiet = 1;
367                 fmt++;
368         } else
369                 quiet = 0;
370
371         res_type = *(fmt++);
372
373         params.count = 0;
374         params.pointer = &in_objs[0];
375
376         va_start(ap, fmt);
377         while (*fmt) {
378                 char c = *(fmt++);
379                 switch (c) {
380                 case 'd':       /* int */
381                         in_objs[params.count].integer.value = va_arg(ap, int);
382                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
383                         break;
384                         /* add more types as needed */
385                 default:
386                         printk(TPACPI_ERR "acpi_evalf() called "
387                                "with invalid format character '%c'\n", c);
388                         return 0;
389                 }
390         }
391         va_end(ap);
392
393         if (res_type != 'v') {
394                 result.length = sizeof(out_obj);
395                 result.pointer = &out_obj;
396                 resultp = &result;
397         } else
398                 resultp = NULL;
399
400         status = acpi_evaluate_object(handle, method, &params, resultp);
401
402         switch (res_type) {
403         case 'd':               /* int */
404                 if (res)
405                         *(int *)res = out_obj.integer.value;
406                 success = status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER;
407                 break;
408         case 'v':               /* void */
409                 success = status == AE_OK;
410                 break;
411                 /* add more types as needed */
412         default:
413                 printk(TPACPI_ERR "acpi_evalf() called "
414                        "with invalid format character '%c'\n", res_type);
415                 return 0;
416         }
417
418         if (!success && !quiet)
419                 printk(TPACPI_ERR "acpi_evalf(%s, %s, ...) failed: %d\n",
420                        method, fmt0, status);
421
422         return success;
423 }
424
425 static int acpi_ec_read(int i, u8 *p)
426 {
427         int v;
428
429         if (ecrd_handle) {
430                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
431                         return 0;
432                 *p = v;
433         } else {
434                 if (ec_read(i, p) < 0)
435                         return 0;
436         }
437
438         return 1;
439 }
440
441 static int acpi_ec_write(int i, u8 v)
442 {
443         if (ecwr_handle) {
444                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
445                         return 0;
446         } else {
447                 if (ec_write(i, v) < 0)
448                         return 0;
449         }
450
451         return 1;
452 }
453
454 #if defined(CONFIG_THINKPAD_ACPI_DOCK) || defined(CONFIG_THINKPAD_ACPI_BAY)
455 static int _sta(acpi_handle handle)
456 {
457         int status;
458
459         if (!handle || !acpi_evalf(handle, &status, "_STA", "d"))
460                 status = 0;
461
462         return status;
463 }
464 #endif
465
466 static int issue_thinkpad_cmos_command(int cmos_cmd)
467 {
468         if (!cmos_handle)
469                 return -ENXIO;
470
471         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
472                 return -EIO;
473
474         return 0;
475 }
476
477 /*************************************************************************
478  * ACPI device model
479  */
480
481 #define TPACPI_ACPIHANDLE_INIT(object) \
482         drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \
483                 object##_paths, ARRAY_SIZE(object##_paths), &object##_path)
484
485 static void drv_acpi_handle_init(char *name,
486                            acpi_handle *handle, acpi_handle parent,
487                            char **paths, int num_paths, char **path)
488 {
489         int i;
490         acpi_status status;
491
492         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
493                 name);
494
495         for (i = 0; i < num_paths; i++) {
496                 status = acpi_get_handle(parent, paths[i], handle);
497                 if (ACPI_SUCCESS(status)) {
498                         *path = paths[i];
499                         dbg_printk(TPACPI_DBG_INIT,
500                                    "Found ACPI handle %s for %s\n",
501                                    *path, name);
502                         return;
503                 }
504         }
505
506         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
507                     name);
508         *handle = NULL;
509 }
510
511 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
512 {
513         struct ibm_struct *ibm = data;
514
515         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
516                 return;
517
518         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
519                 return;
520
521         ibm->acpi->notify(ibm, event);
522 }
523
524 static int __init setup_acpi_notify(struct ibm_struct *ibm)
525 {
526         acpi_status status;
527         int rc;
528
529         BUG_ON(!ibm->acpi);
530
531         if (!*ibm->acpi->handle)
532                 return 0;
533
534         vdbg_printk(TPACPI_DBG_INIT,
535                 "setting up ACPI notify for %s\n", ibm->name);
536
537         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
538         if (rc < 0) {
539                 printk(TPACPI_ERR "acpi_bus_get_device(%s) failed: %d\n",
540                         ibm->name, rc);
541                 return -ENODEV;
542         }
543
544         ibm->acpi->device->driver_data = ibm;
545         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
546                 TPACPI_ACPI_EVENT_PREFIX,
547                 ibm->name);
548
549         status = acpi_install_notify_handler(*ibm->acpi->handle,
550                         ibm->acpi->type, dispatch_acpi_notify, ibm);
551         if (ACPI_FAILURE(status)) {
552                 if (status == AE_ALREADY_EXISTS) {
553                         printk(TPACPI_NOTICE
554                                "another device driver is already "
555                                "handling %s events\n", ibm->name);
556                 } else {
557                         printk(TPACPI_ERR
558                                "acpi_install_notify_handler(%s) failed: %d\n",
559                                ibm->name, status);
560                 }
561                 return -ENODEV;
562         }
563         ibm->flags.acpi_notify_installed = 1;
564         return 0;
565 }
566
567 static int __init tpacpi_device_add(struct acpi_device *device)
568 {
569         return 0;
570 }
571
572 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
573 {
574         int rc;
575
576         dbg_printk(TPACPI_DBG_INIT,
577                 "registering %s as an ACPI driver\n", ibm->name);
578
579         BUG_ON(!ibm->acpi);
580
581         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
582         if (!ibm->acpi->driver) {
583                 printk(TPACPI_ERR
584                        "failed to allocate memory for ibm->acpi->driver\n");
585                 return -ENOMEM;
586         }
587
588         sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name);
589         ibm->acpi->driver->ids = ibm->acpi->hid;
590
591         ibm->acpi->driver->ops.add = &tpacpi_device_add;
592
593         rc = acpi_bus_register_driver(ibm->acpi->driver);
594         if (rc < 0) {
595                 printk(TPACPI_ERR "acpi_bus_register_driver(%s) failed: %d\n",
596                        ibm->name, rc);
597                 kfree(ibm->acpi->driver);
598                 ibm->acpi->driver = NULL;
599         } else if (!rc)
600                 ibm->flags.acpi_driver_registered = 1;
601
602         return rc;
603 }
604
605
606 /****************************************************************************
607  ****************************************************************************
608  *
609  * Procfs Helpers
610  *
611  ****************************************************************************
612  ****************************************************************************/
613
614 static int dispatch_procfs_read(char *page, char **start, off_t off,
615                         int count, int *eof, void *data)
616 {
617         struct ibm_struct *ibm = data;
618         int len;
619
620         if (!ibm || !ibm->read)
621                 return -EINVAL;
622
623         len = ibm->read(page);
624         if (len < 0)
625                 return len;
626
627         if (len <= off + count)
628                 *eof = 1;
629         *start = page + off;
630         len -= off;
631         if (len > count)
632                 len = count;
633         if (len < 0)
634                 len = 0;
635
636         return len;
637 }
638
639 static int dispatch_procfs_write(struct file *file,
640                         const char __user *userbuf,
641                         unsigned long count, void *data)
642 {
643         struct ibm_struct *ibm = data;
644         char *kernbuf;
645         int ret;
646
647         if (!ibm || !ibm->write)
648                 return -EINVAL;
649
650         kernbuf = kmalloc(count + 2, GFP_KERNEL);
651         if (!kernbuf)
652                 return -ENOMEM;
653
654         if (copy_from_user(kernbuf, userbuf, count)) {
655                 kfree(kernbuf);
656                 return -EFAULT;
657         }
658
659         kernbuf[count] = 0;
660         strcat(kernbuf, ",");
661         ret = ibm->write(kernbuf);
662         if (ret == 0)
663                 ret = count;
664
665         kfree(kernbuf);
666
667         return ret;
668 }
669
670 static char *next_cmd(char **cmds)
671 {
672         char *start = *cmds;
673         char *end;
674
675         while ((end = strchr(start, ',')) && end == start)
676                 start = end + 1;
677
678         if (!end)
679                 return NULL;
680
681         *end = 0;
682         *cmds = end + 1;
683         return start;
684 }
685
686
687 /****************************************************************************
688  ****************************************************************************
689  *
690  * Device model: input, hwmon and platform
691  *
692  ****************************************************************************
693  ****************************************************************************/
694
695 static struct platform_device *tpacpi_pdev;
696 static struct platform_device *tpacpi_sensors_pdev;
697 static struct device *tpacpi_hwmon;
698 static struct input_dev *tpacpi_inputdev;
699 static struct mutex tpacpi_inputdev_send_mutex;
700 static LIST_HEAD(tpacpi_all_drivers);
701
702 static int tpacpi_suspend_handler(struct platform_device *pdev,
703                                   pm_message_t state)
704 {
705         struct ibm_struct *ibm, *itmp;
706
707         list_for_each_entry_safe(ibm, itmp,
708                                  &tpacpi_all_drivers,
709                                  all_drivers) {
710                 if (ibm->suspend)
711                         (ibm->suspend)(state);
712         }
713
714         return 0;
715 }
716
717 static int tpacpi_resume_handler(struct platform_device *pdev)
718 {
719         struct ibm_struct *ibm, *itmp;
720
721         list_for_each_entry_safe(ibm, itmp,
722                                  &tpacpi_all_drivers,
723                                  all_drivers) {
724                 if (ibm->resume)
725                         (ibm->resume)();
726         }
727
728         return 0;
729 }
730
731 static struct platform_driver tpacpi_pdriver = {
732         .driver = {
733                 .name = TPACPI_DRVR_NAME,
734                 .owner = THIS_MODULE,
735         },
736         .suspend = tpacpi_suspend_handler,
737         .resume = tpacpi_resume_handler,
738 };
739
740 static struct platform_driver tpacpi_hwmon_pdriver = {
741         .driver = {
742                 .name = TPACPI_HWMON_DRVR_NAME,
743                 .owner = THIS_MODULE,
744         },
745 };
746
747 /*************************************************************************
748  * sysfs support helpers
749  */
750
751 struct attribute_set {
752         unsigned int members, max_members;
753         struct attribute_group group;
754 };
755
756 struct attribute_set_obj {
757         struct attribute_set s;
758         struct attribute *a;
759 } __attribute__((packed));
760
761 static struct attribute_set *create_attr_set(unsigned int max_members,
762                                                 const char *name)
763 {
764         struct attribute_set_obj *sobj;
765
766         if (max_members == 0)
767                 return NULL;
768
769         /* Allocates space for implicit NULL at the end too */
770         sobj = kzalloc(sizeof(struct attribute_set_obj) +
771                     max_members * sizeof(struct attribute *),
772                     GFP_KERNEL);
773         if (!sobj)
774                 return NULL;
775         sobj->s.max_members = max_members;
776         sobj->s.group.attrs = &sobj->a;
777         sobj->s.group.name = name;
778
779         return &sobj->s;
780 }
781
782 #define destroy_attr_set(_set) \
783         kfree(_set);
784
785 /* not multi-threaded safe, use it in a single thread per set */
786 static int add_to_attr_set(struct attribute_set *s, struct attribute *attr)
787 {
788         if (!s || !attr)
789                 return -EINVAL;
790
791         if (s->members >= s->max_members)
792                 return -ENOMEM;
793
794         s->group.attrs[s->members] = attr;
795         s->members++;
796
797         return 0;
798 }
799
800 static int add_many_to_attr_set(struct attribute_set *s,
801                         struct attribute **attr,
802                         unsigned int count)
803 {
804         int i, res;
805
806         for (i = 0; i < count; i++) {
807                 res = add_to_attr_set(s, attr[i]);
808                 if (res)
809                         return res;
810         }
811
812         return 0;
813 }
814
815 static void delete_attr_set(struct attribute_set *s, struct kobject *kobj)
816 {
817         sysfs_remove_group(kobj, &s->group);
818         destroy_attr_set(s);
819 }
820
821 #define register_attr_set_with_sysfs(_attr_set, _kobj) \
822         sysfs_create_group(_kobj, &_attr_set->group)
823
824 static int parse_strtoul(const char *buf,
825                 unsigned long max, unsigned long *value)
826 {
827         char *endp;
828
829         while (*buf && isspace(*buf))
830                 buf++;
831         *value = simple_strtoul(buf, &endp, 0);
832         while (*endp && isspace(*endp))
833                 endp++;
834         if (*endp || *value > max)
835                 return -EINVAL;
836
837         return 0;
838 }
839
840 static void tpacpi_disable_brightness_delay(void)
841 {
842         if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0))
843                 printk(TPACPI_NOTICE
844                         "ACPI backlight control delay disabled\n");
845 }
846
847 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
848 {
849         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
850         union acpi_object *obj;
851         int rc;
852
853         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
854                 obj = (union acpi_object *)buffer.pointer;
855                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
856                         printk(TPACPI_ERR "Unknown _BCL data, "
857                                "please report this to %s\n", TPACPI_MAIL);
858                         rc = 0;
859                 } else {
860                         rc = obj->package.count;
861                 }
862         } else {
863                 return 0;
864         }
865
866         kfree(buffer.pointer);
867         return rc;
868 }
869
870 static acpi_status __init tpacpi_acpi_walk_find_bcl(acpi_handle handle,
871                                         u32 lvl, void *context, void **rv)
872 {
873         char name[ACPI_PATH_SEGMENT_LENGTH];
874         struct acpi_buffer buffer = { sizeof(name), &name };
875
876         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
877             !strncmp("_BCL", name, sizeof(name) - 1)) {
878                 BUG_ON(!rv || !*rv);
879                 **(int **)rv = tpacpi_query_bcl_levels(handle);
880                 return AE_CTRL_TERMINATE;
881         } else {
882                 return AE_OK;
883         }
884 }
885
886 /*
887  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
888  */
889 static int __init tpacpi_check_std_acpi_brightness_support(void)
890 {
891         int status;
892         int bcl_levels = 0;
893         void *bcl_ptr = &bcl_levels;
894
895         if (!vid_handle) {
896                 TPACPI_ACPIHANDLE_INIT(vid);
897         }
898         if (!vid_handle)
899                 return 0;
900
901         /*
902          * Search for a _BCL method, and execute it.  This is safe on all
903          * ThinkPads, and as a side-effect, _BCL will place a Lenovo Vista
904          * BIOS in ACPI backlight control mode.  We do NOT have to care
905          * about calling the _BCL method in an enabled video device, any
906          * will do for our purposes.
907          */
908
909         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
910                                      tpacpi_acpi_walk_find_bcl, NULL,
911                                      &bcl_ptr);
912
913         if (ACPI_SUCCESS(status) && bcl_levels > 2) {
914                 tp_features.bright_acpimode = 1;
915                 return (bcl_levels - 2);
916         }
917
918         return 0;
919 }
920
921 static int __init tpacpi_new_rfkill(const unsigned int id,
922                         struct rfkill **rfk,
923                         const enum rfkill_type rfktype,
924                         const char *name,
925                         int (*toggle_radio)(void *, enum rfkill_state),
926                         int (*get_state)(void *, enum rfkill_state *))
927 {
928         int res;
929         enum rfkill_state initial_state;
930
931         *rfk = rfkill_allocate(&tpacpi_pdev->dev, rfktype);
932         if (!*rfk) {
933                 printk(TPACPI_ERR
934                         "failed to allocate memory for rfkill class\n");
935                 return -ENOMEM;
936         }
937
938         (*rfk)->name = name;
939         (*rfk)->get_state = get_state;
940         (*rfk)->toggle_radio = toggle_radio;
941
942         if (!get_state(NULL, &initial_state))
943                 (*rfk)->state = initial_state;
944
945         res = rfkill_register(*rfk);
946         if (res < 0) {
947                 printk(TPACPI_ERR
948                         "failed to register %s rfkill switch: %d\n",
949                         name, res);
950                 rfkill_free(*rfk);
951                 *rfk = NULL;
952                 return res;
953         }
954
955         return 0;
956 }
957
958 /*************************************************************************
959  * thinkpad-acpi driver attributes
960  */
961
962 /* interface_version --------------------------------------------------- */
963 static ssize_t tpacpi_driver_interface_version_show(
964                                 struct device_driver *drv,
965                                 char *buf)
966 {
967         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
968 }
969
970 static DRIVER_ATTR(interface_version, S_IRUGO,
971                 tpacpi_driver_interface_version_show, NULL);
972
973 /* debug_level --------------------------------------------------------- */
974 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
975                                                 char *buf)
976 {
977         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
978 }
979
980 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
981                                                 const char *buf, size_t count)
982 {
983         unsigned long t;
984
985         if (parse_strtoul(buf, 0xffff, &t))
986                 return -EINVAL;
987
988         dbg_level = t;
989
990         return count;
991 }
992
993 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
994                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
995
996 /* version ------------------------------------------------------------- */
997 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
998                                                 char *buf)
999 {
1000         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1001                         TPACPI_DESC, TPACPI_VERSION);
1002 }
1003
1004 static DRIVER_ATTR(version, S_IRUGO,
1005                 tpacpi_driver_version_show, NULL);
1006
1007 /* --------------------------------------------------------------------- */
1008
1009 static struct driver_attribute *tpacpi_driver_attributes[] = {
1010         &driver_attr_debug_level, &driver_attr_version,
1011         &driver_attr_interface_version,
1012 };
1013
1014 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1015 {
1016         int i, res;
1017
1018         i = 0;
1019         res = 0;
1020         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1021                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1022                 i++;
1023         }
1024
1025         return res;
1026 }
1027
1028 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1029 {
1030         int i;
1031
1032         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1033                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1034 }
1035
1036 /****************************************************************************
1037  ****************************************************************************
1038  *
1039  * Subdrivers
1040  *
1041  ****************************************************************************
1042  ****************************************************************************/
1043
1044 /*************************************************************************
1045  * thinkpad-acpi init subdriver
1046  */
1047
1048 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
1049 {
1050         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
1051         printk(TPACPI_INFO "%s\n", TPACPI_URL);
1052
1053         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
1054                 (thinkpad_id.bios_version_str) ?
1055                         thinkpad_id.bios_version_str : "unknown",
1056                 (thinkpad_id.ec_version_str) ?
1057                         thinkpad_id.ec_version_str : "unknown");
1058
1059         if (thinkpad_id.vendor && thinkpad_id.model_str)
1060                 printk(TPACPI_INFO "%s %s, model %s\n",
1061                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
1062                                 "IBM" : ((thinkpad_id.vendor ==
1063                                                 PCI_VENDOR_ID_LENOVO) ?
1064                                         "Lenovo" : "Unknown vendor"),
1065                         thinkpad_id.model_str,
1066                         (thinkpad_id.nummodel_str) ?
1067                                 thinkpad_id.nummodel_str : "unknown");
1068
1069         return 0;
1070 }
1071
1072 static int thinkpad_acpi_driver_read(char *p)
1073 {
1074         int len = 0;
1075
1076         len += sprintf(p + len, "driver:\t\t%s\n", TPACPI_DESC);
1077         len += sprintf(p + len, "version:\t%s\n", TPACPI_VERSION);
1078
1079         return len;
1080 }
1081
1082 static struct ibm_struct thinkpad_acpi_driver_data = {
1083         .name = "driver",
1084         .read = thinkpad_acpi_driver_read,
1085 };
1086
1087 /*************************************************************************
1088  * Hotkey subdriver
1089  */
1090
1091 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1092         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1093         TP_ACPI_HOTKEYSCAN_FNF2,
1094         TP_ACPI_HOTKEYSCAN_FNF3,
1095         TP_ACPI_HOTKEYSCAN_FNF4,
1096         TP_ACPI_HOTKEYSCAN_FNF5,
1097         TP_ACPI_HOTKEYSCAN_FNF6,
1098         TP_ACPI_HOTKEYSCAN_FNF7,
1099         TP_ACPI_HOTKEYSCAN_FNF8,
1100         TP_ACPI_HOTKEYSCAN_FNF9,
1101         TP_ACPI_HOTKEYSCAN_FNF10,
1102         TP_ACPI_HOTKEYSCAN_FNF11,
1103         TP_ACPI_HOTKEYSCAN_FNF12,
1104         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1105         TP_ACPI_HOTKEYSCAN_FNINSERT,
1106         TP_ACPI_HOTKEYSCAN_FNDELETE,
1107         TP_ACPI_HOTKEYSCAN_FNHOME,
1108         TP_ACPI_HOTKEYSCAN_FNEND,
1109         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1110         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1111         TP_ACPI_HOTKEYSCAN_FNSPACE,
1112         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1113         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1114         TP_ACPI_HOTKEYSCAN_MUTE,
1115         TP_ACPI_HOTKEYSCAN_THINKPAD,
1116 };
1117
1118 enum {  /* Keys available through NVRAM polling */
1119         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1120         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1121 };
1122
1123 enum {  /* Positions of some of the keys in hotkey masks */
1124         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1125         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1126         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1127         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1128         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1129         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1130         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1131         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1132         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1133         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1134         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1135 };
1136
1137 enum {  /* NVRAM to ACPI HKEY group map */
1138         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1139                                           TP_ACPI_HKEY_ZOOM_MASK |
1140                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1141                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1142         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1143                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1144         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1145                                           TP_ACPI_HKEY_VOLDWN_MASK |
1146                                           TP_ACPI_HKEY_MUTE_MASK,
1147 };
1148
1149 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1150 struct tp_nvram_state {
1151        u16 thinkpad_toggle:1;
1152        u16 zoom_toggle:1;
1153        u16 display_toggle:1;
1154        u16 thinklight_toggle:1;
1155        u16 hibernate_toggle:1;
1156        u16 displayexp_toggle:1;
1157        u16 display_state:1;
1158        u16 brightness_toggle:1;
1159        u16 volume_toggle:1;
1160        u16 mute:1;
1161
1162        u8 brightness_level;
1163        u8 volume_level;
1164 };
1165
1166 static struct task_struct *tpacpi_hotkey_task;
1167 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
1168 static int hotkey_poll_freq = 10;       /* Hz */
1169 static struct mutex hotkey_thread_mutex;
1170 static struct mutex hotkey_thread_data_mutex;
1171 static unsigned int hotkey_config_change;
1172
1173 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1174
1175 #define hotkey_source_mask 0U
1176
1177 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1178
1179 static struct mutex hotkey_mutex;
1180
1181 static enum {   /* Reasons for waking up */
1182         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
1183         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
1184         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
1185 } hotkey_wakeup_reason;
1186
1187 static int hotkey_autosleep_ack;
1188
1189 static int hotkey_orig_status;
1190 static u32 hotkey_orig_mask;
1191 static u32 hotkey_all_mask;
1192 static u32 hotkey_reserved_mask;
1193 static u32 hotkey_mask;
1194
1195 static unsigned int hotkey_report_mode;
1196
1197 static u16 *hotkey_keycode_map;
1198
1199 static struct attribute_set *hotkey_dev_attributes;
1200
1201 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1202 #define HOTKEY_CONFIG_CRITICAL_START \
1203         do { \
1204                 mutex_lock(&hotkey_thread_data_mutex); \
1205                 hotkey_config_change++; \
1206         } while (0);
1207 #define HOTKEY_CONFIG_CRITICAL_END \
1208         mutex_unlock(&hotkey_thread_data_mutex);
1209 #else
1210 #define HOTKEY_CONFIG_CRITICAL_START
1211 #define HOTKEY_CONFIG_CRITICAL_END
1212 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1213
1214 /* HKEY.MHKG() return bits */
1215 #define TP_HOTKEY_TABLET_MASK (1 << 3)
1216
1217 static int hotkey_get_wlsw(int *status)
1218 {
1219         if (!acpi_evalf(hkey_handle, status, "WLSW", "d"))
1220                 return -EIO;
1221         return 0;
1222 }
1223
1224 static int hotkey_get_tablet_mode(int *status)
1225 {
1226         int s;
1227
1228         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
1229                 return -EIO;
1230
1231         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
1232         return 0;
1233 }
1234
1235 /*
1236  * Call with hotkey_mutex held
1237  */
1238 static int hotkey_mask_get(void)
1239 {
1240         u32 m = 0;
1241
1242         if (tp_features.hotkey_mask) {
1243                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
1244                         return -EIO;
1245         }
1246         hotkey_mask = m | (hotkey_source_mask & hotkey_mask);
1247
1248         return 0;
1249 }
1250
1251 /*
1252  * Call with hotkey_mutex held
1253  */
1254 static int hotkey_mask_set(u32 mask)
1255 {
1256         int i;
1257         int rc = 0;
1258
1259         if (tp_features.hotkey_mask) {
1260                 if (!tp_warned.hotkey_mask_ff &&
1261                     (mask == 0xffff || mask == 0xffffff ||
1262                      mask == 0xffffffff)) {
1263                         tp_warned.hotkey_mask_ff = 1;
1264                         printk(TPACPI_NOTICE
1265                                "setting the hotkey mask to 0x%08x is likely "
1266                                "not the best way to go about it\n", mask);
1267                         printk(TPACPI_NOTICE
1268                                "please consider using the driver defaults, "
1269                                "and refer to up-to-date thinkpad-acpi "
1270                                "documentation\n");
1271                 }
1272
1273                 HOTKEY_CONFIG_CRITICAL_START
1274                 for (i = 0; i < 32; i++) {
1275                         u32 m = 1 << i;
1276                         /* enable in firmware mask only keys not in NVRAM
1277                          * mode, but enable the key in the cached hotkey_mask
1278                          * regardless of mode, or the key will end up
1279                          * disabled by hotkey_mask_get() */
1280                         if (!acpi_evalf(hkey_handle,
1281                                         NULL, "MHKM", "vdd", i + 1,
1282                                         !!((mask & ~hotkey_source_mask) & m))) {
1283                                 rc = -EIO;
1284                                 break;
1285                         } else {
1286                                 hotkey_mask = (hotkey_mask & ~m) | (mask & m);
1287                         }
1288                 }
1289                 HOTKEY_CONFIG_CRITICAL_END
1290
1291                 /* hotkey_mask_get must be called unconditionally below */
1292                 if (!hotkey_mask_get() && !rc &&
1293                     (hotkey_mask & ~hotkey_source_mask) !=
1294                      (mask & ~hotkey_source_mask)) {
1295                         printk(TPACPI_NOTICE
1296                                "requested hot key mask 0x%08x, but "
1297                                "firmware forced it to 0x%08x\n",
1298                                mask, hotkey_mask);
1299                 }
1300         } else {
1301 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1302                 HOTKEY_CONFIG_CRITICAL_START
1303                 hotkey_mask = mask & hotkey_source_mask;
1304                 HOTKEY_CONFIG_CRITICAL_END
1305                 hotkey_mask_get();
1306                 if (hotkey_mask != mask) {
1307                         printk(TPACPI_NOTICE
1308                                "requested hot key mask 0x%08x, "
1309                                "forced to 0x%08x (NVRAM poll mask is "
1310                                "0x%08x): no firmware mask support\n",
1311                                mask, hotkey_mask, hotkey_source_mask);
1312                 }
1313 #else
1314                 hotkey_mask_get();
1315                 rc = -ENXIO;
1316 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1317         }
1318
1319         return rc;
1320 }
1321
1322 static int hotkey_status_get(int *status)
1323 {
1324         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
1325                 return -EIO;
1326
1327         return 0;
1328 }
1329
1330 static int hotkey_status_set(int status)
1331 {
1332         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", status))
1333                 return -EIO;
1334
1335         return 0;
1336 }
1337
1338 static void tpacpi_input_send_tabletsw(void)
1339 {
1340         int state;
1341
1342         if (tp_features.hotkey_tablet &&
1343             !hotkey_get_tablet_mode(&state)) {
1344                 mutex_lock(&tpacpi_inputdev_send_mutex);
1345
1346                 input_report_switch(tpacpi_inputdev,
1347                                     SW_TABLET_MODE, !!state);
1348                 input_sync(tpacpi_inputdev);
1349
1350                 mutex_unlock(&tpacpi_inputdev_send_mutex);
1351         }
1352 }
1353
1354 static void tpacpi_input_send_key(unsigned int scancode)
1355 {
1356         unsigned int keycode;
1357
1358         keycode = hotkey_keycode_map[scancode];
1359
1360         if (keycode != KEY_RESERVED) {
1361                 mutex_lock(&tpacpi_inputdev_send_mutex);
1362
1363                 input_report_key(tpacpi_inputdev, keycode, 1);
1364                 if (keycode == KEY_UNKNOWN)
1365                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
1366                                     scancode);
1367                 input_sync(tpacpi_inputdev);
1368
1369                 input_report_key(tpacpi_inputdev, keycode, 0);
1370                 if (keycode == KEY_UNKNOWN)
1371                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
1372                                     scancode);
1373                 input_sync(tpacpi_inputdev);
1374
1375                 mutex_unlock(&tpacpi_inputdev_send_mutex);
1376         }
1377 }
1378
1379 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1380 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
1381
1382 static void tpacpi_hotkey_send_key(unsigned int scancode)
1383 {
1384         tpacpi_input_send_key(scancode);
1385         if (hotkey_report_mode < 2) {
1386                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
1387                                                 0x80, 0x1001 + scancode);
1388         }
1389 }
1390
1391 static void hotkey_read_nvram(struct tp_nvram_state *n, u32 m)
1392 {
1393         u8 d;
1394
1395         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
1396                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
1397                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
1398                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
1399                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
1400                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
1401         }
1402         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
1403                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
1404                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
1405         }
1406         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
1407                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
1408                 n->displayexp_toggle =
1409                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
1410         }
1411         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
1412                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
1413                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
1414                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
1415                 n->brightness_toggle =
1416                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
1417         }
1418         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
1419                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
1420                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
1421                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
1422                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
1423                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
1424         }
1425 }
1426
1427 #define TPACPI_COMPARE_KEY(__scancode, __member) \
1428         do { \
1429                 if ((mask & (1 << __scancode)) && \
1430                     oldn->__member != newn->__member) \
1431                 tpacpi_hotkey_send_key(__scancode); \
1432         } while (0)
1433
1434 #define TPACPI_MAY_SEND_KEY(__scancode) \
1435         do { if (mask & (1 << __scancode)) \
1436                 tpacpi_hotkey_send_key(__scancode); } while (0)
1437
1438 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
1439                                            struct tp_nvram_state *newn,
1440                                            u32 mask)
1441 {
1442         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
1443         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
1444         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
1445         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
1446
1447         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
1448
1449         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
1450
1451         /* handle volume */
1452         if (oldn->volume_toggle != newn->volume_toggle) {
1453                 if (oldn->mute != newn->mute) {
1454                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
1455                 }
1456                 if (oldn->volume_level > newn->volume_level) {
1457                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
1458                 } else if (oldn->volume_level < newn->volume_level) {
1459                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
1460                 } else if (oldn->mute == newn->mute) {
1461                         /* repeated key presses that didn't change state */
1462                         if (newn->mute) {
1463                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
1464                         } else if (newn->volume_level != 0) {
1465                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
1466                         } else {
1467                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
1468                         }
1469                 }
1470         }
1471
1472         /* handle brightness */
1473         if (oldn->brightness_toggle != newn->brightness_toggle) {
1474                 if (oldn->brightness_level < newn->brightness_level) {
1475                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
1476                 } else if (oldn->brightness_level > newn->brightness_level) {
1477                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
1478                 } else {
1479                         /* repeated key presses that didn't change state */
1480                         if (newn->brightness_level != 0) {
1481                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
1482                         } else {
1483                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
1484                         }
1485                 }
1486         }
1487 }
1488
1489 #undef TPACPI_COMPARE_KEY
1490 #undef TPACPI_MAY_SEND_KEY
1491
1492 static int hotkey_kthread(void *data)
1493 {
1494         struct tp_nvram_state s[2];
1495         u32 mask;
1496         unsigned int si, so;
1497         unsigned long t;
1498         unsigned int change_detector, must_reset;
1499
1500         mutex_lock(&hotkey_thread_mutex);
1501
1502         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
1503                 goto exit;
1504
1505         set_freezable();
1506
1507         so = 0;
1508         si = 1;
1509         t = 0;
1510
1511         /* Initial state for compares */
1512         mutex_lock(&hotkey_thread_data_mutex);
1513         change_detector = hotkey_config_change;
1514         mask = hotkey_source_mask & hotkey_mask;
1515         mutex_unlock(&hotkey_thread_data_mutex);
1516         hotkey_read_nvram(&s[so], mask);
1517
1518         while (!kthread_should_stop() && hotkey_poll_freq) {
1519                 if (t == 0)
1520                         t = 1000/hotkey_poll_freq;
1521                 t = msleep_interruptible(t);
1522                 if (unlikely(kthread_should_stop()))
1523                         break;
1524                 must_reset = try_to_freeze();
1525                 if (t > 0 && !must_reset)
1526                         continue;
1527
1528                 mutex_lock(&hotkey_thread_data_mutex);
1529                 if (must_reset || hotkey_config_change != change_detector) {
1530                         /* forget old state on thaw or config change */
1531                         si = so;
1532                         t = 0;
1533                         change_detector = hotkey_config_change;
1534                 }
1535                 mask = hotkey_source_mask & hotkey_mask;
1536                 mutex_unlock(&hotkey_thread_data_mutex);
1537
1538                 if (likely(mask)) {
1539                         hotkey_read_nvram(&s[si], mask);
1540                         if (likely(si != so)) {
1541                                 hotkey_compare_and_issue_event(&s[so], &s[si],
1542                                                                 mask);
1543                         }
1544                 }
1545
1546                 so = si;
1547                 si ^= 1;
1548         }
1549
1550 exit:
1551         mutex_unlock(&hotkey_thread_mutex);
1552         return 0;
1553 }
1554
1555 static void hotkey_poll_stop_sync(void)
1556 {
1557         if (tpacpi_hotkey_task) {
1558                 if (frozen(tpacpi_hotkey_task) ||
1559                     freezing(tpacpi_hotkey_task))
1560                         thaw_process(tpacpi_hotkey_task);
1561
1562                 kthread_stop(tpacpi_hotkey_task);
1563                 tpacpi_hotkey_task = NULL;
1564                 mutex_lock(&hotkey_thread_mutex);
1565                 /* at this point, the thread did exit */
1566                 mutex_unlock(&hotkey_thread_mutex);
1567         }
1568 }
1569
1570 /* call with hotkey_mutex held */
1571 static void hotkey_poll_setup(int may_warn)
1572 {
1573         if ((hotkey_source_mask & hotkey_mask) != 0 &&
1574             hotkey_poll_freq > 0 &&
1575             (tpacpi_inputdev->users > 0 || hotkey_report_mode < 2)) {
1576                 if (!tpacpi_hotkey_task) {
1577                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
1578                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
1579                         if (IS_ERR(tpacpi_hotkey_task)) {
1580                                 tpacpi_hotkey_task = NULL;
1581                                 printk(TPACPI_ERR
1582                                        "could not create kernel thread "
1583                                        "for hotkey polling\n");
1584                         }
1585                 }
1586         } else {
1587                 hotkey_poll_stop_sync();
1588                 if (may_warn &&
1589                     hotkey_source_mask != 0 && hotkey_poll_freq == 0) {
1590                         printk(TPACPI_NOTICE
1591                                 "hot keys 0x%08x require polling, "
1592                                 "which is currently disabled\n",
1593                                 hotkey_source_mask);
1594                 }
1595         }
1596 }
1597
1598 static void hotkey_poll_setup_safe(int may_warn)
1599 {
1600         mutex_lock(&hotkey_mutex);
1601         hotkey_poll_setup(may_warn);
1602         mutex_unlock(&hotkey_mutex);
1603 }
1604
1605 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1606
1607 static void hotkey_poll_setup_safe(int __unused)
1608 {
1609 }
1610
1611 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1612
1613 static int hotkey_inputdev_open(struct input_dev *dev)
1614 {
1615         switch (tpacpi_lifecycle) {
1616         case TPACPI_LIFE_INIT:
1617                 /*
1618                  * hotkey_init will call hotkey_poll_setup_safe
1619                  * at the appropriate moment
1620                  */
1621                 return 0;
1622         case TPACPI_LIFE_EXITING:
1623                 return -EBUSY;
1624         case TPACPI_LIFE_RUNNING:
1625                 hotkey_poll_setup_safe(0);
1626                 return 0;
1627         }
1628
1629         /* Should only happen if tpacpi_lifecycle is corrupt */
1630         BUG();
1631         return -EBUSY;
1632 }
1633
1634 static void hotkey_inputdev_close(struct input_dev *dev)
1635 {
1636         /* disable hotkey polling when possible */
1637         if (tpacpi_lifecycle == TPACPI_LIFE_RUNNING)
1638                 hotkey_poll_setup_safe(0);
1639 }
1640
1641 /* sysfs hotkey enable ------------------------------------------------- */
1642 static ssize_t hotkey_enable_show(struct device *dev,
1643                            struct device_attribute *attr,
1644                            char *buf)
1645 {
1646         int res, status;
1647
1648         res = hotkey_status_get(&status);
1649         if (res)
1650                 return res;
1651
1652         return snprintf(buf, PAGE_SIZE, "%d\n", status);
1653 }
1654
1655 static ssize_t hotkey_enable_store(struct device *dev,
1656                             struct device_attribute *attr,
1657                             const char *buf, size_t count)
1658 {
1659         unsigned long t;
1660         int res;
1661
1662         if (parse_strtoul(buf, 1, &t))
1663                 return -EINVAL;
1664
1665         res = hotkey_status_set(t);
1666
1667         return (res) ? res : count;
1668 }
1669
1670 static struct device_attribute dev_attr_hotkey_enable =
1671         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
1672                 hotkey_enable_show, hotkey_enable_store);
1673
1674 /* sysfs hotkey mask --------------------------------------------------- */
1675 static ssize_t hotkey_mask_show(struct device *dev,
1676                            struct device_attribute *attr,
1677                            char *buf)
1678 {
1679         int res;
1680
1681         if (mutex_lock_interruptible(&hotkey_mutex))
1682                 return -ERESTARTSYS;
1683         res = hotkey_mask_get();
1684         mutex_unlock(&hotkey_mutex);
1685
1686         return (res)?
1687                 res : snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_mask);
1688 }
1689
1690 static ssize_t hotkey_mask_store(struct device *dev,
1691                             struct device_attribute *attr,
1692                             const char *buf, size_t count)
1693 {
1694         unsigned long t;
1695         int res;
1696
1697         if (parse_strtoul(buf, 0xffffffffUL, &t))
1698                 return -EINVAL;
1699
1700         if (mutex_lock_interruptible(&hotkey_mutex))
1701                 return -ERESTARTSYS;
1702
1703         res = hotkey_mask_set(t);
1704
1705 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1706         hotkey_poll_setup(1);
1707 #endif
1708
1709         mutex_unlock(&hotkey_mutex);
1710
1711         return (res) ? res : count;
1712 }
1713
1714 static struct device_attribute dev_attr_hotkey_mask =
1715         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
1716                 hotkey_mask_show, hotkey_mask_store);
1717
1718 /* sysfs hotkey bios_enabled ------------------------------------------- */
1719 static ssize_t hotkey_bios_enabled_show(struct device *dev,
1720                            struct device_attribute *attr,
1721                            char *buf)
1722 {
1723         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_orig_status);
1724 }
1725
1726 static struct device_attribute dev_attr_hotkey_bios_enabled =
1727         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
1728
1729 /* sysfs hotkey bios_mask ---------------------------------------------- */
1730 static ssize_t hotkey_bios_mask_show(struct device *dev,
1731                            struct device_attribute *attr,
1732                            char *buf)
1733 {
1734         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
1735 }
1736
1737 static struct device_attribute dev_attr_hotkey_bios_mask =
1738         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
1739
1740 /* sysfs hotkey all_mask ----------------------------------------------- */
1741 static ssize_t hotkey_all_mask_show(struct device *dev,
1742                            struct device_attribute *attr,
1743                            char *buf)
1744 {
1745         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
1746                                 hotkey_all_mask | hotkey_source_mask);
1747 }
1748
1749 static struct device_attribute dev_attr_hotkey_all_mask =
1750         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
1751
1752 /* sysfs hotkey recommended_mask --------------------------------------- */
1753 static ssize_t hotkey_recommended_mask_show(struct device *dev,
1754                                             struct device_attribute *attr,
1755                                             char *buf)
1756 {
1757         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
1758                         (hotkey_all_mask | hotkey_source_mask)
1759                         & ~hotkey_reserved_mask);
1760 }
1761
1762 static struct device_attribute dev_attr_hotkey_recommended_mask =
1763         __ATTR(hotkey_recommended_mask, S_IRUGO,
1764                 hotkey_recommended_mask_show, NULL);
1765
1766 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1767
1768 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
1769 static ssize_t hotkey_source_mask_show(struct device *dev,
1770                            struct device_attribute *attr,
1771                            char *buf)
1772 {
1773         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
1774 }
1775
1776 static ssize_t hotkey_source_mask_store(struct device *dev,
1777                             struct device_attribute *attr,
1778                             const char *buf, size_t count)
1779 {
1780         unsigned long t;
1781
1782         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
1783                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
1784                 return -EINVAL;
1785
1786         if (mutex_lock_interruptible(&hotkey_mutex))
1787                 return -ERESTARTSYS;
1788
1789         HOTKEY_CONFIG_CRITICAL_START
1790         hotkey_source_mask = t;
1791         HOTKEY_CONFIG_CRITICAL_END
1792
1793         hotkey_poll_setup(1);
1794
1795         mutex_unlock(&hotkey_mutex);
1796
1797         return count;
1798 }
1799
1800 static struct device_attribute dev_attr_hotkey_source_mask =
1801         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
1802                 hotkey_source_mask_show, hotkey_source_mask_store);
1803
1804 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
1805 static ssize_t hotkey_poll_freq_show(struct device *dev,
1806                            struct device_attribute *attr,
1807                            char *buf)
1808 {
1809         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
1810 }
1811
1812 static ssize_t hotkey_poll_freq_store(struct device *dev,
1813                             struct device_attribute *attr,
1814                             const char *buf, size_t count)
1815 {
1816         unsigned long t;
1817
1818         if (parse_strtoul(buf, 25, &t))
1819                 return -EINVAL;
1820
1821         if (mutex_lock_interruptible(&hotkey_mutex))
1822                 return -ERESTARTSYS;
1823
1824         hotkey_poll_freq = t;
1825
1826         hotkey_poll_setup(1);
1827         mutex_unlock(&hotkey_mutex);
1828
1829         return count;
1830 }
1831
1832 static struct device_attribute dev_attr_hotkey_poll_freq =
1833         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
1834                 hotkey_poll_freq_show, hotkey_poll_freq_store);
1835
1836 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1837
1838 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
1839 static ssize_t hotkey_radio_sw_show(struct device *dev,
1840                            struct device_attribute *attr,
1841                            char *buf)
1842 {
1843         int res, s;
1844         res = hotkey_get_wlsw(&s);
1845         if (res < 0)
1846                 return res;
1847
1848         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
1849 }
1850
1851 static struct device_attribute dev_attr_hotkey_radio_sw =
1852         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
1853
1854 static void hotkey_radio_sw_notify_change(void)
1855 {
1856         if (tp_features.hotkey_wlsw)
1857                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
1858                              "hotkey_radio_sw");
1859 }
1860
1861 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
1862 static ssize_t hotkey_tablet_mode_show(struct device *dev,
1863                            struct device_attribute *attr,
1864                            char *buf)
1865 {
1866         int res, s;
1867         res = hotkey_get_tablet_mode(&s);
1868         if (res < 0)
1869                 return res;
1870
1871         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
1872 }
1873
1874 static struct device_attribute dev_attr_hotkey_tablet_mode =
1875         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
1876
1877 static void hotkey_tablet_mode_notify_change(void)
1878 {
1879         if (tp_features.hotkey_tablet)
1880                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
1881                              "hotkey_tablet_mode");
1882 }
1883
1884 /* sysfs hotkey report_mode -------------------------------------------- */
1885 static ssize_t hotkey_report_mode_show(struct device *dev,
1886                            struct device_attribute *attr,
1887                            char *buf)
1888 {
1889         return snprintf(buf, PAGE_SIZE, "%d\n",
1890                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
1891 }
1892
1893 static struct device_attribute dev_attr_hotkey_report_mode =
1894         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
1895
1896 /* sysfs wakeup reason (pollable) -------------------------------------- */
1897 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
1898                            struct device_attribute *attr,
1899                            char *buf)
1900 {
1901         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
1902 }
1903
1904 static struct device_attribute dev_attr_hotkey_wakeup_reason =
1905         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
1906
1907 static void hotkey_wakeup_reason_notify_change(void)
1908 {
1909         if (tp_features.hotkey_mask)
1910                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
1911                              "wakeup_reason");
1912 }
1913
1914 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
1915 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
1916                            struct device_attribute *attr,
1917                            char *buf)
1918 {
1919         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
1920 }
1921
1922 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
1923         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
1924                hotkey_wakeup_hotunplug_complete_show, NULL);
1925
1926 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
1927 {
1928         if (tp_features.hotkey_mask)
1929                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
1930                              "wakeup_hotunplug_complete");
1931 }
1932
1933 /* --------------------------------------------------------------------- */
1934
1935 static struct attribute *hotkey_attributes[] __initdata = {
1936         &dev_attr_hotkey_enable.attr,
1937         &dev_attr_hotkey_bios_enabled.attr,
1938         &dev_attr_hotkey_report_mode.attr,
1939 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1940         &dev_attr_hotkey_mask.attr,
1941         &dev_attr_hotkey_all_mask.attr,
1942         &dev_attr_hotkey_recommended_mask.attr,
1943         &dev_attr_hotkey_source_mask.attr,
1944         &dev_attr_hotkey_poll_freq.attr,
1945 #endif
1946 };
1947
1948 static struct attribute *hotkey_mask_attributes[] __initdata = {
1949         &dev_attr_hotkey_bios_mask.attr,
1950 #ifndef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1951         &dev_attr_hotkey_mask.attr,
1952         &dev_attr_hotkey_all_mask.attr,
1953         &dev_attr_hotkey_recommended_mask.attr,
1954 #endif
1955         &dev_attr_hotkey_wakeup_reason.attr,
1956         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
1957 };
1958
1959 static void bluetooth_update_rfk(void);
1960 static void wan_update_rfk(void);
1961 static void tpacpi_send_radiosw_update(void)
1962 {
1963         int wlsw;
1964
1965         /* Sync these BEFORE sending any rfkill events */
1966         if (tp_features.bluetooth)
1967                 bluetooth_update_rfk();
1968         if (tp_features.wan)
1969                 wan_update_rfk();
1970
1971         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&wlsw)) {
1972                 mutex_lock(&tpacpi_inputdev_send_mutex);
1973
1974                 input_report_switch(tpacpi_inputdev,
1975                                     SW_RFKILL_ALL, !!wlsw);
1976                 input_sync(tpacpi_inputdev);
1977
1978                 mutex_unlock(&tpacpi_inputdev_send_mutex);
1979         }
1980         hotkey_radio_sw_notify_change();
1981 }
1982
1983 static void hotkey_exit(void)
1984 {
1985 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1986         hotkey_poll_stop_sync();
1987 #endif
1988
1989         if (hotkey_dev_attributes)
1990                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
1991
1992         kfree(hotkey_keycode_map);
1993
1994         if (tp_features.hotkey) {
1995                 dbg_printk(TPACPI_DBG_EXIT,
1996                            "restoring original hot key mask\n");
1997                 /* no short-circuit boolean operator below! */
1998                 if ((hotkey_mask_set(hotkey_orig_mask) |
1999                      hotkey_status_set(hotkey_orig_status)) != 0)
2000                         printk(TPACPI_ERR
2001                                "failed to restore hot key mask "
2002                                "to BIOS defaults\n");
2003         }
2004 }
2005
2006 static int __init hotkey_init(struct ibm_init_struct *iibm)
2007 {
2008         /* Requirements for changing the default keymaps:
2009          *
2010          * 1. Many of the keys are mapped to KEY_RESERVED for very
2011          *    good reasons.  Do not change them unless you have deep
2012          *    knowledge on the IBM and Lenovo ThinkPad firmware for
2013          *    the various ThinkPad models.  The driver behaves
2014          *    differently for KEY_RESERVED: such keys have their
2015          *    hot key mask *unset* in mask_recommended, and also
2016          *    in the initial hot key mask programmed into the
2017          *    firmware at driver load time, which means the firm-
2018          *    ware may react very differently if you change them to
2019          *    something else;
2020          *
2021          * 2. You must be subscribed to the linux-thinkpad and
2022          *    ibm-acpi-devel mailing lists, and you should read the
2023          *    list archives since 2007 if you want to change the
2024          *    keymaps.  This requirement exists so that you will
2025          *    know the past history of problems with the thinkpad-
2026          *    acpi driver keymaps, and also that you will be
2027          *    listening to any bug reports;
2028          *
2029          * 3. Do not send thinkpad-acpi specific patches directly to
2030          *    for merging, *ever*.  Send them to the linux-acpi
2031          *    mailinglist for comments.  Merging is to be done only
2032          *    through acpi-test and the ACPI maintainer.
2033          *
2034          * If the above is too much to ask, don't change the keymap.
2035          * Ask the thinkpad-acpi maintainer to do it, instead.
2036          */
2037         static u16 ibm_keycode_map[] __initdata = {
2038                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
2039                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
2040                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
2041                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
2042
2043                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
2044                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
2045                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
2046                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
2047
2048                 /* brightness: firmware always reacts to them, unless
2049                  * X.org did some tricks in the radeon BIOS scratch
2050                  * registers of *some* models */
2051                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
2052                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
2053
2054                 /* Thinklight: firmware always react to it */
2055                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
2056
2057                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
2058                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
2059
2060                 /* Volume: firmware always react to it and reprograms
2061                  * the built-in *extra* mixer.  Never map it to control
2062                  * another mixer by default. */
2063                 KEY_RESERVED,   /* 0x14: VOLUME UP */
2064                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
2065                 KEY_RESERVED,   /* 0x16: MUTE */
2066
2067                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
2068
2069                 /* (assignments unknown, please report if found) */
2070                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2071                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2072         };
2073         static u16 lenovo_keycode_map[] __initdata = {
2074                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
2075                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
2076                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
2077                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
2078
2079                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
2080                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
2081                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
2082                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
2083
2084                 /* These either have to go through ACPI video, or
2085                  * act like in the IBM ThinkPads, so don't ever
2086                  * enable them by default */
2087                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
2088                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
2089
2090                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
2091
2092                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
2093                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
2094
2095                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
2096                  * react to it and reprograms the built-in *extra* mixer.
2097                  * Never map it to control another mixer by default.
2098                  *
2099                  * T60?, T61, R60?, R61: firmware and EC tries to send
2100                  * these over the regular keyboard, so these are no-ops,
2101                  * but there are still weird bugs re. MUTE, so do not
2102                  * change unless you get test reports from all Lenovo
2103                  * models.  May cause the BIOS to interfere with the
2104                  * HDA mixer.
2105                  */
2106                 KEY_RESERVED,   /* 0x14: VOLUME UP */
2107                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
2108                 KEY_RESERVED,   /* 0x16: MUTE */
2109
2110                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
2111
2112                 /* (assignments unknown, please report if found) */
2113                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2114                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2115         };
2116
2117 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
2118 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
2119 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
2120
2121         int res, i;
2122         int status;
2123         int hkeyv;
2124
2125         vdbg_printk(TPACPI_DBG_INIT, "initializing hotkey subdriver\n");
2126
2127         BUG_ON(!tpacpi_inputdev);
2128         BUG_ON(tpacpi_inputdev->open != NULL ||
2129                tpacpi_inputdev->close != NULL);
2130
2131         TPACPI_ACPIHANDLE_INIT(hkey);
2132         mutex_init(&hotkey_mutex);
2133
2134 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2135         mutex_init(&hotkey_thread_mutex);
2136         mutex_init(&hotkey_thread_data_mutex);
2137 #endif
2138
2139         /* hotkey not supported on 570 */
2140         tp_features.hotkey = hkey_handle != NULL;
2141
2142         vdbg_printk(TPACPI_DBG_INIT, "hotkeys are %s\n",
2143                 str_supported(tp_features.hotkey));
2144
2145         if (!tp_features.hotkey)
2146                 return 1;
2147
2148         tpacpi_disable_brightness_delay();
2149
2150         hotkey_dev_attributes = create_attr_set(13, NULL);
2151         if (!hotkey_dev_attributes)
2152                 return -ENOMEM;
2153         res = add_many_to_attr_set(hotkey_dev_attributes,
2154                         hotkey_attributes,
2155                         ARRAY_SIZE(hotkey_attributes));
2156         if (res)
2157                 goto err_exit;
2158
2159         /* mask not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
2160            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
2161            for HKEY interface version 0x100 */
2162         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
2163                 if ((hkeyv >> 8) != 1) {
2164                         printk(TPACPI_ERR "unknown version of the "
2165                                "HKEY interface: 0x%x\n", hkeyv);
2166                         printk(TPACPI_ERR "please report this to %s\n",
2167                                TPACPI_MAIL);
2168                 } else {
2169                         /*
2170                          * MHKV 0x100 in A31, R40, R40e,
2171                          * T4x, X31, and later
2172                          */
2173                         tp_features.hotkey_mask = 1;
2174                 }
2175         }
2176
2177         vdbg_printk(TPACPI_DBG_INIT, "hotkey masks are %s\n",
2178                 str_supported(tp_features.hotkey_mask));
2179
2180         if (tp_features.hotkey_mask) {
2181                 if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
2182                                 "MHKA", "qd")) {
2183                         printk(TPACPI_ERR
2184                                "missing MHKA handler, "
2185                                "please report this to %s\n",
2186                                TPACPI_MAIL);
2187                         /* FN+F12, FN+F4, FN+F3 */
2188                         hotkey_all_mask = 0x080cU;
2189                 }
2190         }
2191
2192         /* hotkey_source_mask *must* be zero for
2193          * the first hotkey_mask_get */
2194         res = hotkey_status_get(&hotkey_orig_status);
2195         if (res)
2196                 goto err_exit;
2197
2198         if (tp_features.hotkey_mask) {
2199                 res = hotkey_mask_get();
2200                 if (res)
2201                         goto err_exit;
2202
2203                 hotkey_orig_mask = hotkey_mask;
2204                 res = add_many_to_attr_set(
2205                                 hotkey_dev_attributes,
2206                                 hotkey_mask_attributes,
2207                                 ARRAY_SIZE(hotkey_mask_attributes));
2208                 if (res)
2209                         goto err_exit;
2210         }
2211
2212 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2213         if (tp_features.hotkey_mask) {
2214                 hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
2215                                         & ~hotkey_all_mask;
2216         } else {
2217                 hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK;
2218         }
2219
2220         vdbg_printk(TPACPI_DBG_INIT,
2221                     "hotkey source mask 0x%08x, polling freq %d\n",
2222                     hotkey_source_mask, hotkey_poll_freq);
2223 #endif
2224
2225         /* Not all thinkpads have a hardware radio switch */
2226         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
2227                 tp_features.hotkey_wlsw = 1;
2228                 printk(TPACPI_INFO
2229                         "radio switch found; radios are %s\n",
2230                         enabled(status, 0));
2231         }
2232         if (tp_features.hotkey_wlsw)
2233                 res = add_to_attr_set(hotkey_dev_attributes,
2234                                 &dev_attr_hotkey_radio_sw.attr);
2235
2236         /* For X41t, X60t, X61t Tablets... */
2237         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
2238                 tp_features.hotkey_tablet = 1;
2239                 printk(TPACPI_INFO
2240                         "possible tablet mode switch found; "
2241                         "ThinkPad in %s mode\n",
2242                         (status & TP_HOTKEY_TABLET_MASK)?
2243                                 "tablet" : "laptop");
2244                 res = add_to_attr_set(hotkey_dev_attributes,
2245                                 &dev_attr_hotkey_tablet_mode.attr);
2246         }
2247
2248         if (!res)
2249                 res = register_attr_set_with_sysfs(
2250                                 hotkey_dev_attributes,
2251                                 &tpacpi_pdev->dev.kobj);
2252         if (res)
2253                 goto err_exit;
2254
2255         /* Set up key map */
2256
2257         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
2258                                         GFP_KERNEL);
2259         if (!hotkey_keycode_map) {
2260                 printk(TPACPI_ERR
2261                         "failed to allocate memory for key map\n");
2262                 res = -ENOMEM;
2263                 goto err_exit;
2264         }
2265
2266         if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
2267                 dbg_printk(TPACPI_DBG_INIT,
2268                            "using Lenovo default hot key map\n");
2269                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
2270                         TPACPI_HOTKEY_MAP_SIZE);
2271         } else {
2272                 dbg_printk(TPACPI_DBG_INIT,
2273                            "using IBM default hot key map\n");
2274                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
2275                         TPACPI_HOTKEY_MAP_SIZE);
2276         }
2277
2278         set_bit(EV_KEY, tpacpi_inputdev->evbit);
2279         set_bit(EV_MSC, tpacpi_inputdev->evbit);
2280         set_bit(MSC_SCAN, tpacpi_inputdev->mscbit);
2281         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
2282         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
2283         tpacpi_inputdev->keycode = hotkey_keycode_map;
2284         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
2285                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
2286                         set_bit(hotkey_keycode_map[i],
2287                                 tpacpi_inputdev->keybit);
2288                 } else {
2289                         if (i < sizeof(hotkey_reserved_mask)*8)
2290                                 hotkey_reserved_mask |= 1 << i;
2291                 }
2292         }
2293
2294         if (tp_features.hotkey_wlsw) {
2295                 set_bit(EV_SW, tpacpi_inputdev->evbit);
2296                 set_bit(SW_RFKILL_ALL, tpacpi_inputdev->swbit);
2297         }
2298         if (tp_features.hotkey_tablet) {
2299                 set_bit(EV_SW, tpacpi_inputdev->evbit);
2300                 set_bit(SW_TABLET_MODE, tpacpi_inputdev->swbit);
2301         }
2302
2303         /* Do not issue duplicate brightness change events to
2304          * userspace */
2305         if (!tp_features.bright_acpimode)
2306                 /* update bright_acpimode... */
2307                 tpacpi_check_std_acpi_brightness_support();
2308
2309         if (tp_features.bright_acpimode) {
2310                 printk(TPACPI_INFO
2311                        "This ThinkPad has standard ACPI backlight "
2312                        "brightness control, supported by the ACPI "
2313                        "video driver\n");
2314                 printk(TPACPI_NOTICE
2315                        "Disabling thinkpad-acpi brightness events "
2316                        "by default...\n");
2317
2318                 /* The hotkey_reserved_mask change below is not
2319                  * necessary while the keys are at KEY_RESERVED in the
2320                  * default map, but better safe than sorry, leave it
2321                  * here as a marker of what we have to do, especially
2322                  * when we finally become able to set this at runtime
2323                  * on response to X.org requests */
2324                 hotkey_reserved_mask |=
2325                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
2326                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
2327         }
2328
2329         dbg_printk(TPACPI_DBG_INIT, "enabling hot key handling\n");
2330         res = hotkey_status_set(1);
2331         if (res) {
2332                 hotkey_exit();
2333                 return res;
2334         }
2335         res = hotkey_mask_set(((hotkey_all_mask | hotkey_source_mask)
2336                                 & ~hotkey_reserved_mask)
2337                                 | hotkey_orig_mask);
2338         if (res < 0 && res != -ENXIO) {
2339                 hotkey_exit();
2340                 return res;
2341         }
2342
2343         dbg_printk(TPACPI_DBG_INIT,
2344                         "legacy hot key reporting over procfs %s\n",
2345                         (hotkey_report_mode < 2) ?
2346                                 "enabled" : "disabled");
2347
2348         tpacpi_inputdev->open = &hotkey_inputdev_open;
2349         tpacpi_inputdev->close = &hotkey_inputdev_close;
2350
2351         hotkey_poll_setup_safe(1);
2352         tpacpi_send_radiosw_update();
2353         tpacpi_input_send_tabletsw();
2354
2355         return 0;
2356
2357 err_exit:
2358         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
2359         hotkey_dev_attributes = NULL;
2360
2361         return (res < 0)? res : 1;
2362 }
2363
2364 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
2365 {
2366         u32 hkey;
2367         unsigned int scancode;
2368         int send_acpi_ev;
2369         int ignore_acpi_ev;
2370         int unk_ev;
2371
2372         if (event != 0x80) {
2373                 printk(TPACPI_ERR
2374                        "unknown HKEY notification event %d\n", event);
2375                 /* forward it to userspace, maybe it knows how to handle it */
2376                 acpi_bus_generate_netlink_event(
2377                                         ibm->acpi->device->pnp.device_class,
2378                                         ibm->acpi->device->dev.bus_id,
2379                                         event, 0);
2380                 return;
2381         }
2382
2383         while (1) {
2384                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
2385                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
2386                         return;
2387                 }
2388
2389                 if (hkey == 0) {
2390                         /* queue empty */
2391                         return;
2392                 }
2393
2394                 send_acpi_ev = 1;
2395                 ignore_acpi_ev = 0;
2396                 unk_ev = 0;
2397
2398                 switch (hkey >> 12) {
2399                 case 1:
2400                         /* 0x1000-0x1FFF: key presses */
2401                         scancode = hkey & 0xfff;
2402                         if (scancode > 0 && scancode < 0x21) {
2403                                 scancode--;
2404                                 if (!(hotkey_source_mask & (1 << scancode))) {
2405                                         tpacpi_input_send_key(scancode);
2406                                         send_acpi_ev = 0;
2407                                 } else {
2408                                         ignore_acpi_ev = 1;
2409                                 }
2410                         } else {
2411                                 unk_ev = 1;
2412                         }
2413                         break;
2414                 case 2:
2415                         /* Wakeup reason */
2416                         switch (hkey) {
2417                         case 0x2304: /* suspend, undock */
2418                         case 0x2404: /* hibernation, undock */
2419                                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
2420                                 ignore_acpi_ev = 1;
2421                                 break;
2422                         case 0x2305: /* suspend, bay eject */
2423                         case 0x2405: /* hibernation, bay eject */
2424                                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
2425                                 ignore_acpi_ev = 1;
2426                                 break;
2427                         default:
2428                                 unk_ev = 1;
2429                         }
2430                         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
2431                                 printk(TPACPI_INFO
2432                                        "woke up due to a hot-unplug "
2433                                        "request...\n");
2434                                 hotkey_wakeup_reason_notify_change();
2435                         }
2436                         break;
2437                 case 3:
2438                         /* bay-related wakeups */
2439                         if (hkey == 0x3003) {
2440                                 hotkey_autosleep_ack = 1;
2441                                 printk(TPACPI_INFO
2442                                        "bay ejected\n");
2443                                 hotkey_wakeup_hotunplug_complete_notify_change();
2444                         } else {
2445                                 unk_ev = 1;
2446                         }
2447                         break;
2448                 case 4:
2449                         /* dock-related wakeups */
2450                         if (hkey == 0x4003) {
2451                                 hotkey_autosleep_ack = 1;
2452                                 printk(TPACPI_INFO
2453                                        "undocked\n");
2454                                 hotkey_wakeup_hotunplug_complete_notify_change();
2455                         } else {
2456                                 unk_ev = 1;
2457                         }
2458                         break;
2459                 case 5:
2460                         /* 0x5000-0x5FFF: human interface helpers */
2461                         switch (hkey) {
2462                         case 0x5010: /* Lenovo new BIOS: brightness changed */
2463                         case 0x500b: /* X61t: tablet pen inserted into bay */
2464                         case 0x500c: /* X61t: tablet pen removed from bay */
2465                                 break;
2466                         case 0x5009: /* X41t-X61t: swivel up (tablet mode) */
2467                         case 0x500a: /* X41t-X61t: swivel down (normal mode) */
2468                                 tpacpi_input_send_tabletsw();
2469                                 hotkey_tablet_mode_notify_change();
2470                                 send_acpi_ev = 0;
2471                                 break;
2472                         case 0x5001:
2473                         case 0x5002:
2474                                 /* LID switch events.  Do not propagate */
2475                                 ignore_acpi_ev = 1;
2476                                 break;
2477                         default:
2478                                 unk_ev = 1;
2479                         }
2480                         break;
2481                 case 7:
2482                         /* 0x7000-0x7FFF: misc */
2483                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
2484                                 tpacpi_send_radiosw_update();
2485                                 send_acpi_ev = 0;
2486                                 break;
2487                         }
2488                         /* fallthrough to default */
2489                 default:
2490                         unk_ev = 1;
2491                 }
2492                 if (unk_ev) {
2493                         printk(TPACPI_NOTICE
2494                                "unhandled HKEY event 0x%04x\n", hkey);
2495                 }
2496
2497                 /* Legacy events */
2498                 if (!ignore_acpi_ev &&
2499                     (send_acpi_ev || hotkey_report_mode < 2)) {
2500                         acpi_bus_generate_proc_event(ibm->acpi->device,
2501                                                      event, hkey);
2502                 }
2503
2504                 /* netlink events */
2505                 if (!ignore_acpi_ev && send_acpi_ev) {
2506                         acpi_bus_generate_netlink_event(
2507                                         ibm->acpi->device->pnp.device_class,
2508                                         ibm->acpi->device->dev.bus_id,
2509                                         event, hkey);
2510                 }
2511         }
2512 }
2513
2514 static void hotkey_suspend(pm_message_t state)
2515 {
2516         /* Do these on suspend, we get the events on early resume! */
2517         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
2518         hotkey_autosleep_ack = 0;
2519 }
2520
2521 static void hotkey_resume(void)
2522 {
2523         tpacpi_disable_brightness_delay();
2524
2525         if (hotkey_mask_get())
2526                 printk(TPACPI_ERR
2527                        "error while trying to read hot key mask "
2528                        "from firmware\n");
2529         tpacpi_send_radiosw_update();
2530         hotkey_tablet_mode_notify_change();
2531         hotkey_wakeup_reason_notify_change();
2532         hotkey_wakeup_hotunplug_complete_notify_change();
2533         hotkey_poll_setup_safe(0);
2534 }
2535
2536 /* procfs -------------------------------------------------------------- */
2537 static int hotkey_read(char *p)
2538 {
2539         int res, status;
2540         int len = 0;
2541
2542         if (!tp_features.hotkey) {
2543                 len += sprintf(p + len, "status:\t\tnot supported\n");
2544                 return len;
2545         }
2546
2547         if (mutex_lock_interruptible(&hotkey_mutex))
2548                 return -ERESTARTSYS;
2549         res = hotkey_status_get(&status);
2550         if (!res)
2551                 res = hotkey_mask_get();
2552         mutex_unlock(&hotkey_mutex);
2553         if (res)
2554                 return res;
2555
2556         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
2557         if (tp_features.hotkey_mask) {
2558                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_mask);
2559                 len += sprintf(p + len,
2560                                "commands:\tenable, disable, reset, <mask>\n");
2561         } else {
2562                 len += sprintf(p + len, "mask:\t\tnot supported\n");
2563                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
2564         }
2565
2566         return len;
2567 }
2568
2569 static int hotkey_write(char *buf)
2570 {
2571         int res, status;
2572         u32 mask;
2573         char *cmd;
2574
2575         if (!tp_features.hotkey)
2576                 return -ENODEV;
2577
2578         if (mutex_lock_interruptible(&hotkey_mutex))
2579                 return -ERESTARTSYS;
2580
2581         status = -1;
2582         mask = hotkey_mask;
2583
2584         res = 0;
2585         while ((cmd = next_cmd(&buf))) {
2586                 if (strlencmp(cmd, "enable") == 0) {
2587                         status = 1;
2588                 } else if (strlencmp(cmd, "disable") == 0) {
2589                         status = 0;
2590                 } else if (strlencmp(cmd, "reset") == 0) {
2591                         status = hotkey_orig_status;
2592                         mask = hotkey_orig_mask;
2593                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
2594                         /* mask set */
2595                 } else if (sscanf(cmd, "%x", &mask) == 1) {
2596                         /* mask set */
2597                 } else {
2598                         res = -EINVAL;
2599                         goto errexit;
2600                 }
2601         }
2602         if (status != -1)
2603                 res = hotkey_status_set(status);
2604
2605         if (!res && mask != hotkey_mask)
2606                 res = hotkey_mask_set(mask);
2607
2608 errexit:
2609         mutex_unlock(&hotkey_mutex);
2610         return res;
2611 }
2612
2613 static const struct acpi_device_id ibm_htk_device_ids[] = {
2614         {TPACPI_ACPI_HKEY_HID, 0},
2615         {"", 0},
2616 };
2617
2618 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
2619         .hid = ibm_htk_device_ids,
2620         .notify = hotkey_notify,
2621         .handle = &hkey_handle,
2622         .type = ACPI_DEVICE_NOTIFY,
2623 };
2624
2625 static struct ibm_struct hotkey_driver_data = {
2626         .name = "hotkey",
2627         .read = hotkey_read,
2628         .write = hotkey_write,
2629         .exit = hotkey_exit,
2630         .resume = hotkey_resume,
2631         .suspend = hotkey_suspend,
2632         .acpi = &ibm_hotkey_acpidriver,
2633 };
2634
2635 /*************************************************************************
2636  * Bluetooth subdriver
2637  */
2638
2639 enum {
2640         /* ACPI GBDC/SBDC bits */
2641         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
2642         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
2643         TP_ACPI_BLUETOOTH_UNK           = 0x04, /* unknown function */
2644 };
2645
2646 static struct rfkill *tpacpi_bluetooth_rfkill;
2647
2648 static int bluetooth_get_radiosw(void)
2649 {
2650         int status;
2651
2652         if (!tp_features.bluetooth)
2653                 return -ENODEV;
2654
2655         /* WLSW overrides bluetooth in firmware/hardware, reflect that */
2656         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status)
2657                 return RFKILL_STATE_HARD_BLOCKED;
2658
2659         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
2660                 return -EIO;
2661
2662         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
2663                 RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
2664 }
2665
2666 static void bluetooth_update_rfk(void)
2667 {
2668         int status;
2669
2670         if (!tpacpi_bluetooth_rfkill)
2671                 return;
2672
2673         status = bluetooth_get_radiosw();
2674         if (status < 0)
2675                 return;
2676         rfkill_force_state(tpacpi_bluetooth_rfkill, status);
2677 }
2678
2679 static int bluetooth_set_radiosw(int radio_on, int update_rfk)
2680 {
2681         int status;
2682
2683         if (!tp_features.bluetooth)
2684                 return -ENODEV;
2685
2686         /* WLSW overrides bluetooth in firmware/hardware, but there is no
2687          * reason to risk weird behaviour. */
2688         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status
2689             && radio_on)
2690                 return -EPERM;
2691
2692         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
2693                 return -EIO;
2694         if (radio_on)
2695                 status |= TP_ACPI_BLUETOOTH_RADIOSSW;
2696         else
2697                 status &= ~TP_ACPI_BLUETOOTH_RADIOSSW;
2698         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
2699                 return -EIO;
2700
2701         if (update_rfk)
2702                 bluetooth_update_rfk();
2703
2704         return 0;
2705 }
2706
2707 /* sysfs bluetooth enable ---------------------------------------------- */
2708 static ssize_t bluetooth_enable_show(struct device *dev,
2709                            struct device_attribute *attr,
2710                            char *buf)
2711 {
2712         int status;
2713
2714         status = bluetooth_get_radiosw();
2715         if (status < 0)
2716                 return status;
2717
2718         return snprintf(buf, PAGE_SIZE, "%d\n",
2719                         (status == RFKILL_STATE_UNBLOCKED) ? 1 : 0);
2720 }
2721
2722 static ssize_t bluetooth_enable_store(struct device *dev,
2723                             struct device_attribute *attr,
2724                             const char *buf, size_t count)
2725 {
2726         unsigned long t;
2727         int res;
2728
2729         if (parse_strtoul(buf, 1, &t))
2730                 return -EINVAL;
2731
2732         res = bluetooth_set_radiosw(t, 1);
2733
2734         return (res) ? res : count;
2735 }
2736
2737 static struct device_attribute dev_attr_bluetooth_enable =
2738         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
2739                 bluetooth_enable_show, bluetooth_enable_store);
2740
2741 /* --------------------------------------------------------------------- */
2742
2743 static struct attribute *bluetooth_attributes[] = {
2744         &dev_attr_bluetooth_enable.attr,
2745         NULL
2746 };
2747
2748 static const struct attribute_group bluetooth_attr_group = {
2749         .attrs = bluetooth_attributes,
2750 };
2751
2752 static int tpacpi_bluetooth_rfk_get(void *data, enum rfkill_state *state)
2753 {
2754         int bts = bluetooth_get_radiosw();
2755
2756         if (bts < 0)
2757                 return bts;
2758
2759         *state = bts;
2760         return 0;
2761 }
2762
2763 static int tpacpi_bluetooth_rfk_set(void *data, enum rfkill_state state)
2764 {
2765         return bluetooth_set_radiosw((state == RFKILL_STATE_UNBLOCKED), 0);
2766 }
2767
2768 static void bluetooth_exit(void)
2769 {
2770         if (tpacpi_bluetooth_rfkill)
2771                 rfkill_unregister(tpacpi_bluetooth_rfkill);
2772
2773         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
2774                         &bluetooth_attr_group);
2775 }
2776
2777 static int __init bluetooth_init(struct ibm_init_struct *iibm)
2778 {
2779         int res;
2780         int status = 0;
2781
2782         vdbg_printk(TPACPI_DBG_INIT, "initializing bluetooth subdriver\n");
2783
2784         TPACPI_ACPIHANDLE_INIT(hkey);
2785
2786         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
2787            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
2788         tp_features.bluetooth = hkey_handle &&
2789             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
2790
2791         vdbg_printk(TPACPI_DBG_INIT, "bluetooth is %s, status 0x%02x\n",
2792                 str_supported(tp_features.bluetooth),
2793                 status);
2794
2795         if (tp_features.bluetooth &&
2796             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
2797                 /* no bluetooth hardware present in system */
2798                 tp_features.bluetooth = 0;
2799                 dbg_printk(TPACPI_DBG_INIT,
2800                            "bluetooth hardware not installed\n");
2801         }
2802
2803         if (!tp_features.bluetooth)
2804                 return 1;
2805
2806         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
2807                                 &bluetooth_attr_group);
2808         if (res)
2809                 return res;
2810
2811         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
2812                                 &tpacpi_bluetooth_rfkill,
2813                                 RFKILL_TYPE_BLUETOOTH,
2814                                 "tpacpi_bluetooth_sw",
2815                                 tpacpi_bluetooth_rfk_set,
2816                                 tpacpi_bluetooth_rfk_get);
2817         if (res) {
2818                 bluetooth_exit();
2819                 return res;
2820         }
2821
2822         return 0;
2823 }
2824
2825 /* procfs -------------------------------------------------------------- */
2826 static int bluetooth_read(char *p)
2827 {
2828         int len = 0;
2829         int status = bluetooth_get_radiosw();
2830
2831         if (!tp_features.bluetooth)
2832                 len += sprintf(p + len, "status:\t\tnot supported\n");
2833         else {
2834                 len += sprintf(p + len, "status:\t\t%s\n",
2835                                 (status == RFKILL_STATE_UNBLOCKED) ?
2836                                         "enabled" : "disabled");
2837                 len += sprintf(p + len, "commands:\tenable, disable\n");
2838         }
2839
2840         return len;
2841 }
2842
2843 static int bluetooth_write(char *buf)
2844 {
2845         char *cmd;
2846
2847         if (!tp_features.bluetooth)
2848                 return -ENODEV;
2849
2850         while ((cmd = next_cmd(&buf))) {
2851                 if (strlencmp(cmd, "enable") == 0) {
2852                         bluetooth_set_radiosw(1, 1);
2853                 } else if (strlencmp(cmd, "disable") == 0) {
2854                         bluetooth_set_radiosw(0, 1);
2855                 } else
2856                         return -EINVAL;
2857         }
2858
2859         return 0;
2860 }
2861
2862 static struct ibm_struct bluetooth_driver_data = {
2863         .name = "bluetooth",
2864         .read = bluetooth_read,
2865         .write = bluetooth_write,
2866         .exit = bluetooth_exit,
2867 };
2868
2869 /*************************************************************************
2870  * Wan subdriver
2871  */
2872
2873 enum {
2874         /* ACPI GWAN/SWAN bits */
2875         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
2876         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
2877         TP_ACPI_WANCARD_UNK             = 0x04, /* unknown function */
2878 };
2879
2880 static struct rfkill *tpacpi_wan_rfkill;
2881
2882 static int wan_get_radiosw(void)
2883 {
2884         int status;
2885
2886         if (!tp_features.wan)
2887                 return -ENODEV;
2888
2889         /* WLSW overrides WWAN in firmware/hardware, reflect that */
2890         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status)
2891                 return RFKILL_STATE_HARD_BLOCKED;
2892
2893         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
2894                 return -EIO;
2895
2896         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
2897                 RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
2898 }
2899
2900 static void wan_update_rfk(void)
2901 {
2902         int status;
2903
2904         if (!tpacpi_wan_rfkill)
2905                 return;
2906
2907         status = wan_get_radiosw();
2908         if (status < 0)
2909                 return;
2910         rfkill_force_state(tpacpi_wan_rfkill, status);
2911 }
2912
2913 static int wan_set_radiosw(int radio_on, int update_rfk)
2914 {
2915         int status;
2916
2917         if (!tp_features.wan)
2918                 return -ENODEV;
2919
2920         /* WLSW overrides bluetooth in firmware/hardware, but there is no
2921          * reason to risk weird behaviour. */
2922         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status
2923             && radio_on)
2924                 return -EPERM;
2925
2926         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
2927                 return -EIO;
2928         if (radio_on)
2929                 status |= TP_ACPI_WANCARD_RADIOSSW;
2930         else
2931                 status &= ~TP_ACPI_WANCARD_RADIOSSW;
2932         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
2933                 return -EIO;
2934
2935         if (update_rfk)
2936                 wan_update_rfk();
2937
2938         return 0;
2939 }
2940
2941 /* sysfs wan enable ---------------------------------------------------- */
2942 static ssize_t wan_enable_show(struct device *dev,
2943                            struct device_attribute *attr,
2944                            char *buf)
2945 {
2946         int status;
2947
2948         status = wan_get_radiosw();
2949         if (status < 0)
2950                 return status;
2951
2952         return snprintf(buf, PAGE_SIZE, "%d\n",
2953                         (status == RFKILL_STATE_UNBLOCKED) ? 1 : 0);
2954 }
2955
2956 static ssize_t wan_enable_store(struct device *dev,
2957                             struct device_attribute *attr,
2958                             const char *buf, size_t count)
2959 {
2960         unsigned long t;
2961         int res;
2962
2963         if (parse_strtoul(buf, 1, &t))
2964                 return -EINVAL;
2965
2966         res = wan_set_radiosw(t, 1);
2967
2968         return (res) ? res : count;
2969 }
2970
2971 static struct device_attribute dev_attr_wan_enable =
2972         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
2973                 wan_enable_show, wan_enable_store);
2974
2975 /* --------------------------------------------------------------------- */
2976
2977 static struct attribute *wan_attributes[] = {
2978         &dev_attr_wan_enable.attr,
2979         NULL
2980 };
2981
2982 static const struct attribute_group wan_attr_group = {
2983         .attrs = wan_attributes,
2984 };
2985
2986 static int tpacpi_wan_rfk_get(void *data, enum rfkill_state *state)
2987 {
2988         int wans = wan_get_radiosw();
2989
2990         if (wans < 0)
2991                 return wans;
2992
2993         *state = wans;
2994         return 0;
2995 }
2996
2997 static int tpacpi_wan_rfk_set(void *data, enum rfkill_state state)
2998 {
2999         return wan_set_radiosw((state == RFKILL_STATE_UNBLOCKED), 0);
3000 }
3001
3002 static void wan_exit(void)
3003 {
3004         if (tpacpi_wan_rfkill)
3005                 rfkill_unregister(tpacpi_wan_rfkill);
3006
3007         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3008                 &wan_attr_group);
3009 }
3010
3011 static int __init wan_init(struct ibm_init_struct *iibm)
3012 {
3013         int res;
3014         int status = 0;
3015
3016         vdbg_printk(TPACPI_DBG_INIT, "initializing wan subdriver\n");
3017
3018         TPACPI_ACPIHANDLE_INIT(hkey);
3019
3020         tp_features.wan = hkey_handle &&
3021             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
3022
3023         vdbg_printk(TPACPI_DBG_INIT, "wan is %s, status 0x%02x\n",
3024                 str_supported(tp_features.wan),
3025                 status);
3026
3027         if (tp_features.wan &&
3028             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
3029                 /* no wan hardware present in system */
3030                 tp_features.wan = 0;
3031                 dbg_printk(TPACPI_DBG_INIT,
3032                            "wan hardware not installed\n");
3033         }
3034
3035         if (!tp_features.wan)
3036                 return 1;
3037
3038         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3039                                 &wan_attr_group);
3040         if (res)
3041                 return res;
3042
3043         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
3044                                 &tpacpi_wan_rfkill,
3045                                 RFKILL_TYPE_WWAN,
3046                                 "tpacpi_wwan_sw",
3047                                 tpacpi_wan_rfk_set,
3048                                 tpacpi_wan_rfk_get);
3049         if (res) {
3050                 wan_exit();
3051                 return res;
3052         }
3053
3054         return 0;
3055 }
3056
3057 /* procfs -------------------------------------------------------------- */
3058 static int wan_read(char *p)
3059 {
3060         int len = 0;
3061         int status = wan_get_radiosw();
3062
3063         if (!tp_features.wan)
3064                 len += sprintf(p + len, "status:\t\tnot supported\n");
3065         else {
3066                 len += sprintf(p + len, "status:\t\t%s\n",
3067                                 (status == RFKILL_STATE_UNBLOCKED) ?
3068                                         "enabled" : "disabled");
3069                 len += sprintf(p + len, "commands:\tenable, disable\n");
3070         }
3071
3072         return len;
3073 }
3074
3075 static int wan_write(char *buf)
3076 {
3077         char *cmd;
3078
3079         if (!tp_features.wan)
3080                 return -ENODEV;
3081
3082         while ((cmd = next_cmd(&buf))) {
3083                 if (strlencmp(cmd, "enable") == 0) {
3084                         wan_set_radiosw(1, 1);
3085                 } else if (strlencmp(cmd, "disable") == 0) {
3086                         wan_set_radiosw(0, 1);
3087                 } else
3088                         return -EINVAL;
3089         }
3090
3091         return 0;
3092 }
3093
3094 static struct ibm_struct wan_driver_data = {
3095         .name = "wan",
3096         .read = wan_read,
3097         .write = wan_write,
3098         .exit = wan_exit,
3099 };
3100
3101 /*************************************************************************
3102  * Video subdriver
3103  */
3104
3105 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
3106
3107 enum video_access_mode {
3108         TPACPI_VIDEO_NONE = 0,
3109         TPACPI_VIDEO_570,       /* 570 */
3110         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
3111         TPACPI_VIDEO_NEW,       /* all others */
3112 };
3113
3114 enum {  /* video status flags, based on VIDEO_570 */
3115         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
3116         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
3117         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
3118 };
3119
3120 enum {  /* TPACPI_VIDEO_570 constants */
3121         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
3122         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
3123                                                  * video_status_flags */
3124         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
3125         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
3126 };
3127
3128 static enum video_access_mode video_supported;
3129 static int video_orig_autosw;
3130
3131 static int video_autosw_get(void);
3132 static int video_autosw_set(int enable);
3133
3134 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
3135
3136 static int __init video_init(struct ibm_init_struct *iibm)
3137 {
3138         int ivga;
3139
3140         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
3141
3142         TPACPI_ACPIHANDLE_INIT(vid);
3143         TPACPI_ACPIHANDLE_INIT(vid2);
3144
3145         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
3146                 /* G41, assume IVGA doesn't change */
3147                 vid_handle = vid2_handle;
3148
3149         if (!vid_handle)
3150                 /* video switching not supported on R30, R31 */
3151                 video_supported = TPACPI_VIDEO_NONE;
3152         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
3153                 /* 570 */
3154                 video_supported = TPACPI_VIDEO_570;
3155         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
3156                 /* 600e/x, 770e, 770x */
3157                 video_supported = TPACPI_VIDEO_770;
3158         else
3159                 /* all others */
3160                 video_supported = TPACPI_VIDEO_NEW;
3161
3162         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
3163                 str_supported(video_supported != TPACPI_VIDEO_NONE),
3164                 video_supported);
3165
3166         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
3167 }
3168
3169 static void video_exit(void)
3170 {
3171         dbg_printk(TPACPI_DBG_EXIT,
3172                    "restoring original video autoswitch mode\n");
3173         if (video_autosw_set(video_orig_autosw))
3174                 printk(TPACPI_ERR "error while trying to restore original "
3175                         "video autoswitch mode\n");
3176 }
3177
3178 static int video_outputsw_get(void)
3179 {
3180         int status = 0;
3181         int i;
3182
3183         switch (video_supported) {
3184         case TPACPI_VIDEO_570:
3185                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
3186                                  TP_ACPI_VIDEO_570_PHSCMD))
3187                         return -EIO;
3188                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
3189                 break;
3190         case TPACPI_VIDEO_770:
3191                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
3192                         return -EIO;
3193                 if (i)
3194                         status |= TP_ACPI_VIDEO_S_LCD;
3195                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
3196                         return -EIO;
3197                 if (i)
3198                         status |= TP_ACPI_VIDEO_S_CRT;
3199                 break;
3200         case TPACPI_VIDEO_NEW:
3201                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
3202                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
3203                         return -EIO;
3204                 if (i)
3205                         status |= TP_ACPI_VIDEO_S_CRT;
3206
3207                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
3208                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
3209                         return -EIO;
3210                 if (i)
3211                         status |= TP_ACPI_VIDEO_S_LCD;
3212                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
3213                         return -EIO;
3214                 if (i)
3215                         status |= TP_ACPI_VIDEO_S_DVI;
3216                 break;
3217         default:
3218                 return -ENOSYS;
3219         }
3220
3221         return status;
3222 }
3223
3224 static int video_outputsw_set(int status)
3225 {
3226         int autosw;
3227         int res = 0;
3228
3229         switch (video_supported) {
3230         case TPACPI_VIDEO_570:
3231                 res = acpi_evalf(NULL, NULL,
3232                                  "\\_SB.PHS2", "vdd",
3233                                  TP_ACPI_VIDEO_570_PHS2CMD,
3234                                  status | TP_ACPI_VIDEO_570_PHS2SET);
3235                 break;
3236         case TPACPI_VIDEO_770:
3237                 autosw = video_autosw_get();
3238                 if (autosw < 0)
3239                         return autosw;
3240
3241                 res = video_autosw_set(1);
3242                 if (res)
3243                         return res;
3244                 res = acpi_evalf(vid_handle, NULL,
3245                                  "ASWT", "vdd", status * 0x100, 0);
3246                 if (!autosw && video_autosw_set(autosw)) {
3247                         printk(TPACPI_ERR
3248                                "video auto-switch left enabled due to error\n");
3249                         return -EIO;
3250                 }
3251                 break;
3252         case TPACPI_VIDEO_NEW:
3253                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
3254                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
3255                 break;
3256         default:
3257                 return -ENOSYS;
3258         }
3259
3260         return (res)? 0 : -EIO;
3261 }
3262
3263 static int video_autosw_get(void)
3264 {
3265         int autosw = 0;
3266
3267         switch (video_supported) {
3268         case TPACPI_VIDEO_570:
3269                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
3270                         return -EIO;
3271                 break;
3272         case TPACPI_VIDEO_770:
3273         case TPACPI_VIDEO_NEW:
3274                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
3275                         return -EIO;
3276                 break;
3277         default:
3278                 return -ENOSYS;
3279         }
3280
3281         return autosw & 1;
3282 }
3283
3284 static int video_autosw_set(int enable)
3285 {
3286         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
3287                 return -EIO;
3288         return 0;
3289 }
3290
3291 static int video_outputsw_cycle(void)
3292 {
3293         int autosw = video_autosw_get();
3294         int res;
3295
3296         if (autosw < 0)
3297                 return autosw;
3298
3299         switch (video_supported) {
3300         case TPACPI_VIDEO_570:
3301                 res = video_autosw_set(1);
3302                 if (res)
3303                         return res;
3304                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
3305                 break;
3306         case TPACPI_VIDEO_770:
3307         case TPACPI_VIDEO_NEW:
3308                 res = video_autosw_set(1);
3309                 if (res)
3310                         return res;
3311                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
3312                 break;
3313         default:
3314                 return -ENOSYS;
3315         }
3316         if (!autosw && video_autosw_set(autosw)) {
3317                 printk(TPACPI_ERR
3318                        "video auto-switch left enabled due to error\n");
3319                 return -EIO;
3320         }
3321
3322         return (res)? 0 : -EIO;
3323 }
3324
3325 static int video_expand_toggle(void)
3326 {
3327         switch (video_supported) {
3328         case TPACPI_VIDEO_570:
3329                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
3330                         0 : -EIO;
3331         case TPACPI_VIDEO_770:
3332                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
3333                         0 : -EIO;
3334         case TPACPI_VIDEO_NEW:
3335                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
3336                         0 : -EIO;
3337         default:
3338                 return -ENOSYS;
3339         }
3340         /* not reached */
3341 }
3342
3343 static int video_read(char *p)
3344 {
3345         int status, autosw;
3346         int len = 0;
3347
3348         if (video_supported == TPACPI_VIDEO_NONE) {
3349                 len += sprintf(p + len, "status:\t\tnot supported\n");
3350                 return len;
3351         }
3352
3353         status = video_outputsw_get();
3354         if (status < 0)
3355                 return status;
3356
3357         autosw = video_autosw_get();
3358         if (autosw < 0)
3359                 return autosw;
3360
3361         len += sprintf(p + len, "status:\t\tsupported\n");
3362         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
3363         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
3364         if (video_supported == TPACPI_VIDEO_NEW)
3365                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
3366         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
3367         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
3368         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
3369         if (video_supported == TPACPI_VIDEO_NEW)
3370                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
3371         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
3372         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
3373
3374         return len;
3375 }
3376
3377 static int video_write(char *buf)
3378 {
3379         char *cmd;
3380         int enable, disable, status;
3381         int res;
3382
3383         if (video_supported == TPACPI_VIDEO_NONE)
3384                 return -ENODEV;
3385
3386         enable = 0;
3387         disable = 0;
3388
3389         while ((cmd = next_cmd(&buf))) {
3390                 if (strlencmp(cmd, "lcd_enable") == 0) {
3391                         enable |= TP_ACPI_VIDEO_S_LCD;
3392                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
3393                         disable |= TP_ACPI_VIDEO_S_LCD;
3394                 } else if (strlencmp(cmd, "crt_enable") == 0) {
3395                         enable |= TP_ACPI_VIDEO_S_CRT;
3396                 } else if (strlencmp(cmd, "crt_disable") == 0) {
3397                         disable |= TP_ACPI_VIDEO_S_CRT;
3398                 } else if (video_supported == TPACPI_VIDEO_NEW &&
3399                            strlencmp(cmd, "dvi_enable") == 0) {
3400                         enable |= TP_ACPI_VIDEO_S_DVI;
3401                 } else if (video_supported == TPACPI_VIDEO_NEW &&
3402                            strlencmp(cmd, "dvi_disable") == 0) {
3403                         disable |= TP_ACPI_VIDEO_S_DVI;
3404                 } else if (strlencmp(cmd, "auto_enable") == 0) {
3405                         res = video_autosw_set(1);
3406                         if (res)
3407                                 return res;
3408                 } else if (strlencmp(cmd, "auto_disable") == 0) {
3409                         res = video_autosw_set(0);
3410                         if (res)
3411                                 return res;
3412                 } else if (strlencmp(cmd, "video_switch") == 0) {
3413                         res = video_outputsw_cycle();
3414                         if (res)
3415                                 return res;
3416                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
3417                         res = video_expand_toggle();
3418                         if (res)
3419                                 return res;
3420                 } else
3421                         return -EINVAL;
3422         }
3423
3424         if (enable || disable) {
3425                 status = video_outputsw_get();
3426                 if (status < 0)
3427                         return status;
3428                 res = video_outputsw_set((status & ~disable) | enable);
3429                 if (res)
3430                         return res;
3431         }
3432
3433         return 0;
3434 }
3435
3436 static struct ibm_struct video_driver_data = {
3437         .name = "video",
3438         .read = video_read,
3439         .write = video_write,
3440         .exit = video_exit,
3441 };
3442
3443 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
3444
3445 /*************************************************************************
3446  * Light (thinklight) subdriver
3447  */
3448
3449 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
3450 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
3451
3452 static int light_get_status(void)
3453 {
3454         int status = 0;
3455
3456         if (tp_features.light_status) {
3457                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
3458                         return -EIO;
3459                 return (!!status);
3460         }
3461
3462         return -ENXIO;
3463 }
3464
3465 static int light_set_status(int status)
3466 {
3467         int rc;
3468
3469         if (tp_features.light) {
3470                 if (cmos_handle) {
3471                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
3472                                         (status)?
3473                                                 TP_CMOS_THINKLIGHT_ON :
3474                                                 TP_CMOS_THINKLIGHT_OFF);
3475                 } else {
3476                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
3477                                         (status)? 1 : 0);
3478                 }
3479                 return (rc)? 0 : -EIO;
3480         }
3481
3482         return -ENXIO;
3483 }
3484
3485 static void light_set_status_worker(struct work_struct *work)
3486 {
3487         struct tpacpi_led_classdev *data =
3488                         container_of(work, struct tpacpi_led_classdev, work);
3489
3490         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
3491                 light_set_status((data->new_brightness != LED_OFF));
3492 }
3493
3494 static void light_sysfs_set(struct led_classdev *led_cdev,
3495                         enum led_brightness brightness)
3496 {
3497         struct tpacpi_led_classdev *data =
3498                 container_of(led_cdev,
3499                              struct tpacpi_led_classdev,
3500                              led_classdev);
3501         data->new_brightness = brightness;
3502         queue_work(tpacpi_wq, &data->work);
3503 }
3504
3505 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
3506 {
3507         return (light_get_status() == 1)? LED_FULL : LED_OFF;
3508 }
3509
3510 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
3511         .led_classdev = {
3512                 .name           = "tpacpi::thinklight",
3513                 .brightness_set = &light_sysfs_set,
3514                 .brightness_get = &light_sysfs_get,
3515         }
3516 };
3517
3518 static int __init light_init(struct ibm_init_struct *iibm)
3519 {
3520         int rc;
3521
3522         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
3523
3524         TPACPI_ACPIHANDLE_INIT(ledb);
3525         TPACPI_ACPIHANDLE_INIT(lght);
3526         TPACPI_ACPIHANDLE_INIT(cmos);
3527         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
3528
3529         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
3530         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
3531
3532         if (tp_features.light)
3533                 /* light status not supported on
3534                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
3535                 tp_features.light_status =
3536                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
3537
3538         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
3539                 str_supported(tp_features.light),
3540                 str_supported(tp_features.light_status));
3541
3542         if (!tp_features.light)
3543                 return 1;
3544
3545         rc = led_classdev_register(&tpacpi_pdev->dev,
3546                                    &tpacpi_led_thinklight.led_classdev);
3547
3548         if (rc < 0) {
3549                 tp_features.light = 0;
3550                 tp_features.light_status = 0;
3551         } else  {
3552                 rc = 0;
3553         }
3554
3555         return rc;
3556 }
3557
3558 static void light_exit(void)
3559 {
3560         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
3561         if (work_pending(&tpacpi_led_thinklight.work))
3562                 flush_workqueue(tpacpi_wq);
3563 }
3564
3565 static int light_read(char *p)
3566 {
3567         int len = 0;
3568         int status;
3569
3570         if (!tp_features.light) {
3571                 len += sprintf(p + len, "status:\t\tnot supported\n");
3572         } else if (!tp_features.light_status) {
3573                 len += sprintf(p + len, "status:\t\tunknown\n");
3574                 len += sprintf(p + len, "commands:\ton, off\n");
3575         } else {
3576                 status = light_get_status();
3577                 if (status < 0)
3578                         return status;
3579                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
3580                 len += sprintf(p + len, "commands:\ton, off\n");
3581         }
3582
3583         return len;
3584 }
3585
3586 static int light_write(char *buf)
3587 {
3588         char *cmd;
3589         int newstatus = 0;
3590
3591         if (!tp_features.light)
3592                 return -ENODEV;
3593
3594         while ((cmd = next_cmd(&buf))) {
3595                 if (strlencmp(cmd, "on") == 0) {
3596                         newstatus = 1;
3597                 } else if (strlencmp(cmd, "off") == 0) {
3598                         newstatus = 0;
3599                 } else
3600                         return -EINVAL;
3601         }
3602
3603         return light_set_status(newstatus);
3604 }
3605
3606 static struct ibm_struct light_driver_data = {
3607         .name = "light",
3608         .read = light_read,
3609         .write = light_write,
3610         .exit = light_exit,
3611 };
3612
3613 /*************************************************************************
3614  * Dock subdriver
3615  */
3616
3617 #ifdef CONFIG_THINKPAD_ACPI_DOCK
3618
3619 static void dock_notify(struct ibm_struct *ibm, u32 event);
3620 static int dock_read(char *p);
3621 static int dock_write(char *buf);
3622
3623 TPACPI_HANDLE(dock, root, "\\_SB.GDCK", /* X30, X31, X40 */
3624            "\\_SB.PCI0.DOCK",   /* 600e/x,770e,770x,A2xm/p,T20-22,X20-21 */
3625            "\\_SB.PCI0.PCI1.DOCK",      /* all others */
3626            "\\_SB.PCI.ISA.SLCE",        /* 570 */
3627     );                          /* A21e,G4x,R30,R31,R32,R40,R40e,R50e */
3628
3629 /* don't list other alternatives as we install a notify handler on the 570 */
3630 TPACPI_HANDLE(pci, root, "\\_SB.PCI");  /* 570 */
3631
3632 static const struct acpi_device_id ibm_pci_device_ids[] = {
3633         {PCI_ROOT_HID_STRING, 0},
3634         {"", 0},
3635 };
3636
3637 static struct tp_acpi_drv_struct ibm_dock_acpidriver[2] = {
3638         {
3639          .notify = dock_notify,
3640          .handle = &dock_handle,
3641          .type = ACPI_SYSTEM_NOTIFY,
3642         },
3643         {
3644         /* THIS ONE MUST NEVER BE USED FOR DRIVER AUTOLOADING.
3645          * We just use it to get notifications of dock hotplug
3646          * in very old thinkpads */
3647          .hid = ibm_pci_device_ids,
3648          .notify = dock_notify,
3649          .handle = &pci_handle,
3650          .type = ACPI_SYSTEM_NOTIFY,
3651         },
3652 };
3653
3654 static struct ibm_struct dock_driver_data[2] = {
3655         {
3656          .name = "dock",
3657          .read = dock_read,
3658          .write = dock_write,
3659          .acpi = &ibm_dock_acpidriver[0],
3660         },
3661         {
3662          .name = "dock",
3663          .acpi = &ibm_dock_acpidriver[1],
3664         },
3665 };
3666
3667 #define dock_docked() (_sta(dock_handle) & 1)
3668
3669 static int __init dock_init(struct ibm_init_struct *iibm)
3670 {
3671         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver\n");
3672
3673         TPACPI_ACPIHANDLE_INIT(dock);
3674
3675         vdbg_printk(TPACPI_DBG_INIT, "dock is %s\n",
3676                 str_supported(dock_handle != NULL));
3677
3678         return (dock_handle)? 0 : 1;
3679 }
3680
3681 static int __init dock_init2(struct ibm_init_struct *iibm)
3682 {
3683         int dock2_needed;
3684
3685         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver part 2\n");
3686
3687         if (dock_driver_data[0].flags.acpi_driver_registered &&
3688             dock_driver_data[0].flags.acpi_notify_installed) {
3689                 TPACPI_ACPIHANDLE_INIT(pci);
3690                 dock2_needed = (pci_handle != NULL);
3691                 vdbg_printk(TPACPI_DBG_INIT,
3692                             "dock PCI handler for the TP 570 is %s\n",
3693                             str_supported(dock2_needed));
3694         } else {
3695                 vdbg_printk(TPACPI_DBG_INIT,
3696                 "dock subdriver part 2 not required\n");
3697                 dock2_needed = 0;
3698         }
3699
3700         return (dock2_needed)? 0 : 1;
3701 }
3702
3703 static void dock_notify(struct ibm_struct *ibm, u32 event)
3704 {
3705         int docked = dock_docked();
3706         int pci = ibm->acpi->hid && ibm->acpi->device &&
3707                 acpi_match_device_ids(ibm->acpi->device, ibm_pci_device_ids);
3708         int data;
3709
3710         if (event == 1 && !pci) /* 570 */
3711                 data = 1;       /* button */
3712         else if (event == 1 && pci)     /* 570 */
3713                 data = 3;       /* dock */
3714         else if (event == 3 && docked)
3715                 data = 1;       /* button */
3716         else if (event == 3 && !docked)
3717                 data = 2;       /* undock */
3718         else if (event == 0 && docked)
3719                 data = 3;       /* dock */
3720         else {
3721                 printk(TPACPI_ERR "unknown dock event %d, status %d\n",
3722                        event, _sta(dock_handle));
3723                 data = 0;       /* unknown */
3724         }
3725         acpi_bus_generate_proc_event(ibm->acpi->device, event, data);
3726         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
3727                                           ibm->acpi->device->dev.bus_id,
3728                                           event, data);
3729 }
3730
3731 static int dock_read(char *p)
3732 {
3733         int len = 0;
3734         int docked = dock_docked();
3735
3736         if (!dock_handle)
3737                 len += sprintf(p + len, "status:\t\tnot supported\n");
3738         else if (!docked)
3739                 len += sprintf(p + len, "status:\t\tundocked\n");
3740         else {
3741                 len += sprintf(p + len, "status:\t\tdocked\n");
3742                 len += sprintf(p + len, "commands:\tdock, undock\n");
3743         }
3744
3745         return len;
3746 }
3747
3748 static int dock_write(char *buf)
3749 {
3750         char *cmd;
3751
3752         if (!dock_docked())
3753                 return -ENODEV;
3754
3755         while ((cmd = next_cmd(&buf))) {
3756                 if (strlencmp(cmd, "undock") == 0) {
3757                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 0) ||
3758                             !acpi_evalf(dock_handle, NULL, "_EJ0", "vd", 1))
3759                                 return -EIO;
3760                 } else if (strlencmp(cmd, "dock") == 0) {
3761                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 1))
3762                                 return -EIO;
3763                 } else
3764                         return -EINVAL;
3765         }
3766
3767         return 0;
3768 }
3769
3770 #endif /* CONFIG_THINKPAD_ACPI_DOCK */
3771
3772 /*************************************************************************
3773  * Bay subdriver
3774  */
3775
3776 #ifdef CONFIG_THINKPAD_ACPI_BAY
3777
3778 TPACPI_HANDLE(bay, root, "\\_SB.PCI.IDE.SECN.MAST",     /* 570 */
3779            "\\_SB.PCI0.IDE0.IDES.IDSM", /* 600e/x, 770e, 770x */
3780            "\\_SB.PCI0.SATA.SCND.MSTR", /* T60, X60, Z60 */
3781            "\\_SB.PCI0.IDE0.SCND.MSTR", /* all others */
3782            );                           /* A21e, R30, R31 */
3783 TPACPI_HANDLE(bay_ej, bay, "_EJ3",      /* 600e/x, A2xm/p, A3x */
3784            "_EJ0",              /* all others */
3785            );                   /* 570,A21e,G4x,R30,R31,R32,R40e,R50e */
3786 TPACPI_HANDLE(bay2, root, "\\_SB.PCI0.IDE0.PRIM.SLAV",  /* A3x, R32 */
3787            "\\_SB.PCI0.IDE0.IDEP.IDPS", /* 600e/x, 770e, 770x */
3788            );                           /* all others */
3789 TPACPI_HANDLE(bay2_ej, bay2, "_EJ3",    /* 600e/x, 770e, A3x */
3790            "_EJ0",                      /* 770x */
3791            );                           /* all others */
3792
3793 static int __init bay_init(struct ibm_init_struct *iibm)
3794 {
3795         vdbg_printk(TPACPI_DBG_INIT, "initializing bay subdriver\n");
3796
3797         TPACPI_ACPIHANDLE_INIT(bay);
3798         if (bay_handle)
3799                 TPACPI_ACPIHANDLE_INIT(bay_ej);
3800         TPACPI_ACPIHANDLE_INIT(bay2);
3801         if (bay2_handle)
3802                 TPACPI_ACPIHANDLE_INIT(bay2_ej);
3803
3804         tp_features.bay_status = bay_handle &&
3805                 acpi_evalf(bay_handle, NULL, "_STA", "qv");
3806         tp_features.bay_status2 = bay2_handle &&
3807                 acpi_evalf(bay2_handle, NULL, "_STA", "qv");
3808
3809         tp_features.bay_eject = bay_handle && bay_ej_handle &&
3810                 (strlencmp(bay_ej_path, "_EJ0") == 0 || experimental);
3811         tp_features.bay_eject2 = bay2_handle && bay2_ej_handle &&
3812                 (strlencmp(bay2_ej_path, "_EJ0") == 0 || experimental);
3813
3814         vdbg_printk(TPACPI_DBG_INIT,
3815                 "bay 1: status %s, eject %s; bay 2: status %s, eject %s\n",
3816                 str_supported(tp_features.bay_status),
3817                 str_supported(tp_features.bay_eject),
3818                 str_supported(tp_features.bay_status2),
3819                 str_supported(tp_features.bay_eject2));
3820
3821         return (tp_features.bay_status || tp_features.bay_eject ||
3822                 tp_features.bay_status2 || tp_features.bay_eject2)? 0 : 1;
3823 }
3824
3825 static void bay_notify(struct ibm_struct *ibm, u32 event)
3826 {
3827         acpi_bus_generate_proc_event(ibm->acpi->device, event, 0);
3828         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
3829                                           ibm->acpi->device->dev.bus_id,
3830                                           event, 0);
3831 }
3832
3833 #define bay_occupied(b) (_sta(b##_handle) & 1)
3834
3835 static int bay_read(char *p)
3836 {
3837         int len = 0;
3838         int occupied = bay_occupied(bay);
3839         int occupied2 = bay_occupied(bay2);
3840         int eject, eject2;
3841
3842         len += sprintf(p + len, "status:\t\t%s\n",
3843                 tp_features.bay_status ?
3844                         (occupied ? "occupied" : "unoccupied") :
3845                                 "not supported");
3846         if (tp_features.bay_status2)
3847                 len += sprintf(p + len, "status2:\t%s\n", occupied2 ?
3848                                "occupied" : "unoccupied");
3849
3850         eject = tp_features.bay_eject && occupied;
3851         eject2 = tp_features.bay_eject2 && occupied2;
3852
3853         if (eject && eject2)
3854                 len += sprintf(p + len, "commands:\teject, eject2\n");
3855         else if (eject)
3856                 len += sprintf(p + len, "commands:\teject\n");
3857         else if (eject2)
3858                 len += sprintf(p + len, "commands:\teject2\n");
3859
3860         return len;
3861 }
3862
3863 static int bay_write(char *buf)
3864 {
3865         char *cmd;
3866
3867         if (!tp_features.bay_eject && !tp_features.bay_eject2)
3868                 return -ENODEV;
3869
3870         while ((cmd = next_cmd(&buf))) {
3871                 if (tp_features.bay_eject && strlencmp(cmd, "eject") == 0) {
3872                         if (!acpi_evalf(bay_ej_handle, NULL, NULL, "vd", 1))
3873                                 return -EIO;
3874                 } else if (tp_features.bay_eject2 &&
3875                            strlencmp(cmd, "eject2") == 0) {
3876                         if (!acpi_evalf(bay2_ej_handle, NULL, NULL, "vd", 1))
3877                                 return -EIO;
3878                 } else
3879                         return -EINVAL;
3880         }
3881
3882         return 0;
3883 }
3884
3885 static struct tp_acpi_drv_struct ibm_bay_acpidriver = {
3886         .notify = bay_notify,
3887         .handle = &bay_handle,
3888         .type = ACPI_SYSTEM_NOTIFY,
3889 };
3890
3891 static struct ibm_struct bay_driver_data = {
3892         .name = "bay",
3893         .read = bay_read,
3894         .write = bay_write,
3895         .acpi = &ibm_bay_acpidriver,
3896 };
3897
3898 #endif /* CONFIG_THINKPAD_ACPI_BAY */
3899
3900 /*************************************************************************
3901  * CMOS subdriver
3902  */
3903
3904 /* sysfs cmos_command -------------------------------------------------- */
3905 static ssize_t cmos_command_store(struct device *dev,
3906                             struct device_attribute *attr,
3907                             const char *buf, size_t count)
3908 {
3909         unsigned long cmos_cmd;
3910         int res;
3911
3912         if (parse_strtoul(buf, 21, &cmos_cmd))
3913                 return -EINVAL;
3914
3915         res = issue_thinkpad_cmos_command(cmos_cmd);
3916         return (res)? res : count;
3917 }
3918
3919 static struct device_attribute dev_attr_cmos_command =
3920         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
3921
3922 /* --------------------------------------------------------------------- */
3923
3924 static int __init cmos_init(struct ibm_init_struct *iibm)
3925 {
3926         int res;
3927
3928         vdbg_printk(TPACPI_DBG_INIT,
3929                 "initializing cmos commands subdriver\n");
3930
3931         TPACPI_ACPIHANDLE_INIT(cmos);
3932
3933         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
3934                 str_supported(cmos_handle != NULL));
3935
3936         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
3937         if (res)
3938                 return res;
3939
3940         return (cmos_handle)? 0 : 1;
3941 }
3942
3943 static void cmos_exit(void)
3944 {
3945         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
3946 }
3947
3948 static int cmos_read(char *p)
3949 {
3950         int len = 0;
3951
3952         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3953            R30, R31, T20-22, X20-21 */
3954         if (!cmos_handle)
3955                 len += sprintf(p + len, "status:\t\tnot supported\n");
3956         else {
3957                 len += sprintf(p + len, "status:\t\tsupported\n");
3958                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
3959         }
3960
3961         return len;
3962 }
3963
3964 static int cmos_write(char *buf)
3965 {
3966         char *cmd;
3967         int cmos_cmd, res;
3968
3969         while ((cmd = next_cmd(&buf))) {
3970                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
3971                     cmos_cmd >= 0 && cmos_cmd <= 21) {
3972                         /* cmos_cmd set */
3973                 } else
3974                         return -EINVAL;
3975
3976                 res = issue_thinkpad_cmos_command(cmos_cmd);
3977                 if (res)
3978                         return res;
3979         }
3980
3981         return 0;
3982 }
3983
3984 static struct ibm_struct cmos_driver_data = {
3985         .name = "cmos",
3986         .read = cmos_read,
3987         .write = cmos_write,
3988         .exit = cmos_exit,
3989 };
3990
3991 /*************************************************************************
3992  * LED subdriver
3993  */
3994
3995 enum led_access_mode {
3996         TPACPI_LED_NONE = 0,
3997         TPACPI_LED_570, /* 570 */
3998         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
3999         TPACPI_LED_NEW, /* all others */
4000 };
4001
4002 enum {  /* For TPACPI_LED_OLD */
4003         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4004         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4005         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4006 };
4007
4008 enum led_status_t {
4009         TPACPI_LED_OFF = 0,
4010         TPACPI_LED_ON,
4011         TPACPI_LED_BLINK,
4012 };
4013
4014 static enum led_access_mode led_supported;
4015
4016 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4017            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4018                                 /* T20-22, X20-21 */
4019            "LED",               /* all others */
4020            );                   /* R30, R31 */
4021
4022 #define TPACPI_LED_NUMLEDS 8
4023 static struct tpacpi_led_classdev *tpacpi_leds;
4024 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4025 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4026         /* there's a limit of 19 chars + NULL before 2.6.26 */
4027         "tpacpi::power",
4028         "tpacpi:orange:batt",
4029         "tpacpi:green:batt",
4030         "tpacpi::dock_active",
4031         "tpacpi::bay_active",
4032         "tpacpi::dock_batt",
4033         "tpacpi::unknown_led",
4034         "tpacpi::standby",
4035 };
4036
4037 static int led_get_status(const unsigned int led)
4038 {
4039         int status;
4040         enum led_status_t led_s;
4041
4042         switch (led_supported) {
4043         case TPACPI_LED_570:
4044                 if (!acpi_evalf(ec_handle,
4045                                 &status, "GLED", "dd", 1 << led))
4046                         return -EIO;
4047                 led_s = (status == 0)?
4048                                 TPACPI_LED_OFF :
4049                                 ((status == 1)?
4050                                         TPACPI_LED_ON :
4051                                         TPACPI_LED_BLINK);
4052                 tpacpi_led_state_cache[led] = led_s;
4053                 return led_s;
4054         default:
4055                 return -ENXIO;
4056         }
4057
4058         /* not reached */
4059 }
4060
4061 static int led_set_status(const unsigned int led,
4062                           const enum led_status_t ledstatus)
4063 {
4064         /* off, on, blink. Index is led_status_t */
4065         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
4066         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
4067
4068         int rc = 0;
4069
4070         switch (led_supported) {
4071         case TPACPI_LED_570:
4072                 /* 570 */
4073                 if (led > 7)
4074                         return -EINVAL;
4075                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4076                                 (1 << led), led_sled_arg1[ledstatus]))
4077                         rc = -EIO;
4078                 break;
4079         case TPACPI_LED_OLD:
4080                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
4081                 if (led > 7)
4082                         return -EINVAL;
4083                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
4084                 if (rc >= 0)
4085                         rc = ec_write(TPACPI_LED_EC_HLBL,
4086                                       (ledstatus == TPACPI_LED_BLINK) << led);
4087                 if (rc >= 0)
4088                         rc = ec_write(TPACPI_LED_EC_HLCL,
4089                                       (ledstatus != TPACPI_LED_OFF) << led);
4090                 break;
4091         case TPACPI_LED_NEW:
4092                 /* all others */
4093                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4094                                 led, led_led_arg1[ledstatus]))
4095                         rc = -EIO;
4096                 break;
4097         default:
4098                 rc = -ENXIO;
4099         }
4100
4101         if (!rc)
4102                 tpacpi_led_state_cache[led] = ledstatus;
4103
4104         return rc;
4105 }
4106
4107 static void led_sysfs_set_status(unsigned int led,
4108                                  enum led_brightness brightness)
4109 {
4110         led_set_status(led,
4111                         (brightness == LED_OFF) ?
4112                         TPACPI_LED_OFF :
4113                         (tpacpi_led_state_cache[led] == TPACPI_LED_BLINK) ?
4114                                 TPACPI_LED_BLINK : TPACPI_LED_ON);
4115 }
4116
4117 static void led_set_status_worker(struct work_struct *work)
4118 {
4119         struct tpacpi_led_classdev *data =
4120                 container_of(work, struct tpacpi_led_classdev, work);
4121
4122         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4123                 led_sysfs_set_status(data->led, data->new_brightness);
4124 }
4125
4126 static void led_sysfs_set(struct led_classdev *led_cdev,
4127                         enum led_brightness brightness)
4128 {
4129         struct tpacpi_led_classdev *data = container_of(led_cdev,
4130                              struct tpacpi_led_classdev, led_classdev);
4131
4132         data->new_brightness = brightness;
4133         queue_work(tpacpi_wq, &data->work);
4134 }
4135
4136 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
4137                         unsigned long *delay_on, unsigned long *delay_off)
4138 {
4139         struct tpacpi_led_classdev *data = container_of(led_cdev,
4140                              struct tpacpi_led_classdev, led_classdev);
4141
4142         /* Can we choose the flash rate? */
4143         if (*delay_on == 0 && *delay_off == 0) {
4144                 /* yes. set them to the hardware blink rate (1 Hz) */
4145                 *delay_on = 500; /* ms */
4146                 *delay_off = 500; /* ms */
4147         } else if ((*delay_on != 500) || (*delay_off != 500))
4148                 return -EINVAL;
4149
4150         data->new_brightness = TPACPI_LED_BLINK;
4151         queue_work(tpacpi_wq, &data->work);
4152
4153         return 0;
4154 }
4155
4156 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
4157 {
4158         int rc;
4159
4160         struct tpacpi_led_classdev *data = container_of(led_cdev,
4161                              struct tpacpi_led_classdev, led_classdev);
4162
4163         rc = led_get_status(data->led);
4164
4165         if (rc == TPACPI_LED_OFF || rc < 0)
4166                 rc = LED_OFF;   /* no error handling in led class :( */
4167         else
4168                 rc = LED_FULL;
4169
4170         return rc;
4171 }
4172
4173 static void led_exit(void)
4174 {
4175         unsigned int i;
4176
4177         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
4178                 if (tpacpi_leds[i].led_classdev.name)
4179                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
4180         }
4181
4182         kfree(tpacpi_leds);
4183 }
4184
4185 static int __init led_init(struct ibm_init_struct *iibm)
4186 {
4187         unsigned int i;
4188         int rc;
4189
4190         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
4191
4192         TPACPI_ACPIHANDLE_INIT(led);
4193
4194         if (!led_handle)
4195                 /* led not supported on R30, R31 */
4196                 led_supported = TPACPI_LED_NONE;
4197         else if (strlencmp(led_path, "SLED") == 0)
4198                 /* 570 */
4199                 led_supported = TPACPI_LED_570;
4200         else if (strlencmp(led_path, "SYSL") == 0)
4201                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4202                 led_supported = TPACPI_LED_OLD;
4203         else
4204                 /* all others */
4205                 led_supported = TPACPI_LED_NEW;
4206
4207         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
4208                 str_supported(led_supported), led_supported);
4209
4210         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
4211                               GFP_KERNEL);
4212         if (!tpacpi_leds) {
4213                 printk(TPACPI_ERR "Out of memory for LED data\n");
4214                 return -ENOMEM;
4215         }
4216
4217         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
4218                 tpacpi_leds[i].led = i;
4219
4220                 tpacpi_leds[i].led_classdev.brightness_set = &led_sysfs_set;
4221                 tpacpi_leds[i].led_classdev.blink_set = &led_sysfs_blink_set;
4222                 if (led_supported == TPACPI_LED_570)
4223                         tpacpi_leds[i].led_classdev.brightness_get =
4224                                                         &led_sysfs_get;
4225
4226                 tpacpi_leds[i].led_classdev.name = tpacpi_led_names[i];
4227
4228                 INIT_WORK(&tpacpi_leds[i].work, led_set_status_worker);
4229
4230                 rc = led_classdev_register(&tpacpi_pdev->dev,
4231                                            &tpacpi_leds[i].led_classdev);
4232                 if (rc < 0) {
4233                         tpacpi_leds[i].led_classdev.name = NULL;
4234                         led_exit();
4235                         return rc;
4236                 }
4237         }
4238
4239         return (led_supported != TPACPI_LED_NONE)? 0 : 1;
4240 }
4241
4242 #define str_led_status(s) \
4243         ((s) == TPACPI_LED_OFF ? "off" : \
4244                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
4245
4246 static int led_read(char *p)
4247 {
4248         int len = 0;
4249
4250         if (!led_supported) {
4251                 len += sprintf(p + len, "status:\t\tnot supported\n");
4252                 return len;
4253         }
4254         len += sprintf(p + len, "status:\t\tsupported\n");
4255
4256         if (led_supported == TPACPI_LED_570) {
4257                 /* 570 */
4258                 int i, status;
4259                 for (i = 0; i < 8; i++) {
4260                         status = led_get_status(i);
4261                         if (status < 0)
4262                                 return -EIO;
4263                         len += sprintf(p + len, "%d:\t\t%s\n",
4264                                        i, str_led_status(status));
4265                 }
4266         }
4267
4268         len += sprintf(p + len, "commands:\t"
4269                        "<led> on, <led> off, <led> blink (<led> is 0-7)\n");
4270
4271         return len;
4272 }
4273
4274 static int led_write(char *buf)
4275 {
4276         char *cmd;
4277         int led, rc;
4278         enum led_status_t s;
4279
4280         if (!led_supported)
4281                 return -ENODEV;
4282
4283         while ((cmd = next_cmd(&buf))) {
4284                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 7)
4285                         return -EINVAL;
4286
4287                 if (strstr(cmd, "off")) {
4288                         s = TPACPI_LED_OFF;
4289                 } else if (strstr(cmd, "on")) {
4290                         s = TPACPI_LED_ON;
4291                 } else if (strstr(cmd, "blink")) {
4292                         s = TPACPI_LED_BLINK;
4293                 } else {
4294                         return -EINVAL;
4295                 }
4296
4297                 rc = led_set_status(led, s);
4298                 if (rc < 0)
4299                         return rc;
4300         }
4301
4302         return 0;
4303 }
4304
4305 static struct ibm_struct led_driver_data = {
4306         .name = "led",
4307         .read = led_read,
4308         .write = led_write,
4309         .exit = led_exit,
4310 };
4311
4312 /*************************************************************************
4313  * Beep subdriver
4314  */
4315
4316 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
4317
4318 static int __init beep_init(struct ibm_init_struct *iibm)
4319 {
4320         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
4321
4322         TPACPI_ACPIHANDLE_INIT(beep);
4323
4324         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
4325                 str_supported(beep_handle != NULL));
4326
4327         return (beep_handle)? 0 : 1;
4328 }
4329
4330 static int beep_read(char *p)
4331 {
4332         int len = 0;
4333
4334         if (!beep_handle)
4335                 len += sprintf(p + len, "status:\t\tnot supported\n");
4336         else {
4337                 len += sprintf(p + len, "status:\t\tsupported\n");
4338                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
4339         }
4340
4341         return len;
4342 }
4343
4344 static int beep_write(char *buf)
4345 {
4346         char *cmd;
4347         int beep_cmd;
4348
4349         if (!beep_handle)
4350                 return -ENODEV;
4351
4352         while ((cmd = next_cmd(&buf))) {
4353                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
4354                     beep_cmd >= 0 && beep_cmd <= 17) {
4355                         /* beep_cmd set */
4356                 } else
4357                         return -EINVAL;
4358                 if (!acpi_evalf(beep_handle, NULL, NULL, "vdd", beep_cmd, 0))
4359                         return -EIO;
4360         }
4361
4362         return 0;
4363 }
4364
4365 static struct ibm_struct beep_driver_data = {
4366         .name = "beep",
4367         .read = beep_read,
4368         .write = beep_write,
4369 };
4370
4371 /*************************************************************************
4372  * Thermal subdriver
4373  */
4374
4375 enum thermal_access_mode {
4376         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
4377         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
4378         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
4379         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
4380         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
4381 };
4382
4383 enum { /* TPACPI_THERMAL_TPEC_* */
4384         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
4385         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
4386         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
4387 };
4388
4389 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
4390 struct ibm_thermal_sensors_struct {
4391         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
4392 };
4393
4394 static enum thermal_access_mode thermal_read_mode;
4395
4396 /* idx is zero-based */
4397 static int thermal_get_sensor(int idx, s32 *value)
4398 {
4399         int t;
4400         s8 tmp;
4401         char tmpi[5];
4402
4403         t = TP_EC_THERMAL_TMP0;
4404
4405         switch (thermal_read_mode) {
4406 #if TPACPI_MAX_THERMAL_SENSORS >= 16
4407         case TPACPI_THERMAL_TPEC_16:
4408                 if (idx >= 8 && idx <= 15) {
4409                         t = TP_EC_THERMAL_TMP8;
4410                         idx -= 8;
4411                 }
4412                 /* fallthrough */
4413 #endif
4414         case TPACPI_THERMAL_TPEC_8:
4415                 if (idx <= 7) {
4416                         if (!acpi_ec_read(t + idx, &tmp))
4417                                 return -EIO;
4418                         *value = tmp * 1000;
4419                         return 0;
4420                 }
4421                 break;
4422
4423         case TPACPI_THERMAL_ACPI_UPDT:
4424                 if (idx <= 7) {
4425                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
4426                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
4427                                 return -EIO;
4428                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
4429                                 return -EIO;
4430                         *value = (t - 2732) * 100;
4431                         return 0;
4432                 }
4433                 break;
4434
4435         case TPACPI_THERMAL_ACPI_TMP07:
4436                 if (idx <= 7) {
4437                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
4438                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
4439                                 return -EIO;
4440                         if (t > 127 || t < -127)
4441                                 t = TP_EC_THERMAL_TMP_NA;
4442                         *value = t * 1000;
4443                         return 0;
4444                 }
4445                 break;
4446
4447         case TPACPI_THERMAL_NONE:
4448         default:
4449                 return -ENOSYS;
4450         }
4451
4452         return -EINVAL;
4453 }
4454
4455 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
4456 {
4457         int res, i;
4458         int n;
4459
4460         n = 8;
4461         i = 0;
4462
4463         if (!s)
4464                 return -EINVAL;
4465
4466         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
4467                 n = 16;
4468
4469         for (i = 0 ; i < n; i++) {
4470                 res = thermal_get_sensor(i, &s->temp[i]);
4471                 if (res)
4472                         return res;
4473         }
4474
4475         return n;
4476 }
4477
4478 /* sysfs temp##_input -------------------------------------------------- */
4479
4480 static ssize_t thermal_temp_input_show(struct device *dev,
4481                            struct device_attribute *attr,
4482                            char *buf)
4483 {
4484         struct sensor_device_attribute *sensor_attr =
4485                                         to_sensor_dev_attr(attr);
4486         int idx = sensor_attr->index;
4487         s32 value;
4488         int res;
4489
4490         res = thermal_get_sensor(idx, &value);
4491         if (res)
4492                 return res;
4493         if (value == TP_EC_THERMAL_TMP_NA * 1000)
4494                 return -ENXIO;
4495
4496         return snprintf(buf, PAGE_SIZE, "%d\n", value);
4497 }
4498
4499 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
4500          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
4501                      thermal_temp_input_show, NULL, _idxB)
4502
4503 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
4504         THERMAL_SENSOR_ATTR_TEMP(1, 0),
4505         THERMAL_SENSOR_ATTR_TEMP(2, 1),
4506         THERMAL_SENSOR_ATTR_TEMP(3, 2),
4507         THERMAL_SENSOR_ATTR_TEMP(4, 3),
4508         THERMAL_SENSOR_ATTR_TEMP(5, 4),
4509         THERMAL_SENSOR_ATTR_TEMP(6, 5),
4510         THERMAL_SENSOR_ATTR_TEMP(7, 6),
4511         THERMAL_SENSOR_ATTR_TEMP(8, 7),
4512         THERMAL_SENSOR_ATTR_TEMP(9, 8),
4513         THERMAL_SENSOR_ATTR_TEMP(10, 9),
4514         THERMAL_SENSOR_ATTR_TEMP(11, 10),
4515         THERMAL_SENSOR_ATTR_TEMP(12, 11),
4516         THERMAL_SENSOR_ATTR_TEMP(13, 12),
4517         THERMAL_SENSOR_ATTR_TEMP(14, 13),
4518         THERMAL_SENSOR_ATTR_TEMP(15, 14),
4519         THERMAL_SENSOR_ATTR_TEMP(16, 15),
4520 };
4521
4522 #define THERMAL_ATTRS(X) \
4523         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
4524
4525 static struct attribute *thermal_temp_input_attr[] = {
4526         THERMAL_ATTRS(8),
4527         THERMAL_ATTRS(9),
4528         THERMAL_ATTRS(10),
4529         THERMAL_ATTRS(11),
4530         THERMAL_ATTRS(12),
4531         THERMAL_ATTRS(13),
4532         THERMAL_ATTRS(14),
4533         THERMAL_ATTRS(15),
4534         THERMAL_ATTRS(0),
4535         THERMAL_ATTRS(1),
4536         THERMAL_ATTRS(2),
4537         THERMAL_ATTRS(3),
4538         THERMAL_ATTRS(4),
4539         THERMAL_ATTRS(5),
4540         THERMAL_ATTRS(6),
4541         THERMAL_ATTRS(7),
4542         NULL
4543 };
4544
4545 static const struct attribute_group thermal_temp_input16_group = {
4546         .attrs = thermal_temp_input_attr
4547 };
4548
4549 static const struct attribute_group thermal_temp_input8_group = {
4550         .attrs = &thermal_temp_input_attr[8]
4551 };
4552
4553 #undef THERMAL_SENSOR_ATTR_TEMP
4554 #undef THERMAL_ATTRS
4555
4556 /* --------------------------------------------------------------------- */
4557
4558 static int __init thermal_init(struct ibm_init_struct *iibm)
4559 {
4560         u8 t, ta1, ta2;
4561         int i;
4562         int acpi_tmp7;
4563         int res;
4564
4565         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
4566
4567         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
4568
4569         if (thinkpad_id.ec_model) {
4570                 /*
4571                  * Direct EC access mode: sensors at registers
4572                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
4573                  * non-implemented, thermal sensors return 0x80 when
4574                  * not available
4575                  */
4576
4577                 ta1 = ta2 = 0;
4578                 for (i = 0; i < 8; i++) {
4579                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
4580                                 ta1 |= t;
4581                         } else {
4582                                 ta1 = 0;
4583                                 break;
4584                         }
4585                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
4586                                 ta2 |= t;
4587                         } else {
4588                                 ta1 = 0;
4589                                 break;
4590                         }
4591                 }
4592                 if (ta1 == 0) {
4593                         /* This is sheer paranoia, but we handle it anyway */
4594                         if (acpi_tmp7) {
4595                                 printk(TPACPI_ERR
4596                                        "ThinkPad ACPI EC access misbehaving, "
4597                                        "falling back to ACPI TMPx access "
4598                                        "mode\n");
4599                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
4600                         } else {
4601                                 printk(TPACPI_ERR
4602                                        "ThinkPad ACPI EC access misbehaving, "
4603                                        "disabling thermal sensors access\n");
4604                                 thermal_read_mode = TPACPI_THERMAL_NONE;
4605                         }
4606                 } else {
4607                         thermal_read_mode =
4608                             (ta2 != 0) ?
4609                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
4610                 }
4611         } else if (acpi_tmp7) {
4612                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
4613                         /* 600e/x, 770e, 770x */
4614                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
4615                 } else {
4616                         /* Standard ACPI TMPx access, max 8 sensors */
4617                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
4618                 }
4619         } else {
4620                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
4621                 thermal_read_mode = TPACPI_THERMAL_NONE;
4622         }
4623
4624         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
4625                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
4626                 thermal_read_mode);
4627
4628         switch (thermal_read_mode) {
4629         case TPACPI_THERMAL_TPEC_16:
4630                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
4631                                 &thermal_temp_input16_group);
4632                 if (res)
4633                         return res;
4634                 break;
4635         case TPACPI_THERMAL_TPEC_8:
4636         case TPACPI_THERMAL_ACPI_TMP07:
4637         case TPACPI_THERMAL_ACPI_UPDT:
4638                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
4639                                 &thermal_temp_input8_group);
4640                 if (res)
4641                         return res;
4642                 break;
4643         case TPACPI_THERMAL_NONE:
4644         default:
4645                 return 1;
4646         }
4647
4648         return 0;
4649 }
4650
4651 static void thermal_exit(void)
4652 {
4653         switch (thermal_read_mode) {
4654         case TPACPI_THERMAL_TPEC_16:
4655                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
4656                                    &thermal_temp_input16_group);
4657                 break;
4658         case TPACPI_THERMAL_TPEC_8:
4659         case TPACPI_THERMAL_ACPI_TMP07:
4660         case TPACPI_THERMAL_ACPI_UPDT:
4661                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
4662                                    &thermal_temp_input16_group);
4663                 break;
4664         case TPACPI_THERMAL_NONE:
4665         default:
4666                 break;
4667         }
4668 }
4669
4670 static int thermal_read(char *p)
4671 {
4672         int len = 0;
4673         int n, i;
4674         struct ibm_thermal_sensors_struct t;
4675
4676         n = thermal_get_sensors(&t);
4677         if (unlikely(n < 0))
4678                 return n;
4679
4680         len += sprintf(p + len, "temperatures:\t");
4681
4682         if (n > 0) {
4683                 for (i = 0; i < (n - 1); i++)
4684                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
4685                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
4686         } else
4687                 len += sprintf(p + len, "not supported\n");
4688
4689         return len;
4690 }
4691
4692 static struct ibm_struct thermal_driver_data = {
4693         .name = "thermal",
4694         .read = thermal_read,
4695         .exit = thermal_exit,
4696 };
4697
4698 /*************************************************************************
4699  * EC Dump subdriver
4700  */
4701
4702 static u8 ecdump_regs[256];
4703
4704 static int ecdump_read(char *p)
4705 {
4706         int len = 0;
4707         int i, j;
4708         u8 v;
4709
4710         len += sprintf(p + len, "EC      "
4711                        " +00 +01 +02 +03 +04 +05 +06 +07"
4712                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
4713         for (i = 0; i < 256; i += 16) {
4714                 len += sprintf(p + len, "EC 0x%02x:", i);
4715                 for (j = 0; j < 16; j++) {
4716                         if (!acpi_ec_read(i + j, &v))
4717                                 break;
4718                         if (v != ecdump_regs[i + j])
4719                                 len += sprintf(p + len, " *%02x", v);
4720                         else
4721                                 len += sprintf(p + len, "  %02x", v);
4722                         ecdump_regs[i + j] = v;
4723                 }
4724                 len += sprintf(p + len, "\n");
4725                 if (j != 16)
4726                         break;
4727         }
4728
4729         /* These are way too dangerous to advertise openly... */
4730 #if 0
4731         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
4732                        " (<offset> is 00-ff, <value> is 00-ff)\n");
4733         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
4734                        " (<offset> is 00-ff, <value> is 0-255)\n");
4735 #endif
4736         return len;
4737 }
4738
4739 static int ecdump_write(char *buf)
4740 {
4741         char *cmd;
4742         int i, v;
4743
4744         while ((cmd = next_cmd(&buf))) {
4745                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
4746                         /* i and v set */
4747                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
4748                         /* i and v set */
4749                 } else
4750                         return -EINVAL;
4751                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
4752                         if (!acpi_ec_write(i, v))
4753                                 return -EIO;
4754                 } else
4755                         return -EINVAL;
4756         }
4757
4758         return 0;
4759 }
4760
4761 static struct ibm_struct ecdump_driver_data = {
4762         .name = "ecdump",
4763         .read = ecdump_read,
4764         .write = ecdump_write,
4765         .flags.experimental = 1,
4766 };
4767
4768 /*************************************************************************
4769  * Backlight/brightness subdriver
4770  */
4771
4772 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
4773
4774 enum {
4775         TP_EC_BACKLIGHT = 0x31,
4776
4777         /* TP_EC_BACKLIGHT bitmasks */
4778         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
4779         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
4780         TP_EC_BACKLIGHT_MAPSW = 0x20,
4781 };
4782
4783 static struct backlight_device *ibm_backlight_device;
4784 static int brightness_mode;
4785 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
4786
4787 static struct mutex brightness_mutex;
4788
4789 /*
4790  * ThinkPads can read brightness from two places: EC 0x31, or
4791  * CMOS NVRAM byte 0x5E, bits 0-3.
4792  *
4793  * EC 0x31 has the following layout
4794  *   Bit 7: unknown function
4795  *   Bit 6: unknown function
4796  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
4797  *   Bit 4: must be set to zero to avoid problems
4798  *   Bit 3-0: backlight brightness level
4799  *
4800  * brightness_get_raw returns status data in the EC 0x31 layout
4801  */
4802 static int brightness_get_raw(int *status)
4803 {
4804         u8 lec = 0, lcmos = 0, level = 0;
4805
4806         if (brightness_mode & 1) {
4807                 if (!acpi_ec_read(TP_EC_BACKLIGHT, &lec))
4808                         return -EIO;
4809                 level = lec & TP_EC_BACKLIGHT_LVLMSK;
4810         };
4811         if (brightness_mode & 2) {
4812                 lcmos = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
4813                          & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
4814                         >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
4815                 lcmos &= (tp_features.bright_16levels)? 0x0f : 0x07;
4816                 level = lcmos;
4817         }
4818
4819         if (brightness_mode == 3) {
4820                 *status = lec;  /* Prefer EC, CMOS is just a backing store */
4821                 lec &= TP_EC_BACKLIGHT_LVLMSK;
4822                 if (lec == lcmos)
4823                         tp_warned.bright_cmos_ec_unsync = 0;
4824                 else {
4825                         if (!tp_warned.bright_cmos_ec_unsync) {
4826                                 printk(TPACPI_ERR
4827                                         "CMOS NVRAM (%u) and EC (%u) do not "
4828                                         "agree on display brightness level\n",
4829                                         (unsigned int) lcmos,
4830                                         (unsigned int) lec);
4831                                 tp_warned.bright_cmos_ec_unsync = 1;
4832                         }
4833                         return -EIO;
4834                 }
4835         } else {
4836                 *status = level;
4837         }
4838
4839         return 0;
4840 }
4841
4842 /* May return EINTR which can always be mapped to ERESTARTSYS */
4843 static int brightness_set(int value)
4844 {
4845         int cmos_cmd, inc, i, res;
4846         int current_value;
4847         int command_bits;
4848
4849         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
4850             value < 0)
4851                 return -EINVAL;
4852
4853         res = mutex_lock_interruptible(&brightness_mutex);
4854         if (res < 0)
4855                 return res;
4856
4857         res = brightness_get_raw(&current_value);
4858         if (res < 0)
4859                 goto errout;
4860
4861         command_bits = current_value & TP_EC_BACKLIGHT_CMDMSK;
4862         current_value &= TP_EC_BACKLIGHT_LVLMSK;
4863
4864         cmos_cmd = value > current_value ?
4865                         TP_CMOS_BRIGHTNESS_UP :
4866                         TP_CMOS_BRIGHTNESS_DOWN;
4867         inc = (value > current_value)? 1 : -1;
4868
4869         res = 0;
4870         for (i = current_value; i != value; i += inc) {
4871                 if ((brightness_mode & 2) &&
4872                     issue_thinkpad_cmos_command(cmos_cmd)) {
4873                         res = -EIO;
4874                         goto errout;
4875                 }
4876                 if ((brightness_mode & 1) &&
4877                     !acpi_ec_write(TP_EC_BACKLIGHT,
4878                                    (i + inc) | command_bits)) {
4879                         res = -EIO;
4880                         goto errout;;
4881                 }
4882         }
4883
4884 errout:
4885         mutex_unlock(&brightness_mutex);
4886         return res;
4887 }
4888
4889 /* sysfs backlight class ----------------------------------------------- */
4890
4891 static int brightness_update_status(struct backlight_device *bd)
4892 {
4893         /* it is the backlight class's job (caller) to handle
4894          * EINTR and other errors properly */
4895         return brightness_set(
4896                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
4897                  bd->props.power == FB_BLANK_UNBLANK) ?
4898                                 bd->props.brightness : 0);
4899 }
4900
4901 static int brightness_get(struct backlight_device *bd)
4902 {
4903         int status, res;
4904
4905         res = brightness_get_raw(&status);
4906         if (res < 0)
4907                 return 0; /* FIXME: teach backlight about error handling */
4908
4909         return status & TP_EC_BACKLIGHT_LVLMSK;
4910 }
4911
4912 static struct backlight_ops ibm_backlight_data = {
4913         .get_brightness = brightness_get,
4914         .update_status  = brightness_update_status,
4915 };
4916
4917 /* --------------------------------------------------------------------- */
4918
4919 static int __init brightness_init(struct ibm_init_struct *iibm)
4920 {
4921         int b;
4922
4923         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
4924
4925         mutex_init(&brightness_mutex);
4926
4927         /*
4928          * We always attempt to detect acpi support, so as to switch
4929          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
4930          * going to publish a backlight interface
4931          */
4932         b = tpacpi_check_std_acpi_brightness_support();
4933         if (b > 0) {
4934
4935                 if (acpi_video_backlight_support()) {
4936                         if (brightness_enable > 1) {
4937                                 printk(TPACPI_NOTICE
4938                                        "Standard ACPI backlight interface "
4939                                        "available, not loading native one.\n");
4940                                 return 1;
4941                         } else if (brightness_enable == 1) {
4942                                 printk(TPACPI_NOTICE
4943                                        "Backlight control force enabled, even if standard "
4944                                        "ACPI backlight interface is available\n");
4945                         }
4946                 } else {
4947                         if (brightness_enable > 1) {
4948                                 printk(TPACPI_NOTICE
4949                                        "Standard ACPI backlight interface not "
4950                                        "available, thinkpad_acpi native "
4951                                        "brightness control enabled\n");
4952                         }
4953                 }
4954         }
4955
4956         if (!brightness_enable) {
4957                 dbg_printk(TPACPI_DBG_INIT,
4958                            "brightness support disabled by "
4959                            "module parameter\n");
4960                 return 1;
4961         }
4962
4963         if (b > 16) {
4964                 printk(TPACPI_ERR
4965                        "Unsupported brightness interface, "
4966                        "please contact %s\n", TPACPI_MAIL);
4967                 return 1;
4968         }
4969         if (b == 16)
4970                 tp_features.bright_16levels = 1;
4971
4972         if (!brightness_mode) {
4973                 if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO)
4974                         brightness_mode = 2;
4975                 else
4976                         brightness_mode = 3;
4977
4978                 dbg_printk(TPACPI_DBG_INIT, "selected brightness_mode=%d\n",
4979                         brightness_mode);
4980         }
4981
4982         if (brightness_mode > 3)
4983                 return -EINVAL;
4984
4985         if (brightness_get_raw(&b) < 0)
4986                 return 1;
4987
4988         if (tp_features.bright_16levels)
4989                 printk(TPACPI_INFO
4990                        "detected a 16-level brightness capable ThinkPad\n");
4991
4992         ibm_backlight_device = backlight_device_register(
4993                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
4994                                         &ibm_backlight_data);
4995         if (IS_ERR(ibm_backlight_device)) {
4996                 printk(TPACPI_ERR "Could not register backlight device\n");
4997                 return PTR_ERR(ibm_backlight_device);
4998         }
4999         vdbg_printk(TPACPI_DBG_INIT, "brightness is supported\n");
5000
5001         ibm_backlight_device->props.max_brightness =
5002                                 (tp_features.bright_16levels)? 15 : 7;
5003         ibm_backlight_device->props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
5004         backlight_update_status(ibm_backlight_device);
5005
5006         return 0;
5007 }
5008
5009 static void brightness_exit(void)
5010 {
5011         if (ibm_backlight_device) {
5012                 vdbg_printk(TPACPI_DBG_EXIT,
5013                             "calling backlight_device_unregister()\n");
5014                 backlight_device_unregister(ibm_backlight_device);
5015         }
5016 }
5017
5018 static int brightness_read(char *p)
5019 {
5020         int len = 0;
5021         int level;
5022
5023         level = brightness_get(NULL);
5024         if (level < 0) {
5025                 len += sprintf(p + len, "level:\t\tunreadable\n");
5026         } else {
5027                 len += sprintf(p + len, "level:\t\t%d\n", level);
5028                 len += sprintf(p + len, "commands:\tup, down\n");
5029                 len += sprintf(p + len, "commands:\tlevel <level>"
5030                                " (<level> is 0-%d)\n",
5031                                (tp_features.bright_16levels) ? 15 : 7);
5032         }
5033
5034         return len;
5035 }
5036
5037 static int brightness_write(char *buf)
5038 {
5039         int level;
5040         int rc;
5041         char *cmd;
5042         int max_level = (tp_features.bright_16levels) ? 15 : 7;
5043
5044         level = brightness_get(NULL);
5045         if (level < 0)
5046                 return level;
5047
5048         while ((cmd = next_cmd(&buf))) {
5049                 if (strlencmp(cmd, "up") == 0) {
5050                         if (level < max_level)
5051                                 level++;
5052                 } else if (strlencmp(cmd, "down") == 0) {
5053                         if (level > 0)
5054                                 level--;
5055                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
5056                            level >= 0 && level <= max_level) {
5057                         /* new level set */
5058                 } else
5059                         return -EINVAL;
5060         }
5061
5062         /*
5063          * Now we know what the final level should be, so we try to set it.
5064          * Doing it this way makes the syscall restartable in case of EINTR
5065          */
5066         rc = brightness_set(level);
5067         return (rc == -EINTR)? ERESTARTSYS : rc;
5068 }
5069
5070 static struct ibm_struct brightness_driver_data = {
5071         .name = "brightness",
5072         .read = brightness_read,
5073         .write = brightness_write,
5074         .exit = brightness_exit,
5075 };
5076
5077 /*************************************************************************
5078  * Volume subdriver
5079  */
5080
5081 static int volume_offset = 0x30;
5082
5083 static int volume_read(char *p)
5084 {
5085         int len = 0;
5086         u8 level;
5087
5088         if (!acpi_ec_read(volume_offset, &level)) {
5089                 len += sprintf(p + len, "level:\t\tunreadable\n");
5090         } else {
5091                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
5092                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
5093                 len += sprintf(p + len, "commands:\tup, down, mute\n");
5094                 len += sprintf(p + len, "commands:\tlevel <level>"
5095                                " (<level> is 0-15)\n");
5096         }
5097
5098         return len;
5099 }
5100
5101 static int volume_write(char *buf)
5102 {
5103         int cmos_cmd, inc, i;
5104         u8 level, mute;
5105         int new_level, new_mute;
5106         char *cmd;
5107
5108         while ((cmd = next_cmd(&buf))) {
5109                 if (!acpi_ec_read(volume_offset, &level))
5110                         return -EIO;
5111                 new_mute = mute = level & 0x40;
5112                 new_level = level = level & 0xf;
5113
5114                 if (strlencmp(cmd, "up") == 0) {
5115                         if (mute)
5116                                 new_mute = 0;
5117                         else
5118                                 new_level = level == 15 ? 15 : level + 1;
5119                 } else if (strlencmp(cmd, "down") == 0) {
5120                         if (mute)
5121                                 new_mute = 0;
5122                         else
5123                                 new_level = level == 0 ? 0 : level - 1;
5124                 } else if (sscanf(cmd, "level %d", &new_level) == 1 &&
5125                            new_level >= 0 && new_level <= 15) {
5126                         /* new_level set */
5127                 } else if (strlencmp(cmd, "mute") == 0) {
5128                         new_mute = 0x40;
5129                 } else
5130                         return -EINVAL;
5131
5132                 if (new_level != level) {
5133                         /* mute doesn't change */
5134
5135                         cmos_cmd = (new_level > level) ?
5136                                         TP_CMOS_VOLUME_UP : TP_CMOS_VOLUME_DOWN;
5137                         inc = new_level > level ? 1 : -1;
5138
5139                         if (mute && (issue_thinkpad_cmos_command(cmos_cmd) ||
5140                                      !acpi_ec_write(volume_offset, level)))
5141                                 return -EIO;
5142
5143                         for (i = level; i != new_level; i += inc)
5144                                 if (issue_thinkpad_cmos_command(cmos_cmd) ||
5145                                     !acpi_ec_write(volume_offset, i + inc))
5146                                         return -EIO;
5147
5148                         if (mute &&
5149                             (issue_thinkpad_cmos_command(TP_CMOS_VOLUME_MUTE) ||
5150                              !acpi_ec_write(volume_offset, new_level + mute))) {
5151                                 return -EIO;
5152                         }
5153                 }
5154
5155                 if (new_mute != mute) {
5156                         /* level doesn't change */
5157
5158                         cmos_cmd = (new_mute) ?
5159                                    TP_CMOS_VOLUME_MUTE : TP_CMOS_VOLUME_UP;
5160
5161                         if (issue_thinkpad_cmos_command(cmos_cmd) ||
5162                             !acpi_ec_write(volume_offset, level + new_mute))
5163                                 return -EIO;
5164                 }
5165         }
5166
5167         return 0;
5168 }
5169
5170 static struct ibm_struct volume_driver_data = {
5171         .name = "volume",
5172         .read = volume_read,
5173         .write = volume_write,
5174 };
5175
5176 /*************************************************************************
5177  * Fan subdriver
5178  */
5179
5180 /*
5181  * FAN ACCESS MODES
5182  *
5183  * TPACPI_FAN_RD_ACPI_GFAN:
5184  *      ACPI GFAN method: returns fan level
5185  *
5186  *      see TPACPI_FAN_WR_ACPI_SFAN
5187  *      EC 0x2f (HFSP) not available if GFAN exists
5188  *
5189  * TPACPI_FAN_WR_ACPI_SFAN:
5190  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
5191  *
5192  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
5193  *      it for writing.
5194  *
5195  * TPACPI_FAN_WR_TPEC:
5196  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
5197  *      Supported on almost all ThinkPads
5198  *
5199  *      Fan speed changes of any sort (including those caused by the
5200  *      disengaged mode) are usually done slowly by the firmware as the
5201  *      maximum ammount of fan duty cycle change per second seems to be
5202  *      limited.
5203  *
5204  *      Reading is not available if GFAN exists.
5205  *      Writing is not available if SFAN exists.
5206  *
5207  *      Bits
5208  *       7      automatic mode engaged;
5209  *              (default operation mode of the ThinkPad)
5210  *              fan level is ignored in this mode.
5211  *       6      full speed mode (takes precedence over bit 7);
5212  *              not available on all thinkpads.  May disable
5213  *              the tachometer while the fan controller ramps up
5214  *              the speed (which can take up to a few *minutes*).
5215  *              Speeds up fan to 100% duty-cycle, which is far above
5216  *              the standard RPM levels.  It is not impossible that
5217  *              it could cause hardware damage.
5218  *      5-3     unused in some models.  Extra bits for fan level
5219  *              in others, but still useless as all values above
5220  *              7 map to the same speed as level 7 in these models.
5221  *      2-0     fan level (0..7 usually)
5222  *                      0x00 = stop
5223  *                      0x07 = max (set when temperatures critical)
5224  *              Some ThinkPads may have other levels, see
5225  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
5226  *
5227  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
5228  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
5229  *      does so, its initial value is meaningless (0x07).
5230  *
5231  *      For firmware bugs, refer to:
5232  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
5233  *
5234  *      ----
5235  *
5236  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
5237  *      Main fan tachometer reading (in RPM)
5238  *
5239  *      This register is present on all ThinkPads with a new-style EC, and
5240  *      it is known not to be present on the A21m/e, and T22, as there is
5241  *      something else in offset 0x84 according to the ACPI DSDT.  Other
5242  *      ThinkPads from this same time period (and earlier) probably lack the
5243  *      tachometer as well.
5244  *
5245  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firwmare
5246  *      was never fixed by IBM to report the EC firmware version string
5247  *      probably support the tachometer (like the early X models), so
5248  *      detecting it is quite hard.  We need more data to know for sure.
5249  *
5250  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
5251  *      might result.
5252  *
5253  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
5254  *      mode.
5255  *
5256  *      For firmware bugs, refer to:
5257  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
5258  *
5259  * TPACPI_FAN_WR_ACPI_FANS:
5260  *      ThinkPad X31, X40, X41.  Not available in the X60.
5261  *
5262  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
5263  *      high speed.  ACPI DSDT seems to map these three speeds to levels
5264  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
5265  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
5266  *
5267  *      The speeds are stored on handles
5268  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
5269  *
5270  *      There are three default speed sets, acessible as handles:
5271  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
5272  *
5273  *      ACPI DSDT switches which set is in use depending on various
5274  *      factors.
5275  *
5276  *      TPACPI_FAN_WR_TPEC is also available and should be used to
5277  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
5278  *      but the ACPI tables just mention level 7.
5279  */
5280
5281 enum {                                  /* Fan control constants */
5282         fan_status_offset = 0x2f,       /* EC register 0x2f */
5283         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
5284                                          * 0x84 must be read before 0x85 */
5285
5286         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
5287         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
5288
5289         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
5290 };
5291
5292 enum fan_status_access_mode {
5293         TPACPI_FAN_NONE = 0,            /* No fan status or control */
5294         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
5295         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
5296 };
5297
5298 enum fan_control_access_mode {
5299         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
5300         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
5301         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
5302         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
5303 };
5304
5305 enum fan_control_commands {
5306         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
5307         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
5308         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
5309                                                  * and also watchdog cmd */
5310 };
5311
5312 static int fan_control_allowed;
5313
5314 static enum fan_status_access_mode fan_status_access_mode;
5315 static enum fan_control_access_mode fan_control_access_mode;
5316 static enum fan_control_commands fan_control_commands;
5317
5318 static u8 fan_control_initial_status;
5319 static u8 fan_control_desired_level;
5320 static u8 fan_control_resume_level;
5321 static int fan_watchdog_maxinterval;
5322
5323 static struct mutex fan_mutex;
5324
5325 static void fan_watchdog_fire(struct work_struct *ignored);
5326 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
5327
5328 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
5329 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
5330            "\\FSPD",            /* 600e/x, 770e, 770x */
5331            );                   /* all others */
5332 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
5333            "JFNS",              /* 770x-JL */
5334            );                   /* all others */
5335
5336 /*
5337  * Call with fan_mutex held
5338  */
5339 static void fan_update_desired_level(u8 status)
5340 {
5341         if ((status &
5342              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
5343                 if (status > 7)
5344                         fan_control_desired_level = 7;
5345                 else
5346                         fan_control_desired_level = status;
5347         }
5348 }
5349
5350 static int fan_get_status(u8 *status)
5351 {
5352         u8 s;
5353
5354         /* TODO:
5355          * Add TPACPI_FAN_RD_ACPI_FANS ? */
5356
5357         switch (fan_status_access_mode) {
5358         case TPACPI_FAN_RD_ACPI_GFAN:
5359                 /* 570, 600e/x, 770e, 770x */
5360
5361                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
5362                         return -EIO;
5363
5364                 if (likely(status))
5365                         *status = s & 0x07;
5366
5367                 break;
5368
5369         case TPACPI_FAN_RD_TPEC:
5370                 /* all except 570, 600e/x, 770e, 770x */
5371                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
5372                         return -EIO;
5373
5374                 if (likely(status))
5375                         *status = s;
5376
5377                 break;
5378
5379         default:
5380                 return -ENXIO;
5381         }
5382
5383         return 0;
5384 }
5385
5386 static int fan_get_status_safe(u8 *status)
5387 {
5388         int rc;
5389         u8 s;
5390
5391         if (mutex_lock_interruptible(&fan_mutex))
5392                 return -ERESTARTSYS;
5393         rc = fan_get_status(&s);
5394         if (!rc)
5395                 fan_update_desired_level(s);
5396         mutex_unlock(&fan_mutex);
5397
5398         if (status)
5399                 *status = s;
5400
5401         return rc;
5402 }
5403
5404 static int fan_get_speed(unsigned int *speed)
5405 {
5406         u8 hi, lo;
5407
5408         switch (fan_status_access_mode) {
5409         case TPACPI_FAN_RD_TPEC:
5410                 /* all except 570, 600e/x, 770e, 770x */
5411                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
5412                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
5413                         return -EIO;
5414
5415                 if (likely(speed))
5416                         *speed = (hi << 8) | lo;
5417
5418                 break;
5419
5420         default:
5421                 return -ENXIO;
5422         }
5423
5424         return 0;
5425 }
5426
5427 static int fan_set_level(int level)
5428 {
5429         if (!fan_control_allowed)
5430                 return -EPERM;
5431
5432         switch (fan_control_access_mode) {
5433         case TPACPI_FAN_WR_ACPI_SFAN:
5434                 if (level >= 0 && level <= 7) {
5435                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
5436                                 return -EIO;
5437                 } else
5438                         return -EINVAL;
5439                 break;
5440
5441         case TPACPI_FAN_WR_ACPI_FANS:
5442         case TPACPI_FAN_WR_TPEC:
5443                 if (!(level & TP_EC_FAN_AUTO) &&
5444                     !(level & TP_EC_FAN_FULLSPEED) &&
5445                     ((level < 0) || (level > 7)))
5446                         return -EINVAL;
5447
5448                 /* safety net should the EC not support AUTO
5449                  * or FULLSPEED mode bits and just ignore them */
5450                 if (level & TP_EC_FAN_FULLSPEED)
5451                         level |= 7;     /* safety min speed 7 */
5452                 else if (level & TP_EC_FAN_AUTO)
5453                         level |= 4;     /* safety min speed 4 */
5454
5455                 if (!acpi_ec_write(fan_status_offset, level))
5456                         return -EIO;
5457                 else
5458                         tp_features.fan_ctrl_status_undef = 0;
5459                 break;
5460
5461         default:
5462                 return -ENXIO;
5463         }
5464         return 0;
5465 }
5466
5467 static int fan_set_level_safe(int level)
5468 {
5469         int rc;
5470
5471         if (!fan_control_allowed)
5472                 return -EPERM;
5473
5474         if (mutex_lock_interruptible(&fan_mutex))
5475                 return -ERESTARTSYS;
5476
5477         if (level == TPACPI_FAN_LAST_LEVEL)
5478                 level = fan_control_desired_level;
5479
5480         rc = fan_set_level(level);
5481         if (!rc)
5482                 fan_update_desired_level(level);
5483
5484         mutex_unlock(&fan_mutex);
5485         return rc;
5486 }
5487
5488 static int fan_set_enable(void)
5489 {
5490         u8 s;
5491         int rc;
5492
5493         if (!fan_control_allowed)
5494                 return -EPERM;
5495
5496         if (mutex_lock_interruptible(&fan_mutex))
5497                 return -ERESTARTSYS;
5498
5499         switch (fan_control_access_mode) {
5500         case TPACPI_FAN_WR_ACPI_FANS:
5501         case TPACPI_FAN_WR_TPEC:
5502                 rc = fan_get_status(&s);
5503                 if (rc < 0)
5504                         break;
5505
5506                 /* Don't go out of emergency fan mode */
5507                 if (s != 7) {
5508                         s &= 0x07;
5509                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
5510                 }
5511
5512                 if (!acpi_ec_write(fan_status_offset, s))
5513                         rc = -EIO;
5514                 else {
5515                         tp_features.fan_ctrl_status_undef = 0;
5516                         rc = 0;
5517                 }
5518                 break;
5519
5520         case TPACPI_FAN_WR_ACPI_SFAN:
5521                 rc = fan_get_status(&s);
5522                 if (rc < 0)
5523                         break;
5524
5525                 s &= 0x07;
5526
5527                 /* Set fan to at least level 4 */
5528                 s |= 4;
5529
5530                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
5531                         rc = -EIO;
5532                 else
5533                         rc = 0;
5534                 break;
5535
5536         default:
5537                 rc = -ENXIO;
5538         }
5539
5540         mutex_unlock(&fan_mutex);
5541         return rc;
5542 }
5543
5544 static int fan_set_disable(void)
5545 {
5546         int rc;
5547
5548         if (!fan_control_allowed)
5549                 return -EPERM;
5550
5551         if (mutex_lock_interruptible(&fan_mutex))
5552                 return -ERESTARTSYS;
5553
5554         rc = 0;
5555         switch (fan_control_access_mode) {
5556         case TPACPI_FAN_WR_ACPI_FANS:
5557         case TPACPI_FAN_WR_TPEC:
5558                 if (!acpi_ec_write(fan_status_offset, 0x00))
5559                         rc = -EIO;
5560                 else {
5561                         fan_control_desired_level = 0;
5562                         tp_features.fan_ctrl_status_undef = 0;
5563                 }
5564                 break;
5565
5566         case TPACPI_FAN_WR_ACPI_SFAN:
5567                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
5568                         rc = -EIO;
5569                 else
5570                         fan_control_desired_level = 0;
5571                 break;
5572
5573         default:
5574                 rc = -ENXIO;
5575         }
5576
5577
5578         mutex_unlock(&fan_mutex);
5579         return rc;
5580 }
5581
5582 static int fan_set_speed(int speed)
5583 {
5584         int rc;
5585
5586         if (!fan_control_allowed)
5587                 return -EPERM;
5588
5589         if (mutex_lock_interruptible(&fan_mutex))
5590                 return -ERESTARTSYS;
5591
5592         rc = 0;
5593         switch (fan_control_access_mode) {
5594         case TPACPI_FAN_WR_ACPI_FANS:
5595                 if (speed >= 0 && speed <= 65535) {
5596                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
5597                                         speed, speed, speed))
5598                                 rc = -EIO;
5599                 } else
5600                         rc = -EINVAL;
5601                 break;
5602
5603         default:
5604                 rc = -ENXIO;
5605         }
5606
5607         mutex_unlock(&fan_mutex);
5608         return rc;
5609 }
5610
5611 static void fan_watchdog_reset(void)
5612 {
5613         static int fan_watchdog_active;
5614
5615         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
5616                 return;
5617
5618         if (fan_watchdog_active)
5619                 cancel_delayed_work(&fan_watchdog_task);
5620
5621         if (fan_watchdog_maxinterval > 0 &&
5622             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
5623                 fan_watchdog_active = 1;
5624                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
5625                                 msecs_to_jiffies(fan_watchdog_maxinterval
5626                                                  * 1000))) {
5627                         printk(TPACPI_ERR
5628                                "failed to queue the fan watchdog, "
5629                                "watchdog will not trigger\n");
5630                 }
5631         } else
5632                 fan_watchdog_active = 0;
5633 }
5634
5635 static void fan_watchdog_fire(struct work_struct *ignored)
5636 {
5637         int rc;
5638
5639         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
5640                 return;
5641
5642         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
5643         rc = fan_set_enable();
5644         if (rc < 0) {
5645                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
5646                         "will try again later...\n", -rc);
5647                 /* reschedule for later */
5648                 fan_watchdog_reset();
5649         }
5650 }
5651
5652 /*
5653  * SYSFS fan layout: hwmon compatible (device)
5654  *
5655  * pwm*_enable:
5656  *      0: "disengaged" mode
5657  *      1: manual mode
5658  *      2: native EC "auto" mode (recommended, hardware default)
5659  *
5660  * pwm*: set speed in manual mode, ignored otherwise.
5661  *      0 is level 0; 255 is level 7. Intermediate points done with linear
5662  *      interpolation.
5663  *
5664  * fan*_input: tachometer reading, RPM
5665  *
5666  *
5667  * SYSFS fan layout: extensions
5668  *
5669  * fan_watchdog (driver):
5670  *      fan watchdog interval in seconds, 0 disables (default), max 120
5671  */
5672
5673 /* sysfs fan pwm1_enable ----------------------------------------------- */
5674 static ssize_t fan_pwm1_enable_show(struct device *dev,
5675                                     struct device_attribute *attr,
5676                                     char *buf)
5677 {
5678         int res, mode;
5679         u8 status;
5680
5681         res = fan_get_status_safe(&status);
5682         if (res)
5683                 return res;
5684
5685         if (unlikely(tp_features.fan_ctrl_status_undef)) {
5686                 if (status != fan_control_initial_status) {
5687                         tp_features.fan_ctrl_status_undef = 0;
5688                 } else {
5689                         /* Return most likely status. In fact, it
5690                          * might be the only possible status */
5691                         status = TP_EC_FAN_AUTO;
5692                 }
5693         }
5694
5695         if (status & TP_EC_FAN_FULLSPEED) {
5696                 mode = 0;
5697         } else if (status & TP_EC_FAN_AUTO) {
5698                 mode = 2;
5699         } else
5700                 mode = 1;
5701
5702         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
5703 }
5704
5705 static ssize_t fan_pwm1_enable_store(struct device *dev,
5706                                      struct device_attribute *attr,
5707                                      const char *buf, size_t count)
5708 {
5709         unsigned long t;
5710         int res, level;
5711
5712         if (parse_strtoul(buf, 2, &t))
5713                 return -EINVAL;
5714
5715         switch (t) {
5716         case 0:
5717                 level = TP_EC_FAN_FULLSPEED;
5718                 break;
5719         case 1:
5720                 level = TPACPI_FAN_LAST_LEVEL;
5721                 break;
5722         case 2:
5723                 level = TP_EC_FAN_AUTO;
5724                 break;
5725         case 3:
5726                 /* reserved for software-controlled auto mode */
5727                 return -ENOSYS;
5728         default:
5729                 return -EINVAL;
5730         }
5731
5732         res = fan_set_level_safe(level);
5733         if (res == -ENXIO)
5734                 return -EINVAL;
5735         else if (res < 0)
5736                 return res;
5737
5738         fan_watchdog_reset();
5739
5740         return count;
5741 }
5742
5743 static struct device_attribute dev_attr_fan_pwm1_enable =
5744         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
5745                 fan_pwm1_enable_show, fan_pwm1_enable_store);
5746
5747 /* sysfs fan pwm1 ------------------------------------------------------ */
5748 static ssize_t fan_pwm1_show(struct device *dev,
5749                              struct device_attribute *attr,
5750                              char *buf)
5751 {
5752         int res;
5753         u8 status;
5754
5755         res = fan_get_status_safe(&status);
5756         if (res)
5757                 return res;
5758
5759         if (unlikely(tp_features.fan_ctrl_status_undef)) {
5760                 if (status != fan_control_initial_status) {
5761                         tp_features.fan_ctrl_status_undef = 0;
5762                 } else {
5763                         status = TP_EC_FAN_AUTO;
5764                 }
5765         }
5766
5767         if ((status &
5768              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
5769                 status = fan_control_desired_level;
5770
5771         if (status > 7)
5772                 status = 7;
5773
5774         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
5775 }
5776
5777 static ssize_t fan_pwm1_store(struct device *dev,
5778                               struct device_attribute *attr,
5779                               const char *buf, size_t count)
5780 {
5781         unsigned long s;
5782         int rc;
5783         u8 status, newlevel;
5784
5785         if (parse_strtoul(buf, 255, &s))
5786                 return -EINVAL;
5787
5788         /* scale down from 0-255 to 0-7 */
5789         newlevel = (s >> 5) & 0x07;
5790
5791         if (mutex_lock_interruptible(&fan_mutex))
5792                 return -ERESTARTSYS;
5793
5794         rc = fan_get_status(&status);
5795         if (!rc && (status &
5796                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
5797                 rc = fan_set_level(newlevel);
5798                 if (rc == -ENXIO)
5799                         rc = -EINVAL;
5800                 else if (!rc) {
5801                         fan_update_desired_level(newlevel);
5802                         fan_watchdog_reset();
5803                 }
5804         }
5805
5806         mutex_unlock(&fan_mutex);
5807         return (rc)? rc : count;
5808 }
5809
5810 static struct device_attribute dev_attr_fan_pwm1 =
5811         __ATTR(pwm1, S_IWUSR | S_IRUGO,
5812                 fan_pwm1_show, fan_pwm1_store);
5813
5814 /* sysfs fan fan1_input ------------------------------------------------ */
5815 static ssize_t fan_fan1_input_show(struct device *dev,
5816                            struct device_attribute *attr,
5817                            char *buf)
5818 {
5819         int res;
5820         unsigned int speed;
5821
5822         res = fan_get_speed(&speed);
5823         if (res < 0)
5824                 return res;
5825
5826         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
5827 }
5828
5829 static struct device_attribute dev_attr_fan_fan1_input =
5830         __ATTR(fan1_input, S_IRUGO,
5831                 fan_fan1_input_show, NULL);
5832
5833 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
5834 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
5835                                      char *buf)
5836 {
5837         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
5838 }
5839
5840 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
5841                                       const char *buf, size_t count)
5842 {
5843         unsigned long t;
5844
5845         if (parse_strtoul(buf, 120, &t))
5846                 return -EINVAL;
5847
5848         if (!fan_control_allowed)
5849                 return -EPERM;
5850
5851         fan_watchdog_maxinterval = t;
5852         fan_watchdog_reset();
5853
5854         return count;
5855 }
5856
5857 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
5858                 fan_fan_watchdog_show, fan_fan_watchdog_store);
5859
5860 /* --------------------------------------------------------------------- */
5861 static struct attribute *fan_attributes[] = {
5862         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
5863         &dev_attr_fan_fan1_input.attr,
5864         NULL
5865 };
5866
5867 static const struct attribute_group fan_attr_group = {
5868         .attrs = fan_attributes,
5869 };
5870
5871 static int __init fan_init(struct ibm_init_struct *iibm)
5872 {
5873         int rc;
5874
5875         vdbg_printk(TPACPI_DBG_INIT, "initializing fan subdriver\n");
5876
5877         mutex_init(&fan_mutex);
5878         fan_status_access_mode = TPACPI_FAN_NONE;
5879         fan_control_access_mode = TPACPI_FAN_WR_NONE;
5880         fan_control_commands = 0;
5881         fan_watchdog_maxinterval = 0;
5882         tp_features.fan_ctrl_status_undef = 0;
5883         fan_control_desired_level = 7;
5884
5885         TPACPI_ACPIHANDLE_INIT(fans);
5886         TPACPI_ACPIHANDLE_INIT(gfan);
5887         TPACPI_ACPIHANDLE_INIT(sfan);
5888
5889         if (gfan_handle) {
5890                 /* 570, 600e/x, 770e, 770x */
5891                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
5892         } else {
5893                 /* all other ThinkPads: note that even old-style
5894                  * ThinkPad ECs supports the fan control register */
5895                 if (likely(acpi_ec_read(fan_status_offset,
5896                                         &fan_control_initial_status))) {
5897                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
5898
5899                         /* In some ThinkPads, neither the EC nor the ACPI
5900                          * DSDT initialize the fan status, and it ends up
5901                          * being set to 0x07 when it *could* be either
5902                          * 0x07 or 0x80.
5903                          *
5904                          * Enable for TP-1Y (T43), TP-78 (R51e),
5905                          * TP-76 (R52), TP-70 (T43, R52), which are known
5906                          * to be buggy. */
5907                         if (fan_control_initial_status == 0x07) {
5908                                 switch (thinkpad_id.ec_model) {
5909                                 case 0x5931: /* TP-1Y */
5910                                 case 0x3837: /* TP-78 */
5911                                 case 0x3637: /* TP-76 */
5912                                 case 0x3037: /* TP-70 */
5913                                         printk(TPACPI_NOTICE
5914                                                "fan_init: initial fan status "
5915                                                "is unknown, assuming it is "
5916                                                "in auto mode\n");
5917                                         tp_features.fan_ctrl_status_undef = 1;
5918                                         ;;
5919                                 }
5920                         }
5921                 } else {
5922                         printk(TPACPI_ERR
5923                                "ThinkPad ACPI EC access misbehaving, "
5924                                "fan status and control unavailable\n");
5925                         return 1;
5926                 }
5927         }
5928
5929         if (sfan_handle) {
5930                 /* 570, 770x-JL */
5931                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
5932                 fan_control_commands |=
5933                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
5934         } else {
5935                 if (!gfan_handle) {
5936                         /* gfan without sfan means no fan control */
5937                         /* all other models implement TP EC 0x2f control */
5938
5939                         if (fans_handle) {
5940                                 /* X31, X40, X41 */
5941                                 fan_control_access_mode =
5942                                     TPACPI_FAN_WR_ACPI_FANS;
5943                                 fan_control_commands |=
5944                                     TPACPI_FAN_CMD_SPEED |
5945                                     TPACPI_FAN_CMD_LEVEL |
5946                                     TPACPI_FAN_CMD_ENABLE;
5947                         } else {
5948                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
5949                                 fan_control_commands |=
5950                                     TPACPI_FAN_CMD_LEVEL |
5951                                     TPACPI_FAN_CMD_ENABLE;
5952                         }
5953                 }
5954         }
5955
5956         vdbg_printk(TPACPI_DBG_INIT, "fan is %s, modes %d, %d\n",
5957                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
5958                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
5959                 fan_status_access_mode, fan_control_access_mode);
5960
5961         /* fan control master switch */
5962         if (!fan_control_allowed) {
5963                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
5964                 fan_control_commands = 0;
5965                 dbg_printk(TPACPI_DBG_INIT,
5966                            "fan control features disabled by parameter\n");
5967         }
5968
5969         /* update fan_control_desired_level */
5970         if (fan_status_access_mode != TPACPI_FAN_NONE)
5971                 fan_get_status_safe(NULL);
5972
5973         if (fan_status_access_mode != TPACPI_FAN_NONE ||
5974             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
5975                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5976                                          &fan_attr_group);
5977                 if (rc < 0)
5978                         return rc;
5979
5980                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
5981                                         &driver_attr_fan_watchdog);
5982                 if (rc < 0) {
5983                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5984                                         &fan_attr_group);
5985                         return rc;
5986                 }
5987                 return 0;
5988         } else
5989                 return 1;
5990 }
5991
5992 static void fan_exit(void)
5993 {
5994         vdbg_printk(TPACPI_DBG_EXIT,
5995                     "cancelling any pending fan watchdog tasks\n");
5996
5997         /* FIXME: can we really do this unconditionally? */
5998         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
5999         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
6000                            &driver_attr_fan_watchdog);
6001
6002         cancel_delayed_work(&fan_watchdog_task);
6003         flush_workqueue(tpacpi_wq);
6004 }
6005
6006 static void fan_suspend(pm_message_t state)
6007 {
6008         int rc;
6009
6010         if (!fan_control_allowed)
6011                 return;
6012
6013         /* Store fan status in cache */
6014         fan_control_resume_level = 0;
6015         rc = fan_get_status_safe(&fan_control_resume_level);
6016         if (rc < 0)
6017                 printk(TPACPI_NOTICE
6018                         "failed to read fan level for later "
6019                         "restore during resume: %d\n", rc);
6020
6021         /* if it is undefined, don't attempt to restore it.
6022          * KEEP THIS LAST */
6023         if (tp_features.fan_ctrl_status_undef)
6024                 fan_control_resume_level = 0;
6025 }
6026
6027 static void fan_resume(void)
6028 {
6029         u8 current_level = 7;
6030         bool do_set = false;
6031         int rc;
6032
6033         /* DSDT *always* updates status on resume */
6034         tp_features.fan_ctrl_status_undef = 0;
6035
6036         if (!fan_control_allowed ||
6037             !fan_control_resume_level ||
6038             (fan_get_status_safe(&current_level) < 0))
6039                 return;
6040
6041         switch (fan_control_access_mode) {
6042         case TPACPI_FAN_WR_ACPI_SFAN:
6043                 /* never decrease fan level */
6044                 do_set = (fan_control_resume_level > current_level);
6045                 break;
6046         case TPACPI_FAN_WR_ACPI_FANS:
6047         case TPACPI_FAN_WR_TPEC:
6048                 /* never decrease fan level, scale is:
6049                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
6050                  *
6051                  * We expect the firmware to set either 7 or AUTO, but we
6052                  * handle FULLSPEED out of paranoia.
6053                  *
6054                  * So, we can safely only restore FULLSPEED or 7, anything
6055                  * else could slow the fan.  Restoring AUTO is useless, at
6056                  * best that's exactly what the DSDT already set (it is the
6057                  * slower it uses).
6058                  *
6059                  * Always keep in mind that the DSDT *will* have set the
6060                  * fans to what the vendor supposes is the best level.  We
6061                  * muck with it only to speed the fan up.
6062                  */
6063                 if (fan_control_resume_level != 7 &&
6064                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
6065                         return;
6066                 else
6067                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
6068                                  (current_level != fan_control_resume_level);
6069                 break;
6070         default:
6071                 return;
6072         }
6073         if (do_set) {
6074                 printk(TPACPI_NOTICE
6075                         "restoring fan level to 0x%02x\n",
6076                         fan_control_resume_level);
6077                 rc = fan_set_level_safe(fan_control_resume_level);
6078                 if (rc < 0)
6079                         printk(TPACPI_NOTICE
6080                                 "failed to restore fan level: %d\n", rc);
6081         }
6082 }
6083
6084 static int fan_read(char *p)
6085 {
6086         int len = 0;
6087         int rc;
6088         u8 status;
6089         unsigned int speed = 0;
6090
6091         switch (fan_status_access_mode) {
6092         case TPACPI_FAN_RD_ACPI_GFAN:
6093                 /* 570, 600e/x, 770e, 770x */
6094                 rc = fan_get_status_safe(&status);
6095                 if (rc < 0)
6096                         return rc;
6097
6098                 len += sprintf(p + len, "status:\t\t%s\n"
6099                                "level:\t\t%d\n",
6100                                (status != 0) ? "enabled" : "disabled", status);
6101                 break;
6102
6103         case TPACPI_FAN_RD_TPEC:
6104                 /* all except 570, 600e/x, 770e, 770x */
6105                 rc = fan_get_status_safe(&status);
6106                 if (rc < 0)
6107                         return rc;
6108
6109                 if (unlikely(tp_features.fan_ctrl_status_undef)) {
6110                         if (status != fan_control_initial_status)
6111                                 tp_features.fan_ctrl_status_undef = 0;
6112                         else
6113                                 /* Return most likely status. In fact, it
6114                                  * might be the only possible status */
6115                                 status = TP_EC_FAN_AUTO;
6116                 }
6117
6118                 len += sprintf(p + len, "status:\t\t%s\n",
6119                                (status != 0) ? "enabled" : "disabled");
6120
6121                 rc = fan_get_speed(&speed);
6122                 if (rc < 0)
6123                         return rc;
6124
6125                 len += sprintf(p + len, "speed:\t\t%d\n", speed);
6126
6127                 if (status & TP_EC_FAN_FULLSPEED)
6128                         /* Disengaged mode takes precedence */
6129                         len += sprintf(p + len, "level:\t\tdisengaged\n");
6130                 else if (status & TP_EC_FAN_AUTO)
6131                         len += sprintf(p + len, "level:\t\tauto\n");
6132                 else
6133                         len += sprintf(p + len, "level:\t\t%d\n", status);
6134                 break;
6135
6136         case TPACPI_FAN_NONE:
6137         default:
6138                 len += sprintf(p + len, "status:\t\tnot supported\n");
6139         }
6140
6141         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
6142                 len += sprintf(p + len, "commands:\tlevel <level>");
6143
6144                 switch (fan_control_access_mode) {
6145                 case TPACPI_FAN_WR_ACPI_SFAN:
6146                         len += sprintf(p + len, " (<level> is 0-7)\n");
6147                         break;
6148
6149                 default:
6150                         len += sprintf(p + len, " (<level> is 0-7, "
6151                                        "auto, disengaged, full-speed)\n");
6152                         break;
6153                 }
6154         }
6155
6156         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
6157                 len += sprintf(p + len, "commands:\tenable, disable\n"
6158                                "commands:\twatchdog <timeout> (<timeout> "
6159                                "is 0 (off), 1-120 (seconds))\n");
6160
6161         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
6162                 len += sprintf(p + len, "commands:\tspeed <speed>"
6163                                " (<speed> is 0-65535)\n");
6164
6165         return len;
6166 }
6167
6168 static int fan_write_cmd_level(const char *cmd, int *rc)
6169 {
6170         int level;
6171
6172         if (strlencmp(cmd, "level auto") == 0)
6173                 level = TP_EC_FAN_AUTO;
6174         else if ((strlencmp(cmd, "level disengaged") == 0) |
6175                         (strlencmp(cmd, "level full-speed") == 0))
6176                 level = TP_EC_FAN_FULLSPEED;
6177         else if (sscanf(cmd, "level %d", &level) != 1)
6178                 return 0;
6179
6180         *rc = fan_set_level_safe(level);
6181         if (*rc == -ENXIO)
6182                 printk(TPACPI_ERR "level command accepted for unsupported "
6183                        "access mode %d", fan_control_access_mode);
6184
6185         return 1;
6186 }
6187
6188 static int fan_write_cmd_enable(const char *cmd, int *rc)
6189 {
6190         if (strlencmp(cmd, "enable") != 0)
6191                 return 0;
6192
6193         *rc = fan_set_enable();
6194         if (*rc == -ENXIO)
6195                 printk(TPACPI_ERR "enable command accepted for unsupported "
6196                        "access mode %d", fan_control_access_mode);
6197
6198         return 1;
6199 }
6200
6201 static int fan_write_cmd_disable(const char *cmd, int *rc)
6202 {
6203         if (strlencmp(cmd, "disable") != 0)
6204                 return 0;
6205
6206         *rc = fan_set_disable();
6207         if (*rc == -ENXIO)
6208                 printk(TPACPI_ERR "disable command accepted for unsupported "
6209                        "access mode %d", fan_control_access_mode);
6210
6211         return 1;
6212 }
6213
6214 static int fan_write_cmd_speed(const char *cmd, int *rc)
6215 {
6216         int speed;
6217
6218         /* TODO:
6219          * Support speed <low> <medium> <high> ? */
6220
6221         if (sscanf(cmd, "speed %d", &speed) != 1)
6222                 return 0;
6223
6224         *rc = fan_set_speed(speed);
6225         if (*rc == -ENXIO)
6226                 printk(TPACPI_ERR "speed command accepted for unsupported "
6227                        "access mode %d", fan_control_access_mode);
6228
6229         return 1;
6230 }
6231
6232 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
6233 {
6234         int interval;
6235
6236         if (sscanf(cmd, "watchdog %d", &interval) != 1)
6237                 return 0;
6238
6239         if (interval < 0 || interval > 120)
6240                 *rc = -EINVAL;
6241         else
6242                 fan_watchdog_maxinterval = interval;
6243
6244         return 1;
6245 }
6246
6247 static int fan_write(char *buf)
6248 {
6249         char *cmd;
6250         int rc = 0;
6251
6252         while (!rc && (cmd = next_cmd(&buf))) {
6253                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
6254                       fan_write_cmd_level(cmd, &rc)) &&
6255                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
6256                       (fan_write_cmd_enable(cmd, &rc) ||
6257                        fan_write_cmd_disable(cmd, &rc) ||
6258                        fan_write_cmd_watchdog(cmd, &rc))) &&
6259                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
6260                       fan_write_cmd_speed(cmd, &rc))
6261                     )
6262                         rc = -EINVAL;
6263                 else if (!rc)
6264                         fan_watchdog_reset();
6265         }
6266
6267         return rc;
6268 }
6269
6270 static struct ibm_struct fan_driver_data = {
6271         .name = "fan",
6272         .read = fan_read,
6273         .write = fan_write,
6274         .exit = fan_exit,
6275         .suspend = fan_suspend,
6276         .resume = fan_resume,
6277 };
6278
6279 /****************************************************************************
6280  ****************************************************************************
6281  *
6282  * Infrastructure
6283  *
6284  ****************************************************************************
6285  ****************************************************************************/
6286
6287 /* sysfs name ---------------------------------------------------------- */
6288 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
6289                            struct device_attribute *attr,
6290                            char *buf)
6291 {
6292         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
6293 }
6294
6295 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
6296         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
6297
6298 /* --------------------------------------------------------------------- */
6299
6300 /* /proc support */
6301 static struct proc_dir_entry *proc_dir;
6302
6303 /*
6304  * Module and infrastructure proble, init and exit handling
6305  */
6306
6307 static int force_load;
6308
6309 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
6310 static const char * __init str_supported(int is_supported)
6311 {
6312         static char text_unsupported[] __initdata = "not supported";
6313
6314         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
6315 }
6316 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
6317
6318 static void ibm_exit(struct ibm_struct *ibm)
6319 {
6320         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
6321
6322         list_del_init(&ibm->all_drivers);
6323
6324         if (ibm->flags.acpi_notify_installed) {
6325                 dbg_printk(TPACPI_DBG_EXIT,
6326                         "%s: acpi_remove_notify_handler\n", ibm->name);
6327                 BUG_ON(!ibm->acpi);
6328                 acpi_remove_notify_handler(*ibm->acpi->handle,
6329                                            ibm->acpi->type,
6330                                            dispatch_acpi_notify);
6331                 ibm->flags.acpi_notify_installed = 0;
6332                 ibm->flags.acpi_notify_installed = 0;
6333         }
6334
6335         if (ibm->flags.proc_created) {
6336                 dbg_printk(TPACPI_DBG_EXIT,
6337                         "%s: remove_proc_entry\n", ibm->name);
6338                 remove_proc_entry(ibm->name, proc_dir);
6339                 ibm->flags.proc_created = 0;
6340         }
6341
6342         if (ibm->flags.acpi_driver_registered) {
6343                 dbg_printk(TPACPI_DBG_EXIT,
6344                         "%s: acpi_bus_unregister_driver\n", ibm->name);
6345                 BUG_ON(!ibm->acpi);
6346                 acpi_bus_unregister_driver(ibm->acpi->driver);
6347                 kfree(ibm->acpi->driver);
6348                 ibm->acpi->driver = NULL;
6349                 ibm->flags.acpi_driver_registered = 0;
6350         }
6351
6352         if (ibm->flags.init_called && ibm->exit) {
6353                 ibm->exit();
6354                 ibm->flags.init_called = 0;
6355         }
6356
6357         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
6358 }
6359
6360 static int __init ibm_init(struct ibm_init_struct *iibm)
6361 {
6362         int ret;
6363         struct ibm_struct *ibm = iibm->data;
6364         struct proc_dir_entry *entry;
6365
6366         BUG_ON(ibm == NULL);
6367
6368         INIT_LIST_HEAD(&ibm->all_drivers);
6369
6370         if (ibm->flags.experimental && !experimental)
6371                 return 0;
6372
6373         dbg_printk(TPACPI_DBG_INIT,
6374                 "probing for %s\n", ibm->name);
6375
6376         if (iibm->init) {
6377                 ret = iibm->init(iibm);
6378                 if (ret > 0)
6379                         return 0;       /* probe failed */
6380                 if (ret)
6381                         return ret;
6382
6383                 ibm->flags.init_called = 1;
6384         }
6385
6386         if (ibm->acpi) {
6387                 if (ibm->acpi->hid) {
6388                         ret = register_tpacpi_subdriver(ibm);
6389                         if (ret)
6390                                 goto err_out;
6391                 }
6392
6393                 if (ibm->acpi->notify) {
6394                         ret = setup_acpi_notify(ibm);
6395                         if (ret == -ENODEV) {
6396                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
6397                                         ibm->name);
6398                                 ret = 0;
6399                                 goto err_out;
6400                         }
6401                         if (ret < 0)
6402                                 goto err_out;
6403                 }
6404         }
6405
6406         dbg_printk(TPACPI_DBG_INIT,
6407                 "%s installed\n", ibm->name);
6408
6409         if (ibm->read) {
6410                 entry = create_proc_entry(ibm->name,
6411                                           S_IFREG | S_IRUGO | S_IWUSR,
6412                                           proc_dir);
6413                 if (!entry) {
6414                         printk(TPACPI_ERR "unable to create proc entry %s\n",
6415                                ibm->name);
6416                         ret = -ENODEV;
6417                         goto err_out;
6418                 }
6419                 entry->owner = THIS_MODULE;
6420                 entry->data = ibm;
6421                 entry->read_proc = &dispatch_procfs_read;
6422                 if (ibm->write)
6423                         entry->write_proc = &dispatch_procfs_write;
6424                 ibm->flags.proc_created = 1;
6425         }
6426
6427         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
6428
6429         return 0;
6430
6431 err_out:
6432         dbg_printk(TPACPI_DBG_INIT,
6433                 "%s: at error exit path with result %d\n",
6434                 ibm->name, ret);
6435
6436         ibm_exit(ibm);
6437         return (ret < 0)? ret : 0;
6438 }
6439
6440 /* Probing */
6441
6442 /* returns 0 - probe ok, or < 0 - probe error.
6443  * Probe ok doesn't mean thinkpad found.
6444  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
6445 static int __must_check __init get_thinkpad_model_data(
6446                                                 struct thinkpad_id_data *tp)
6447 {
6448         const struct dmi_device *dev = NULL;
6449         char ec_fw_string[18];
6450         char const *s;
6451
6452         if (!tp)
6453                 return -EINVAL;
6454
6455         memset(tp, 0, sizeof(*tp));
6456
6457         if (dmi_name_in_vendors("IBM"))
6458                 tp->vendor = PCI_VENDOR_ID_IBM;
6459         else if (dmi_name_in_vendors("LENOVO"))
6460                 tp->vendor = PCI_VENDOR_ID_LENOVO;
6461         else
6462                 return 0;
6463
6464         s = dmi_get_system_info(DMI_BIOS_VERSION);
6465         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
6466         if (s && !tp->bios_version_str)
6467                 return -ENOMEM;
6468         if (!tp->bios_version_str)
6469                 return 0;
6470         tp->bios_model = tp->bios_version_str[0]
6471                          | (tp->bios_version_str[1] << 8);
6472
6473         /*
6474          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
6475          * X32 or newer, all Z series;  Some models must have an
6476          * up-to-date BIOS or they will not be detected.
6477          *
6478          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
6479          */
6480         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
6481                 if (sscanf(dev->name,
6482                            "IBM ThinkPad Embedded Controller -[%17c",
6483                            ec_fw_string) == 1) {
6484                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
6485                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
6486
6487                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
6488                         if (!tp->ec_version_str)
6489                                 return -ENOMEM;
6490                         tp->ec_model = ec_fw_string[0]
6491                                         | (ec_fw_string[1] << 8);
6492                         break;
6493                 }
6494         }
6495
6496         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
6497         if (s && !strnicmp(s, "ThinkPad", 8)) {
6498                 tp->model_str = kstrdup(s, GFP_KERNEL);
6499                 if (!tp->model_str)
6500                         return -ENOMEM;
6501         }
6502
6503         s = dmi_get_system_info(DMI_PRODUCT_NAME);
6504         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
6505         if (s && !tp->nummodel_str)
6506                 return -ENOMEM;
6507
6508         return 0;
6509 }
6510
6511 static int __init probe_for_thinkpad(void)
6512 {
6513         int is_thinkpad;
6514
6515         if (acpi_disabled)
6516                 return -ENODEV;
6517
6518         /*
6519          * Non-ancient models have better DMI tagging, but very old models
6520          * don't.
6521          */
6522         is_thinkpad = (thinkpad_id.model_str != NULL);
6523
6524         /* ec is required because many other handles are relative to it */
6525         TPACPI_ACPIHANDLE_INIT(ec);
6526         if (!ec_handle) {
6527                 if (is_thinkpad)
6528                         printk(TPACPI_ERR
6529                                 "Not yet supported ThinkPad detected!\n");
6530                 return -ENODEV;
6531         }
6532
6533         /*
6534          * Risks a regression on very old machines, but reduces potential
6535          * false positives a damn great deal
6536          */
6537         if (!is_thinkpad)
6538                 is_thinkpad = (thinkpad_id.vendor == PCI_VENDOR_ID_IBM);
6539
6540         if (!is_thinkpad && !force_load)
6541                 return -ENODEV;
6542
6543         return 0;
6544 }
6545
6546
6547 /* Module init, exit, parameters */
6548
6549 static struct ibm_init_struct ibms_init[] __initdata = {
6550         {
6551                 .init = thinkpad_acpi_driver_init,
6552                 .data = &thinkpad_acpi_driver_data,
6553         },
6554         {
6555                 .init = hotkey_init,
6556                 .data = &hotkey_driver_data,
6557         },
6558         {
6559                 .init = bluetooth_init,
6560                 .data = &bluetooth_driver_data,
6561         },
6562         {
6563                 .init = wan_init,
6564                 .data = &wan_driver_data,
6565         },
6566 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
6567         {
6568                 .init = video_init,
6569                 .data = &video_driver_data,
6570         },
6571 #endif
6572         {
6573                 .init = light_init,
6574                 .data = &light_driver_data,
6575         },
6576 #ifdef CONFIG_THINKPAD_ACPI_DOCK
6577         {
6578                 .init = dock_init,
6579                 .data = &dock_driver_data[0],
6580         },
6581         {
6582                 .init = dock_init2,
6583                 .data = &dock_driver_data[1],
6584         },
6585 #endif
6586 #ifdef CONFIG_THINKPAD_ACPI_BAY
6587         {
6588                 .init = bay_init,
6589                 .data = &bay_driver_data,
6590         },
6591 #endif
6592         {
6593                 .init = cmos_init,
6594                 .data = &cmos_driver_data,
6595         },
6596         {
6597                 .init = led_init,
6598                 .data = &led_driver_data,
6599         },
6600         {
6601                 .init = beep_init,
6602                 .data = &beep_driver_data,
6603         },
6604         {
6605                 .init = thermal_init,
6606                 .data = &thermal_driver_data,
6607         },
6608         {
6609                 .data = &ecdump_driver_data,
6610         },
6611         {
6612                 .init = brightness_init,
6613                 .data = &brightness_driver_data,
6614         },
6615         {
6616                 .data = &volume_driver_data,
6617         },
6618         {
6619                 .init = fan_init,
6620                 .data = &fan_driver_data,
6621         },
6622 };
6623
6624 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
6625 {
6626         unsigned int i;
6627         struct ibm_struct *ibm;
6628
6629         if (!kp || !kp->name || !val)
6630                 return -EINVAL;
6631
6632         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
6633                 ibm = ibms_init[i].data;
6634                 WARN_ON(ibm == NULL);
6635
6636                 if (!ibm || !ibm->name)
6637                         continue;
6638
6639                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
6640                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
6641                                 return -ENOSPC;
6642                         strcpy(ibms_init[i].param, val);
6643                         strcat(ibms_init[i].param, ",");
6644                         return 0;
6645                 }
6646         }
6647
6648         return -EINVAL;
6649 }
6650
6651 module_param(experimental, int, 0);
6652 MODULE_PARM_DESC(experimental,
6653                  "Enables experimental features when non-zero");
6654
6655 module_param_named(debug, dbg_level, uint, 0);
6656 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
6657
6658 module_param(force_load, bool, 0);
6659 MODULE_PARM_DESC(force_load,
6660                  "Attempts to load the driver even on a "
6661                  "mis-identified ThinkPad when true");
6662
6663 module_param_named(fan_control, fan_control_allowed, bool, 0);
6664 MODULE_PARM_DESC(fan_control,
6665                  "Enables setting fan parameters features when true");
6666
6667 module_param_named(brightness_mode, brightness_mode, int, 0);
6668 MODULE_PARM_DESC(brightness_mode,
6669                  "Selects brightness control strategy: "
6670                  "0=auto, 1=EC, 2=CMOS, 3=both");
6671
6672 module_param(brightness_enable, uint, 0);
6673 MODULE_PARM_DESC(brightness_enable,
6674                  "Enables backlight control when 1, disables when 0");
6675
6676 module_param(hotkey_report_mode, uint, 0);
6677 MODULE_PARM_DESC(hotkey_report_mode,
6678                  "used for backwards compatibility with userspace, "
6679                  "see documentation");
6680
6681 #define TPACPI_PARAM(feature) \
6682         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
6683         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
6684                          "at module load, see documentation")
6685
6686 TPACPI_PARAM(hotkey);
6687 TPACPI_PARAM(bluetooth);
6688 TPACPI_PARAM(video);
6689 TPACPI_PARAM(light);
6690 #ifdef CONFIG_THINKPAD_ACPI_DOCK
6691 TPACPI_PARAM(dock);
6692 #endif
6693 #ifdef CONFIG_THINKPAD_ACPI_BAY
6694 TPACPI_PARAM(bay);
6695 #endif /* CONFIG_THINKPAD_ACPI_BAY */
6696 TPACPI_PARAM(cmos);
6697 TPACPI_PARAM(led);
6698 TPACPI_PARAM(beep);
6699 TPACPI_PARAM(ecdump);
6700 TPACPI_PARAM(brightness);
6701 TPACPI_PARAM(volume);
6702 TPACPI_PARAM(fan);
6703
6704 static void thinkpad_acpi_module_exit(void)
6705 {
6706         struct ibm_struct *ibm, *itmp;
6707
6708         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
6709
6710         list_for_each_entry_safe_reverse(ibm, itmp,
6711                                          &tpacpi_all_drivers,
6712                                          all_drivers) {
6713                 ibm_exit(ibm);
6714         }
6715
6716         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
6717
6718         if (tpacpi_inputdev) {
6719                 if (tp_features.input_device_registered)
6720                         input_unregister_device(tpacpi_inputdev);
6721                 else
6722                         input_free_device(tpacpi_inputdev);
6723         }
6724
6725         if (tpacpi_hwmon)
6726                 hwmon_device_unregister(tpacpi_hwmon);
6727
6728         if (tp_features.sensors_pdev_attrs_registered)
6729                 device_remove_file(&tpacpi_sensors_pdev->dev,
6730                                    &dev_attr_thinkpad_acpi_pdev_name);
6731         if (tpacpi_sensors_pdev)
6732                 platform_device_unregister(tpacpi_sensors_pdev);
6733         if (tpacpi_pdev)
6734                 platform_device_unregister(tpacpi_pdev);
6735
6736         if (tp_features.sensors_pdrv_attrs_registered)
6737                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
6738         if (tp_features.platform_drv_attrs_registered)
6739                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
6740
6741         if (tp_features.sensors_pdrv_registered)
6742                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
6743
6744         if (tp_features.platform_drv_registered)
6745                 platform_driver_unregister(&tpacpi_pdriver);
6746
6747         if (proc_dir)
6748                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
6749
6750         if (tpacpi_wq)
6751                 destroy_workqueue(tpacpi_wq);
6752
6753         kfree(thinkpad_id.bios_version_str);
6754         kfree(thinkpad_id.ec_version_str);
6755         kfree(thinkpad_id.model_str);
6756 }
6757
6758
6759 static int __init thinkpad_acpi_module_init(void)
6760 {
6761         int ret, i;
6762
6763         tpacpi_lifecycle = TPACPI_LIFE_INIT;
6764
6765         /* Parameter checking */
6766         if (hotkey_report_mode > 2)
6767                 return -EINVAL;
6768
6769         /* Driver-level probe */
6770
6771         ret = get_thinkpad_model_data(&thinkpad_id);
6772         if (ret) {
6773                 printk(TPACPI_ERR
6774                         "unable to get DMI data: %d\n", ret);
6775                 thinkpad_acpi_module_exit();
6776                 return ret;
6777         }
6778         ret = probe_for_thinkpad();
6779         if (ret) {
6780                 thinkpad_acpi_module_exit();
6781                 return ret;
6782         }
6783
6784         /* Driver initialization */
6785
6786         TPACPI_ACPIHANDLE_INIT(ecrd);
6787         TPACPI_ACPIHANDLE_INIT(ecwr);
6788
6789         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
6790         if (!tpacpi_wq) {
6791                 thinkpad_acpi_module_exit();
6792                 return -ENOMEM;
6793         }
6794
6795         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
6796         if (!proc_dir) {
6797                 printk(TPACPI_ERR
6798                        "unable to create proc dir " TPACPI_PROC_DIR);
6799                 thinkpad_acpi_module_exit();
6800                 return -ENODEV;
6801         }
6802         proc_dir->owner = THIS_MODULE;
6803
6804         ret = platform_driver_register(&tpacpi_pdriver);
6805         if (ret) {
6806                 printk(TPACPI_ERR
6807                        "unable to register main platform driver\n");
6808                 thinkpad_acpi_module_exit();
6809                 return ret;
6810         }
6811         tp_features.platform_drv_registered = 1;
6812
6813         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
6814         if (ret) {
6815                 printk(TPACPI_ERR
6816                        "unable to register hwmon platform driver\n");
6817                 thinkpad_acpi_module_exit();
6818                 return ret;
6819         }
6820         tp_features.sensors_pdrv_registered = 1;
6821
6822         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
6823         if (!ret) {
6824                 tp_features.platform_drv_attrs_registered = 1;
6825                 ret = tpacpi_create_driver_attributes(
6826                                         &tpacpi_hwmon_pdriver.driver);
6827         }
6828         if (ret) {
6829                 printk(TPACPI_ERR
6830                        "unable to create sysfs driver attributes\n");
6831                 thinkpad_acpi_module_exit();
6832                 return ret;
6833         }
6834         tp_features.sensors_pdrv_attrs_registered = 1;
6835
6836
6837         /* Device initialization */
6838         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
6839                                                         NULL, 0);
6840         if (IS_ERR(tpacpi_pdev)) {
6841                 ret = PTR_ERR(tpacpi_pdev);
6842                 tpacpi_pdev = NULL;
6843                 printk(TPACPI_ERR "unable to register platform device\n");
6844                 thinkpad_acpi_module_exit();
6845                 return ret;
6846         }
6847         tpacpi_sensors_pdev = platform_device_register_simple(
6848                                                 TPACPI_HWMON_DRVR_NAME,
6849                                                 -1, NULL, 0);
6850         if (IS_ERR(tpacpi_sensors_pdev)) {
6851                 ret = PTR_ERR(tpacpi_sensors_pdev);
6852                 tpacpi_sensors_pdev = NULL;
6853                 printk(TPACPI_ERR
6854                        "unable to register hwmon platform device\n");
6855                 thinkpad_acpi_module_exit();
6856                 return ret;
6857         }
6858         ret = device_create_file(&tpacpi_sensors_pdev->dev,
6859                                  &dev_attr_thinkpad_acpi_pdev_name);
6860         if (ret) {
6861                 printk(TPACPI_ERR
6862                        "unable to create sysfs hwmon device attributes\n");
6863                 thinkpad_acpi_module_exit();
6864                 return ret;
6865         }
6866         tp_features.sensors_pdev_attrs_registered = 1;
6867         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
6868         if (IS_ERR(tpacpi_hwmon)) {
6869                 ret = PTR_ERR(tpacpi_hwmon);
6870                 tpacpi_hwmon = NULL;
6871                 printk(TPACPI_ERR "unable to register hwmon device\n");
6872                 thinkpad_acpi_module_exit();
6873                 return ret;
6874         }
6875         mutex_init(&tpacpi_inputdev_send_mutex);
6876         tpacpi_inputdev = input_allocate_device();
6877         if (!tpacpi_inputdev) {
6878                 printk(TPACPI_ERR "unable to allocate input device\n");
6879                 thinkpad_acpi_module_exit();
6880                 return -ENOMEM;
6881         } else {
6882                 /* Prepare input device, but don't register */
6883                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
6884                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
6885                 tpacpi_inputdev->id.bustype = BUS_HOST;
6886                 tpacpi_inputdev->id.vendor = (thinkpad_id.vendor) ?
6887                                                 thinkpad_id.vendor :
6888                                                 PCI_VENDOR_ID_IBM;
6889                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
6890                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
6891         }
6892         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
6893                 ret = ibm_init(&ibms_init[i]);
6894                 if (ret >= 0 && *ibms_init[i].param)
6895                         ret = ibms_init[i].data->write(ibms_init[i].param);
6896                 if (ret < 0) {
6897                         thinkpad_acpi_module_exit();
6898                         return ret;
6899                 }
6900         }
6901         ret = input_register_device(tpacpi_inputdev);
6902         if (ret < 0) {
6903                 printk(TPACPI_ERR "unable to register input device\n");
6904                 thinkpad_acpi_module_exit();
6905                 return ret;
6906         } else {
6907                 tp_features.input_device_registered = 1;
6908         }
6909
6910         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
6911         return 0;
6912 }
6913
6914 /* Please remove this in year 2009 */
6915 MODULE_ALIAS("ibm_acpi");
6916
6917 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
6918
6919 /*
6920  * DMI matching for module autoloading
6921  *
6922  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
6923  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
6924  *
6925  * Only models listed in thinkwiki will be supported, so add yours
6926  * if it is not there yet.
6927  */
6928 #define IBM_BIOS_MODULE_ALIAS(__type) \
6929         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW")
6930
6931 /* Non-ancient thinkpads */
6932 MODULE_ALIAS("dmi:bvnIBM:*:svnIBM:*:pvrThinkPad*:rvnIBM:*");
6933 MODULE_ALIAS("dmi:bvnLENOVO:*:svnLENOVO:*:pvrThinkPad*:rvnLENOVO:*");
6934
6935 /* Ancient thinkpad BIOSes have to be identified by
6936  * BIOS type or model number, and there are far less
6937  * BIOS types than model numbers... */
6938 IBM_BIOS_MODULE_ALIAS("I[B,D,H,I,M,N,O,T,W,V,Y,Z]");
6939 IBM_BIOS_MODULE_ALIAS("1[0,3,6,8,A-G,I,K,M-P,S,T]");
6940 IBM_BIOS_MODULE_ALIAS("K[U,X-Z]");
6941
6942 MODULE_AUTHOR("Borislav Deianov, Henrique de Moraes Holschuh");
6943 MODULE_DESCRIPTION(TPACPI_DESC);
6944 MODULE_VERSION(TPACPI_VERSION);
6945 MODULE_LICENSE("GPL");
6946
6947 module_init(thinkpad_acpi_module_init);
6948 module_exit(thinkpad_acpi_module_exit);