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