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