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