thinkpad-acpi: let other subdrivers know backlight level range
[pandora-kernel.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                         }
6278                 } else {
6279                         if (brightness_enable > 1) {
6280                                 printk(TPACPI_NOTICE
6281                                        "Standard ACPI backlight interface not "
6282                                        "available, thinkpad_acpi native "
6283                                        "brightness control enabled\n");
6284                         }
6285                 }
6286         }
6287
6288         if (!brightness_enable) {
6289                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6290                            "brightness support disabled by "
6291                            "module parameter\n");
6292                 return 1;
6293         }
6294
6295         /*
6296          * Check for module parameter bogosity, note that we
6297          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6298          * able to detect "unspecified"
6299          */
6300         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6301                 return -EINVAL;
6302
6303         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6304         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6305             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6306                 if (quirks & TPACPI_BRGHT_Q_EC)
6307                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6308                 else
6309                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6310
6311                 dbg_printk(TPACPI_DBG_BRGHT,
6312                            "driver auto-selected brightness_mode=%d\n",
6313                            brightness_mode);
6314         }
6315
6316         /* Safety */
6317         if (!tpacpi_is_ibm() &&
6318             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6319              brightness_mode == TPACPI_BRGHT_MODE_EC))
6320                 return -EINVAL;
6321
6322         if (tpacpi_brightness_get_raw(&b) < 0)
6323                 return 1;
6324
6325         memset(&props, 0, sizeof(struct backlight_properties));
6326         props.max_brightness = bright_maxlvl;
6327         props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6328         ibm_backlight_device = backlight_device_register(TPACPI_BACKLIGHT_DEV_NAME,
6329                                                          NULL, NULL,
6330                                                          &ibm_backlight_data,
6331                                                          &props);
6332         if (IS_ERR(ibm_backlight_device)) {
6333                 int rc = PTR_ERR(ibm_backlight_device);
6334                 ibm_backlight_device = NULL;
6335                 printk(TPACPI_ERR "Could not register backlight device\n");
6336                 return rc;
6337         }
6338         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6339                         "brightness is supported\n");
6340
6341         if (quirks & TPACPI_BRGHT_Q_ASK) {
6342                 printk(TPACPI_NOTICE
6343                         "brightness: will use unverified default: "
6344                         "brightness_mode=%d\n", brightness_mode);
6345                 printk(TPACPI_NOTICE
6346                         "brightness: please report to %s whether it works well "
6347                         "or not on your ThinkPad\n", TPACPI_MAIL);
6348         }
6349
6350         backlight_update_status(ibm_backlight_device);
6351
6352         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6353                         "brightness: registering brightness hotkeys "
6354                         "as change notification\n");
6355         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
6356                                 | TP_ACPI_HKEY_BRGHTUP_MASK
6357                                 | TP_ACPI_HKEY_BRGHTDWN_MASK);;
6358         return 0;
6359 }
6360
6361 static void brightness_suspend(pm_message_t state)
6362 {
6363         tpacpi_brightness_checkpoint_nvram();
6364 }
6365
6366 static void brightness_shutdown(void)
6367 {
6368         tpacpi_brightness_checkpoint_nvram();
6369 }
6370
6371 static void brightness_exit(void)
6372 {
6373         if (ibm_backlight_device) {
6374                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6375                             "calling backlight_device_unregister()\n");
6376                 backlight_device_unregister(ibm_backlight_device);
6377         }
6378
6379         tpacpi_brightness_checkpoint_nvram();
6380 }
6381
6382 static int brightness_read(struct seq_file *m)
6383 {
6384         int level;
6385
6386         level = brightness_get(NULL);
6387         if (level < 0) {
6388                 seq_printf(m, "level:\t\tunreadable\n");
6389         } else {
6390                 seq_printf(m, "level:\t\t%d\n", level);
6391                 seq_printf(m, "commands:\tup, down\n");
6392                 seq_printf(m, "commands:\tlevel <level> (<level> is 0-%d)\n",
6393                                bright_maxlvl);
6394         }
6395
6396         return 0;
6397 }
6398
6399 static int brightness_write(char *buf)
6400 {
6401         int level;
6402         int rc;
6403         char *cmd;
6404
6405         level = brightness_get(NULL);
6406         if (level < 0)
6407                 return level;
6408
6409         while ((cmd = next_cmd(&buf))) {
6410                 if (strlencmp(cmd, "up") == 0) {
6411                         if (level < bright_maxlvl)
6412                                 level++;
6413                 } else if (strlencmp(cmd, "down") == 0) {
6414                         if (level > 0)
6415                                 level--;
6416                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6417                            level >= 0 && level <= bright_maxlvl) {
6418                         /* new level set */
6419                 } else
6420                         return -EINVAL;
6421         }
6422
6423         tpacpi_disclose_usertask("procfs brightness",
6424                         "set level to %d\n", level);
6425
6426         /*
6427          * Now we know what the final level should be, so we try to set it.
6428          * Doing it this way makes the syscall restartable in case of EINTR
6429          */
6430         rc = brightness_set(level);
6431         if (!rc && ibm_backlight_device)
6432                 backlight_force_update(ibm_backlight_device,
6433                                         BACKLIGHT_UPDATE_SYSFS);
6434         return (rc == -EINTR)? -ERESTARTSYS : rc;
6435 }
6436
6437 static struct ibm_struct brightness_driver_data = {
6438         .name = "brightness",
6439         .read = brightness_read,
6440         .write = brightness_write,
6441         .exit = brightness_exit,
6442         .suspend = brightness_suspend,
6443         .shutdown = brightness_shutdown,
6444 };
6445
6446 /*************************************************************************
6447  * Volume subdriver
6448  */
6449
6450 /*
6451  * IBM ThinkPads have a simple volume controller with MUTE gating.
6452  * Very early Lenovo ThinkPads follow the IBM ThinkPad spec.
6453  *
6454  * Since the *61 series (and probably also the later *60 series), Lenovo
6455  * ThinkPads only implement the MUTE gate.
6456  *
6457  * EC register 0x30
6458  *   Bit 6: MUTE (1 mutes sound)
6459  *   Bit 3-0: Volume
6460  *   Other bits should be zero as far as we know.
6461  *
6462  * This is also stored in CMOS NVRAM, byte 0x60, bit 6 (MUTE), and
6463  * bits 3-0 (volume).  Other bits in NVRAM may have other functions,
6464  * such as bit 7 which is used to detect repeated presses of MUTE,
6465  * and we leave them unchanged.
6466  */
6467
6468 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
6469
6470 #define TPACPI_ALSA_DRVNAME  "ThinkPad EC"
6471 #define TPACPI_ALSA_SHRTNAME "ThinkPad Console Audio Control"
6472 #define TPACPI_ALSA_MIXERNAME TPACPI_ALSA_SHRTNAME
6473
6474 static int alsa_index = ~((1 << (SNDRV_CARDS - 3)) - 1); /* last three slots */
6475 static char *alsa_id = "ThinkPadEC";
6476 static int alsa_enable = SNDRV_DEFAULT_ENABLE1;
6477
6478 struct tpacpi_alsa_data {
6479         struct snd_card *card;
6480         struct snd_ctl_elem_id *ctl_mute_id;
6481         struct snd_ctl_elem_id *ctl_vol_id;
6482 };
6483
6484 static struct snd_card *alsa_card;
6485
6486 enum {
6487         TP_EC_AUDIO = 0x30,
6488
6489         /* TP_EC_AUDIO bits */
6490         TP_EC_AUDIO_MUTESW = 6,
6491
6492         /* TP_EC_AUDIO bitmasks */
6493         TP_EC_AUDIO_LVL_MSK = 0x0F,
6494         TP_EC_AUDIO_MUTESW_MSK = (1 << TP_EC_AUDIO_MUTESW),
6495
6496         /* Maximum volume */
6497         TP_EC_VOLUME_MAX = 14,
6498 };
6499
6500 enum tpacpi_volume_access_mode {
6501         TPACPI_VOL_MODE_AUTO = 0,       /* Not implemented yet */
6502         TPACPI_VOL_MODE_EC,             /* Pure EC control */
6503         TPACPI_VOL_MODE_UCMS_STEP,      /* UCMS step-based control: N/A */
6504         TPACPI_VOL_MODE_ECNVRAM,        /* EC control w/ NVRAM store */
6505         TPACPI_VOL_MODE_MAX
6506 };
6507
6508 enum tpacpi_volume_capabilities {
6509         TPACPI_VOL_CAP_AUTO = 0,        /* Use white/blacklist */
6510         TPACPI_VOL_CAP_VOLMUTE,         /* Output vol and mute */
6511         TPACPI_VOL_CAP_MUTEONLY,        /* Output mute only */
6512         TPACPI_VOL_CAP_MAX
6513 };
6514
6515 static enum tpacpi_volume_access_mode volume_mode =
6516         TPACPI_VOL_MODE_MAX;
6517
6518 static enum tpacpi_volume_capabilities volume_capabilities;
6519 static int volume_control_allowed;
6520
6521 /*
6522  * Used to syncronize writers to TP_EC_AUDIO and
6523  * TP_NVRAM_ADDR_MIXER, as we need to do read-modify-write
6524  */
6525 static struct mutex volume_mutex;
6526
6527 static void tpacpi_volume_checkpoint_nvram(void)
6528 {
6529         u8 lec = 0;
6530         u8 b_nvram;
6531         u8 ec_mask;
6532
6533         if (volume_mode != TPACPI_VOL_MODE_ECNVRAM)
6534                 return;
6535         if (!volume_control_allowed)
6536                 return;
6537
6538         vdbg_printk(TPACPI_DBG_MIXER,
6539                 "trying to checkpoint mixer state to NVRAM...\n");
6540
6541         if (tp_features.mixer_no_level_control)
6542                 ec_mask = TP_EC_AUDIO_MUTESW_MSK;
6543         else
6544                 ec_mask = TP_EC_AUDIO_MUTESW_MSK | TP_EC_AUDIO_LVL_MSK;
6545
6546         if (mutex_lock_killable(&volume_mutex) < 0)
6547                 return;
6548
6549         if (unlikely(!acpi_ec_read(TP_EC_AUDIO, &lec)))
6550                 goto unlock;
6551         lec &= ec_mask;
6552         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
6553
6554         if (lec != (b_nvram & ec_mask)) {
6555                 /* NVRAM needs update */
6556                 b_nvram &= ~ec_mask;
6557                 b_nvram |= lec;
6558                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_MIXER);
6559                 dbg_printk(TPACPI_DBG_MIXER,
6560                            "updated NVRAM mixer status to 0x%02x (0x%02x)\n",
6561                            (unsigned int) lec, (unsigned int) b_nvram);
6562         } else {
6563                 vdbg_printk(TPACPI_DBG_MIXER,
6564                            "NVRAM mixer status already is 0x%02x (0x%02x)\n",
6565                            (unsigned int) lec, (unsigned int) b_nvram);
6566         }
6567
6568 unlock:
6569         mutex_unlock(&volume_mutex);
6570 }
6571
6572 static int volume_get_status_ec(u8 *status)
6573 {
6574         u8 s;
6575
6576         if (!acpi_ec_read(TP_EC_AUDIO, &s))
6577                 return -EIO;
6578
6579         *status = s;
6580
6581         dbg_printk(TPACPI_DBG_MIXER, "status 0x%02x\n", s);
6582
6583         return 0;
6584 }
6585
6586 static int volume_get_status(u8 *status)
6587 {
6588         return volume_get_status_ec(status);
6589 }
6590
6591 static int volume_set_status_ec(const u8 status)
6592 {
6593         if (!acpi_ec_write(TP_EC_AUDIO, status))
6594                 return -EIO;
6595
6596         dbg_printk(TPACPI_DBG_MIXER, "set EC mixer to 0x%02x\n", status);
6597
6598         return 0;
6599 }
6600
6601 static int volume_set_status(const u8 status)
6602 {
6603         return volume_set_status_ec(status);
6604 }
6605
6606 /* returns < 0 on error, 0 on no change, 1 on change */
6607 static int __volume_set_mute_ec(const bool mute)
6608 {
6609         int rc;
6610         u8 s, n;
6611
6612         if (mutex_lock_killable(&volume_mutex) < 0)
6613                 return -EINTR;
6614
6615         rc = volume_get_status_ec(&s);
6616         if (rc)
6617                 goto unlock;
6618
6619         n = (mute) ? s | TP_EC_AUDIO_MUTESW_MSK :
6620                      s & ~TP_EC_AUDIO_MUTESW_MSK;
6621
6622         if (n != s) {
6623                 rc = volume_set_status_ec(n);
6624                 if (!rc)
6625                         rc = 1;
6626         }
6627
6628 unlock:
6629         mutex_unlock(&volume_mutex);
6630         return rc;
6631 }
6632
6633 static int volume_alsa_set_mute(const bool mute)
6634 {
6635         dbg_printk(TPACPI_DBG_MIXER, "ALSA: trying to %smute\n",
6636                    (mute) ? "" : "un");
6637         return __volume_set_mute_ec(mute);
6638 }
6639
6640 static int volume_set_mute(const bool mute)
6641 {
6642         int rc;
6643
6644         dbg_printk(TPACPI_DBG_MIXER, "trying to %smute\n",
6645                    (mute) ? "" : "un");
6646
6647         rc = __volume_set_mute_ec(mute);
6648         return (rc < 0) ? rc : 0;
6649 }
6650
6651 /* returns < 0 on error, 0 on no change, 1 on change */
6652 static int __volume_set_volume_ec(const u8 vol)
6653 {
6654         int rc;
6655         u8 s, n;
6656
6657         if (vol > TP_EC_VOLUME_MAX)
6658                 return -EINVAL;
6659
6660         if (mutex_lock_killable(&volume_mutex) < 0)
6661                 return -EINTR;
6662
6663         rc = volume_get_status_ec(&s);
6664         if (rc)
6665                 goto unlock;
6666
6667         n = (s & ~TP_EC_AUDIO_LVL_MSK) | vol;
6668
6669         if (n != s) {
6670                 rc = volume_set_status_ec(n);
6671                 if (!rc)
6672                         rc = 1;
6673         }
6674
6675 unlock:
6676         mutex_unlock(&volume_mutex);
6677         return rc;
6678 }
6679
6680 static int volume_alsa_set_volume(const u8 vol)
6681 {
6682         dbg_printk(TPACPI_DBG_MIXER,
6683                    "ALSA: trying to set volume level to %hu\n", vol);
6684         return __volume_set_volume_ec(vol);
6685 }
6686
6687 static void volume_alsa_notify_change(void)
6688 {
6689         struct tpacpi_alsa_data *d;
6690
6691         if (alsa_card && alsa_card->private_data) {
6692                 d = alsa_card->private_data;
6693                 if (d->ctl_mute_id)
6694                         snd_ctl_notify(alsa_card,
6695                                         SNDRV_CTL_EVENT_MASK_VALUE,
6696                                         d->ctl_mute_id);
6697                 if (d->ctl_vol_id)
6698                         snd_ctl_notify(alsa_card,
6699                                         SNDRV_CTL_EVENT_MASK_VALUE,
6700                                         d->ctl_vol_id);
6701         }
6702 }
6703
6704 static int volume_alsa_vol_info(struct snd_kcontrol *kcontrol,
6705                                 struct snd_ctl_elem_info *uinfo)
6706 {
6707         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
6708         uinfo->count = 1;
6709         uinfo->value.integer.min = 0;
6710         uinfo->value.integer.max = TP_EC_VOLUME_MAX;
6711         return 0;
6712 }
6713
6714 static int volume_alsa_vol_get(struct snd_kcontrol *kcontrol,
6715                                 struct snd_ctl_elem_value *ucontrol)
6716 {
6717         u8 s;
6718         int rc;
6719
6720         rc = volume_get_status(&s);
6721         if (rc < 0)
6722                 return rc;
6723
6724         ucontrol->value.integer.value[0] = s & TP_EC_AUDIO_LVL_MSK;
6725         return 0;
6726 }
6727
6728 static int volume_alsa_vol_put(struct snd_kcontrol *kcontrol,
6729                                 struct snd_ctl_elem_value *ucontrol)
6730 {
6731         return volume_alsa_set_volume(ucontrol->value.integer.value[0]);
6732 }
6733
6734 #define volume_alsa_mute_info snd_ctl_boolean_mono_info
6735
6736 static int volume_alsa_mute_get(struct snd_kcontrol *kcontrol,
6737                                 struct snd_ctl_elem_value *ucontrol)
6738 {
6739         u8 s;
6740         int rc;
6741
6742         rc = volume_get_status(&s);
6743         if (rc < 0)
6744                 return rc;
6745
6746         ucontrol->value.integer.value[0] =
6747                                 (s & TP_EC_AUDIO_MUTESW_MSK) ? 0 : 1;
6748         return 0;
6749 }
6750
6751 static int volume_alsa_mute_put(struct snd_kcontrol *kcontrol,
6752                                 struct snd_ctl_elem_value *ucontrol)
6753 {
6754         return volume_alsa_set_mute(!ucontrol->value.integer.value[0]);
6755 }
6756
6757 static struct snd_kcontrol_new volume_alsa_control_vol __devinitdata = {
6758         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
6759         .name = "Console Playback Volume",
6760         .index = 0,
6761         .access = SNDRV_CTL_ELEM_ACCESS_READ,
6762         .info = volume_alsa_vol_info,
6763         .get = volume_alsa_vol_get,
6764 };
6765
6766 static struct snd_kcontrol_new volume_alsa_control_mute __devinitdata = {
6767         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
6768         .name = "Console Playback Switch",
6769         .index = 0,
6770         .access = SNDRV_CTL_ELEM_ACCESS_READ,
6771         .info = volume_alsa_mute_info,
6772         .get = volume_alsa_mute_get,
6773 };
6774
6775 static void volume_suspend(pm_message_t state)
6776 {
6777         tpacpi_volume_checkpoint_nvram();
6778 }
6779
6780 static void volume_resume(void)
6781 {
6782         volume_alsa_notify_change();
6783 }
6784
6785 static void volume_shutdown(void)
6786 {
6787         tpacpi_volume_checkpoint_nvram();
6788 }
6789
6790 static void volume_exit(void)
6791 {
6792         if (alsa_card) {
6793                 snd_card_free(alsa_card);
6794                 alsa_card = NULL;
6795         }
6796
6797         tpacpi_volume_checkpoint_nvram();
6798 }
6799
6800 static int __init volume_create_alsa_mixer(void)
6801 {
6802         struct snd_card *card;
6803         struct tpacpi_alsa_data *data;
6804         struct snd_kcontrol *ctl_vol;
6805         struct snd_kcontrol *ctl_mute;
6806         int rc;
6807
6808         rc = snd_card_create(alsa_index, alsa_id, THIS_MODULE,
6809                             sizeof(struct tpacpi_alsa_data), &card);
6810         if (rc < 0 || !card) {
6811                 printk(TPACPI_ERR
6812                         "Failed to create ALSA card structures: %d\n", rc);
6813                 return 1;
6814         }
6815
6816         BUG_ON(!card->private_data);
6817         data = card->private_data;
6818         data->card = card;
6819
6820         strlcpy(card->driver, TPACPI_ALSA_DRVNAME,
6821                 sizeof(card->driver));
6822         strlcpy(card->shortname, TPACPI_ALSA_SHRTNAME,
6823                 sizeof(card->shortname));
6824         snprintf(card->mixername, sizeof(card->mixername), "ThinkPad EC %s",
6825                  (thinkpad_id.ec_version_str) ?
6826                         thinkpad_id.ec_version_str : "(unknown)");
6827         snprintf(card->longname, sizeof(card->longname),
6828                  "%s at EC reg 0x%02x, fw %s", card->shortname, TP_EC_AUDIO,
6829                  (thinkpad_id.ec_version_str) ?
6830                         thinkpad_id.ec_version_str : "unknown");
6831
6832         if (volume_control_allowed) {
6833                 volume_alsa_control_vol.put = volume_alsa_vol_put;
6834                 volume_alsa_control_vol.access =
6835                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
6836
6837                 volume_alsa_control_mute.put = volume_alsa_mute_put;
6838                 volume_alsa_control_mute.access =
6839                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
6840         }
6841
6842         if (!tp_features.mixer_no_level_control) {
6843                 ctl_vol = snd_ctl_new1(&volume_alsa_control_vol, NULL);
6844                 rc = snd_ctl_add(card, ctl_vol);
6845                 if (rc < 0) {
6846                         printk(TPACPI_ERR
6847                                 "Failed to create ALSA volume control: %d\n",
6848                                 rc);
6849                         goto err_exit;
6850                 }
6851                 data->ctl_vol_id = &ctl_vol->id;
6852         }
6853
6854         ctl_mute = snd_ctl_new1(&volume_alsa_control_mute, NULL);
6855         rc = snd_ctl_add(card, ctl_mute);
6856         if (rc < 0) {
6857                 printk(TPACPI_ERR "Failed to create ALSA mute control: %d\n",
6858                         rc);
6859                 goto err_exit;
6860         }
6861         data->ctl_mute_id = &ctl_mute->id;
6862
6863         snd_card_set_dev(card, &tpacpi_pdev->dev);
6864         rc = snd_card_register(card);
6865         if (rc < 0) {
6866                 printk(TPACPI_ERR "Failed to register ALSA card: %d\n", rc);
6867                 goto err_exit;
6868         }
6869
6870         alsa_card = card;
6871         return 0;
6872
6873 err_exit:
6874         snd_card_free(card);
6875         return 1;
6876 }
6877
6878 #define TPACPI_VOL_Q_MUTEONLY   0x0001  /* Mute-only control available */
6879 #define TPACPI_VOL_Q_LEVEL      0x0002  /* Volume control available */
6880
6881 static const struct tpacpi_quirk volume_quirk_table[] __initconst = {
6882         /* Whitelist volume level on all IBM by default */
6883         { .vendor = PCI_VENDOR_ID_IBM,
6884           .bios   = TPACPI_MATCH_ANY,
6885           .ec     = TPACPI_MATCH_ANY,
6886           .quirks = TPACPI_VOL_Q_LEVEL },
6887
6888         /* Lenovo models with volume control (needs confirmation) */
6889         TPACPI_QEC_LNV('7', 'C', TPACPI_VOL_Q_LEVEL), /* R60/i */
6890         TPACPI_QEC_LNV('7', 'E', TPACPI_VOL_Q_LEVEL), /* R60e/i */
6891         TPACPI_QEC_LNV('7', '9', TPACPI_VOL_Q_LEVEL), /* T60/p */
6892         TPACPI_QEC_LNV('7', 'B', TPACPI_VOL_Q_LEVEL), /* X60/s */
6893         TPACPI_QEC_LNV('7', 'J', TPACPI_VOL_Q_LEVEL), /* X60t */
6894         TPACPI_QEC_LNV('7', '7', TPACPI_VOL_Q_LEVEL), /* Z60 */
6895         TPACPI_QEC_LNV('7', 'F', TPACPI_VOL_Q_LEVEL), /* Z61 */
6896
6897         /* Whitelist mute-only on all Lenovo by default */
6898         { .vendor = PCI_VENDOR_ID_LENOVO,
6899           .bios   = TPACPI_MATCH_ANY,
6900           .ec     = TPACPI_MATCH_ANY,
6901           .quirks = TPACPI_VOL_Q_MUTEONLY }
6902 };
6903
6904 static int __init volume_init(struct ibm_init_struct *iibm)
6905 {
6906         unsigned long quirks;
6907         int rc;
6908
6909         vdbg_printk(TPACPI_DBG_INIT, "initializing volume subdriver\n");
6910
6911         mutex_init(&volume_mutex);
6912
6913         /*
6914          * Check for module parameter bogosity, note that we
6915          * init volume_mode to TPACPI_VOL_MODE_MAX in order to be
6916          * able to detect "unspecified"
6917          */
6918         if (volume_mode > TPACPI_VOL_MODE_MAX)
6919                 return -EINVAL;
6920
6921         if (volume_mode == TPACPI_VOL_MODE_UCMS_STEP) {
6922                 printk(TPACPI_ERR
6923                         "UCMS step volume mode not implemented, "
6924                         "please contact %s\n", TPACPI_MAIL);
6925                 return 1;
6926         }
6927
6928         if (volume_capabilities >= TPACPI_VOL_CAP_MAX)
6929                 return -EINVAL;
6930
6931         /*
6932          * The ALSA mixer is our primary interface.
6933          * When disabled, don't install the subdriver at all
6934          */
6935         if (!alsa_enable) {
6936                 vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6937                             "ALSA mixer disabled by parameter, "
6938                             "not loading volume subdriver...\n");
6939                 return 1;
6940         }
6941
6942         quirks = tpacpi_check_quirks(volume_quirk_table,
6943                                      ARRAY_SIZE(volume_quirk_table));
6944
6945         switch (volume_capabilities) {
6946         case TPACPI_VOL_CAP_AUTO:
6947                 if (quirks & TPACPI_VOL_Q_MUTEONLY)
6948                         tp_features.mixer_no_level_control = 1;
6949                 else if (quirks & TPACPI_VOL_Q_LEVEL)
6950                         tp_features.mixer_no_level_control = 0;
6951                 else
6952                         return 1; /* no mixer */
6953                 break;
6954         case TPACPI_VOL_CAP_VOLMUTE:
6955                 tp_features.mixer_no_level_control = 0;
6956                 break;
6957         case TPACPI_VOL_CAP_MUTEONLY:
6958                 tp_features.mixer_no_level_control = 1;
6959                 break;
6960         default:
6961                 return 1;
6962         }
6963
6964         if (volume_capabilities != TPACPI_VOL_CAP_AUTO)
6965                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6966                                 "using user-supplied volume_capabilities=%d\n",
6967                                 volume_capabilities);
6968
6969         if (volume_mode == TPACPI_VOL_MODE_AUTO ||
6970             volume_mode == TPACPI_VOL_MODE_MAX) {
6971                 volume_mode = TPACPI_VOL_MODE_ECNVRAM;
6972
6973                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6974                                 "driver auto-selected volume_mode=%d\n",
6975                                 volume_mode);
6976         } else {
6977                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6978                                 "using user-supplied volume_mode=%d\n",
6979                                 volume_mode);
6980         }
6981
6982         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6983                         "mute is supported, volume control is %s\n",
6984                         str_supported(!tp_features.mixer_no_level_control));
6985
6986         rc = volume_create_alsa_mixer();
6987         if (rc) {
6988                 printk(TPACPI_ERR
6989                         "Could not create the ALSA mixer interface\n");
6990                 return rc;
6991         }
6992
6993         printk(TPACPI_INFO
6994                 "Console audio control enabled, mode: %s\n",
6995                 (volume_control_allowed) ?
6996                         "override (read/write)" :
6997                         "monitor (read only)");
6998
6999         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7000                 "registering volume hotkeys as change notification\n");
7001         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
7002                         | TP_ACPI_HKEY_VOLUP_MASK
7003                         | TP_ACPI_HKEY_VOLDWN_MASK
7004                         | TP_ACPI_HKEY_MUTE_MASK);
7005
7006         return 0;
7007 }
7008
7009 static int volume_read(struct seq_file *m)
7010 {
7011         u8 status;
7012
7013         if (volume_get_status(&status) < 0) {
7014                 seq_printf(m, "level:\t\tunreadable\n");
7015         } else {
7016                 if (tp_features.mixer_no_level_control)
7017                         seq_printf(m, "level:\t\tunsupported\n");
7018                 else
7019                         seq_printf(m, "level:\t\t%d\n",
7020                                         status & TP_EC_AUDIO_LVL_MSK);
7021
7022                 seq_printf(m, "mute:\t\t%s\n",
7023                                 onoff(status, TP_EC_AUDIO_MUTESW));
7024
7025                 if (volume_control_allowed) {
7026                         seq_printf(m, "commands:\tunmute, mute\n");
7027                         if (!tp_features.mixer_no_level_control) {
7028                                 seq_printf(m,
7029                                                "commands:\tup, down\n");
7030                                 seq_printf(m,
7031                                                "commands:\tlevel <level>"
7032                                                " (<level> is 0-%d)\n",
7033                                                TP_EC_VOLUME_MAX);
7034                         }
7035                 }
7036         }
7037
7038         return 0;
7039 }
7040
7041 static int volume_write(char *buf)
7042 {
7043         u8 s;
7044         u8 new_level, new_mute;
7045         int l;
7046         char *cmd;
7047         int rc;
7048
7049         /*
7050          * We do allow volume control at driver startup, so that the
7051          * user can set initial state through the volume=... parameter hack.
7052          */
7053         if (!volume_control_allowed && tpacpi_lifecycle != TPACPI_LIFE_INIT) {
7054                 if (unlikely(!tp_warned.volume_ctrl_forbidden)) {
7055                         tp_warned.volume_ctrl_forbidden = 1;
7056                         printk(TPACPI_NOTICE
7057                                 "Console audio control in monitor mode, "
7058                                 "changes are not allowed.\n");
7059                         printk(TPACPI_NOTICE
7060                                 "Use the volume_control=1 module parameter "
7061                                 "to enable volume control\n");
7062                 }
7063                 return -EPERM;
7064         }
7065
7066         rc = volume_get_status(&s);
7067         if (rc < 0)
7068                 return rc;
7069
7070         new_level = s & TP_EC_AUDIO_LVL_MSK;
7071         new_mute  = s & TP_EC_AUDIO_MUTESW_MSK;
7072
7073         while ((cmd = next_cmd(&buf))) {
7074                 if (!tp_features.mixer_no_level_control) {
7075                         if (strlencmp(cmd, "up") == 0) {
7076                                 if (new_mute)
7077                                         new_mute = 0;
7078                                 else if (new_level < TP_EC_VOLUME_MAX)
7079                                         new_level++;
7080                                 continue;
7081                         } else if (strlencmp(cmd, "down") == 0) {
7082                                 if (new_mute)
7083                                         new_mute = 0;
7084                                 else if (new_level > 0)
7085                                         new_level--;
7086                                 continue;
7087                         } else if (sscanf(cmd, "level %u", &l) == 1 &&
7088                                    l >= 0 && l <= TP_EC_VOLUME_MAX) {
7089                                         new_level = l;
7090                                 continue;
7091                         }
7092                 }
7093                 if (strlencmp(cmd, "mute") == 0)
7094                         new_mute = TP_EC_AUDIO_MUTESW_MSK;
7095                 else if (strlencmp(cmd, "unmute") == 0)
7096                         new_mute = 0;
7097                 else
7098                         return -EINVAL;
7099         }
7100
7101         if (tp_features.mixer_no_level_control) {
7102                 tpacpi_disclose_usertask("procfs volume", "%smute\n",
7103                                         new_mute ? "" : "un");
7104                 rc = volume_set_mute(!!new_mute);
7105         } else {
7106                 tpacpi_disclose_usertask("procfs volume",
7107                                         "%smute and set level to %d\n",
7108                                         new_mute ? "" : "un", new_level);
7109                 rc = volume_set_status(new_mute | new_level);
7110         }
7111         volume_alsa_notify_change();
7112
7113         return (rc == -EINTR) ? -ERESTARTSYS : rc;
7114 }
7115
7116 static struct ibm_struct volume_driver_data = {
7117         .name = "volume",
7118         .read = volume_read,
7119         .write = volume_write,
7120         .exit = volume_exit,
7121         .suspend = volume_suspend,
7122         .resume = volume_resume,
7123         .shutdown = volume_shutdown,
7124 };
7125
7126 #else /* !CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7127
7128 #define alsa_card NULL
7129
7130 static void inline volume_alsa_notify_change(void)
7131 {
7132 }
7133
7134 static int __init volume_init(struct ibm_init_struct *iibm)
7135 {
7136         printk(TPACPI_INFO
7137                 "volume: disabled as there is no ALSA support in this kernel\n");
7138
7139         return 1;
7140 }
7141
7142 static struct ibm_struct volume_driver_data = {
7143         .name = "volume",
7144 };
7145
7146 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7147
7148 /*************************************************************************
7149  * Fan subdriver
7150  */
7151
7152 /*
7153  * FAN ACCESS MODES
7154  *
7155  * TPACPI_FAN_RD_ACPI_GFAN:
7156  *      ACPI GFAN method: returns fan level
7157  *
7158  *      see TPACPI_FAN_WR_ACPI_SFAN
7159  *      EC 0x2f (HFSP) not available if GFAN exists
7160  *
7161  * TPACPI_FAN_WR_ACPI_SFAN:
7162  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
7163  *
7164  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
7165  *      it for writing.
7166  *
7167  * TPACPI_FAN_WR_TPEC:
7168  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
7169  *      Supported on almost all ThinkPads
7170  *
7171  *      Fan speed changes of any sort (including those caused by the
7172  *      disengaged mode) are usually done slowly by the firmware as the
7173  *      maximum amount of fan duty cycle change per second seems to be
7174  *      limited.
7175  *
7176  *      Reading is not available if GFAN exists.
7177  *      Writing is not available if SFAN exists.
7178  *
7179  *      Bits
7180  *       7      automatic mode engaged;
7181  *              (default operation mode of the ThinkPad)
7182  *              fan level is ignored in this mode.
7183  *       6      full speed mode (takes precedence over bit 7);
7184  *              not available on all thinkpads.  May disable
7185  *              the tachometer while the fan controller ramps up
7186  *              the speed (which can take up to a few *minutes*).
7187  *              Speeds up fan to 100% duty-cycle, which is far above
7188  *              the standard RPM levels.  It is not impossible that
7189  *              it could cause hardware damage.
7190  *      5-3     unused in some models.  Extra bits for fan level
7191  *              in others, but still useless as all values above
7192  *              7 map to the same speed as level 7 in these models.
7193  *      2-0     fan level (0..7 usually)
7194  *                      0x00 = stop
7195  *                      0x07 = max (set when temperatures critical)
7196  *              Some ThinkPads may have other levels, see
7197  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
7198  *
7199  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
7200  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
7201  *      does so, its initial value is meaningless (0x07).
7202  *
7203  *      For firmware bugs, refer to:
7204  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7205  *
7206  *      ----
7207  *
7208  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
7209  *      Main fan tachometer reading (in RPM)
7210  *
7211  *      This register is present on all ThinkPads with a new-style EC, and
7212  *      it is known not to be present on the A21m/e, and T22, as there is
7213  *      something else in offset 0x84 according to the ACPI DSDT.  Other
7214  *      ThinkPads from this same time period (and earlier) probably lack the
7215  *      tachometer as well.
7216  *
7217  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
7218  *      was never fixed by IBM to report the EC firmware version string
7219  *      probably support the tachometer (like the early X models), so
7220  *      detecting it is quite hard.  We need more data to know for sure.
7221  *
7222  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
7223  *      might result.
7224  *
7225  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
7226  *      mode.
7227  *
7228  *      For firmware bugs, refer to:
7229  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7230  *
7231  *      ----
7232  *
7233  *      ThinkPad EC register 0x31 bit 0 (only on select models)
7234  *
7235  *      When bit 0 of EC register 0x31 is zero, the tachometer registers
7236  *      show the speed of the main fan.  When bit 0 of EC register 0x31
7237  *      is one, the tachometer registers show the speed of the auxiliary
7238  *      fan.
7239  *
7240  *      Fan control seems to affect both fans, regardless of the state
7241  *      of this bit.
7242  *
7243  *      So far, only the firmware for the X60/X61 non-tablet versions
7244  *      seem to support this (firmware TP-7M).
7245  *
7246  * TPACPI_FAN_WR_ACPI_FANS:
7247  *      ThinkPad X31, X40, X41.  Not available in the X60.
7248  *
7249  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
7250  *      high speed.  ACPI DSDT seems to map these three speeds to levels
7251  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
7252  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
7253  *
7254  *      The speeds are stored on handles
7255  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
7256  *
7257  *      There are three default speed sets, accessible as handles:
7258  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
7259  *
7260  *      ACPI DSDT switches which set is in use depending on various
7261  *      factors.
7262  *
7263  *      TPACPI_FAN_WR_TPEC is also available and should be used to
7264  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
7265  *      but the ACPI tables just mention level 7.
7266  */
7267
7268 enum {                                  /* Fan control constants */
7269         fan_status_offset = 0x2f,       /* EC register 0x2f */
7270         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
7271                                          * 0x84 must be read before 0x85 */
7272         fan_select_offset = 0x31,       /* EC register 0x31 (Firmware 7M)
7273                                            bit 0 selects which fan is active */
7274
7275         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
7276         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
7277
7278         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
7279 };
7280
7281 enum fan_status_access_mode {
7282         TPACPI_FAN_NONE = 0,            /* No fan status or control */
7283         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
7284         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
7285 };
7286
7287 enum fan_control_access_mode {
7288         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
7289         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
7290         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
7291         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
7292 };
7293
7294 enum fan_control_commands {
7295         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
7296         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
7297         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
7298                                                  * and also watchdog cmd */
7299 };
7300
7301 static int fan_control_allowed;
7302
7303 static enum fan_status_access_mode fan_status_access_mode;
7304 static enum fan_control_access_mode fan_control_access_mode;
7305 static enum fan_control_commands fan_control_commands;
7306
7307 static u8 fan_control_initial_status;
7308 static u8 fan_control_desired_level;
7309 static u8 fan_control_resume_level;
7310 static int fan_watchdog_maxinterval;
7311
7312 static struct mutex fan_mutex;
7313
7314 static void fan_watchdog_fire(struct work_struct *ignored);
7315 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
7316
7317 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
7318 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
7319            "\\FSPD",            /* 600e/x, 770e, 770x */
7320            );                   /* all others */
7321 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
7322            "JFNS",              /* 770x-JL */
7323            );                   /* all others */
7324
7325 /*
7326  * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the
7327  * HFSP register at boot, so it contains 0x07 but the Thinkpad could
7328  * be in auto mode (0x80).
7329  *
7330  * This is corrected by any write to HFSP either by the driver, or
7331  * by the firmware.
7332  *
7333  * We assume 0x07 really means auto mode while this quirk is active,
7334  * as this is far more likely than the ThinkPad being in level 7,
7335  * which is only used by the firmware during thermal emergencies.
7336  *
7337  * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52),
7338  * TP-70 (T43, R52), which are known to be buggy.
7339  */
7340
7341 static void fan_quirk1_setup(void)
7342 {
7343         if (fan_control_initial_status == 0x07) {
7344                 printk(TPACPI_NOTICE
7345                        "fan_init: initial fan status is unknown, "
7346                        "assuming it is in auto mode\n");
7347                 tp_features.fan_ctrl_status_undef = 1;
7348         }
7349 }
7350
7351 static void fan_quirk1_handle(u8 *fan_status)
7352 {
7353         if (unlikely(tp_features.fan_ctrl_status_undef)) {
7354                 if (*fan_status != fan_control_initial_status) {
7355                         /* something changed the HFSP regisnter since
7356                          * driver init time, so it is not undefined
7357                          * anymore */
7358                         tp_features.fan_ctrl_status_undef = 0;
7359                 } else {
7360                         /* Return most likely status. In fact, it
7361                          * might be the only possible status */
7362                         *fan_status = TP_EC_FAN_AUTO;
7363                 }
7364         }
7365 }
7366
7367 /* Select main fan on X60/X61, NOOP on others */
7368 static bool fan_select_fan1(void)
7369 {
7370         if (tp_features.second_fan) {
7371                 u8 val;
7372
7373                 if (ec_read(fan_select_offset, &val) < 0)
7374                         return false;
7375                 val &= 0xFEU;
7376                 if (ec_write(fan_select_offset, val) < 0)
7377                         return false;
7378         }
7379         return true;
7380 }
7381
7382 /* Select secondary fan on X60/X61 */
7383 static bool fan_select_fan2(void)
7384 {
7385         u8 val;
7386
7387         if (!tp_features.second_fan)
7388                 return false;
7389
7390         if (ec_read(fan_select_offset, &val) < 0)
7391                 return false;
7392         val |= 0x01U;
7393         if (ec_write(fan_select_offset, val) < 0)
7394                 return false;
7395
7396         return true;
7397 }
7398
7399 /*
7400  * Call with fan_mutex held
7401  */
7402 static void fan_update_desired_level(u8 status)
7403 {
7404         if ((status &
7405              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
7406                 if (status > 7)
7407                         fan_control_desired_level = 7;
7408                 else
7409                         fan_control_desired_level = status;
7410         }
7411 }
7412
7413 static int fan_get_status(u8 *status)
7414 {
7415         u8 s;
7416
7417         /* TODO:
7418          * Add TPACPI_FAN_RD_ACPI_FANS ? */
7419
7420         switch (fan_status_access_mode) {
7421         case TPACPI_FAN_RD_ACPI_GFAN:
7422                 /* 570, 600e/x, 770e, 770x */
7423
7424                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
7425                         return -EIO;
7426
7427                 if (likely(status))
7428                         *status = s & 0x07;
7429
7430                 break;
7431
7432         case TPACPI_FAN_RD_TPEC:
7433                 /* all except 570, 600e/x, 770e, 770x */
7434                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
7435                         return -EIO;
7436
7437                 if (likely(status)) {
7438                         *status = s;
7439                         fan_quirk1_handle(status);
7440                 }
7441
7442                 break;
7443
7444         default:
7445                 return -ENXIO;
7446         }
7447
7448         return 0;
7449 }
7450
7451 static int fan_get_status_safe(u8 *status)
7452 {
7453         int rc;
7454         u8 s;
7455
7456         if (mutex_lock_killable(&fan_mutex))
7457                 return -ERESTARTSYS;
7458         rc = fan_get_status(&s);
7459         if (!rc)
7460                 fan_update_desired_level(s);
7461         mutex_unlock(&fan_mutex);
7462
7463         if (status)
7464                 *status = s;
7465
7466         return rc;
7467 }
7468
7469 static int fan_get_speed(unsigned int *speed)
7470 {
7471         u8 hi, lo;
7472
7473         switch (fan_status_access_mode) {
7474         case TPACPI_FAN_RD_TPEC:
7475                 /* all except 570, 600e/x, 770e, 770x */
7476                 if (unlikely(!fan_select_fan1()))
7477                         return -EIO;
7478                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
7479                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
7480                         return -EIO;
7481
7482                 if (likely(speed))
7483                         *speed = (hi << 8) | lo;
7484
7485                 break;
7486
7487         default:
7488                 return -ENXIO;
7489         }
7490
7491         return 0;
7492 }
7493
7494 static int fan2_get_speed(unsigned int *speed)
7495 {
7496         u8 hi, lo;
7497         bool rc;
7498
7499         switch (fan_status_access_mode) {
7500         case TPACPI_FAN_RD_TPEC:
7501                 /* all except 570, 600e/x, 770e, 770x */
7502                 if (unlikely(!fan_select_fan2()))
7503                         return -EIO;
7504                 rc = !acpi_ec_read(fan_rpm_offset, &lo) ||
7505                              !acpi_ec_read(fan_rpm_offset + 1, &hi);
7506                 fan_select_fan1(); /* play it safe */
7507                 if (rc)
7508                         return -EIO;
7509
7510                 if (likely(speed))
7511                         *speed = (hi << 8) | lo;
7512
7513                 break;
7514
7515         default:
7516                 return -ENXIO;
7517         }
7518
7519         return 0;
7520 }
7521
7522 static int fan_set_level(int level)
7523 {
7524         if (!fan_control_allowed)
7525                 return -EPERM;
7526
7527         switch (fan_control_access_mode) {
7528         case TPACPI_FAN_WR_ACPI_SFAN:
7529                 if (level >= 0 && level <= 7) {
7530                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
7531                                 return -EIO;
7532                 } else
7533                         return -EINVAL;
7534                 break;
7535
7536         case TPACPI_FAN_WR_ACPI_FANS:
7537         case TPACPI_FAN_WR_TPEC:
7538                 if (!(level & TP_EC_FAN_AUTO) &&
7539                     !(level & TP_EC_FAN_FULLSPEED) &&
7540                     ((level < 0) || (level > 7)))
7541                         return -EINVAL;
7542
7543                 /* safety net should the EC not support AUTO
7544                  * or FULLSPEED mode bits and just ignore them */
7545                 if (level & TP_EC_FAN_FULLSPEED)
7546                         level |= 7;     /* safety min speed 7 */
7547                 else if (level & TP_EC_FAN_AUTO)
7548                         level |= 4;     /* safety min speed 4 */
7549
7550                 if (!acpi_ec_write(fan_status_offset, level))
7551                         return -EIO;
7552                 else
7553                         tp_features.fan_ctrl_status_undef = 0;
7554                 break;
7555
7556         default:
7557                 return -ENXIO;
7558         }
7559
7560         vdbg_printk(TPACPI_DBG_FAN,
7561                 "fan control: set fan control register to 0x%02x\n", level);
7562         return 0;
7563 }
7564
7565 static int fan_set_level_safe(int level)
7566 {
7567         int rc;
7568
7569         if (!fan_control_allowed)
7570                 return -EPERM;
7571
7572         if (mutex_lock_killable(&fan_mutex))
7573                 return -ERESTARTSYS;
7574
7575         if (level == TPACPI_FAN_LAST_LEVEL)
7576                 level = fan_control_desired_level;
7577
7578         rc = fan_set_level(level);
7579         if (!rc)
7580                 fan_update_desired_level(level);
7581
7582         mutex_unlock(&fan_mutex);
7583         return rc;
7584 }
7585
7586 static int fan_set_enable(void)
7587 {
7588         u8 s;
7589         int rc;
7590
7591         if (!fan_control_allowed)
7592                 return -EPERM;
7593
7594         if (mutex_lock_killable(&fan_mutex))
7595                 return -ERESTARTSYS;
7596
7597         switch (fan_control_access_mode) {
7598         case TPACPI_FAN_WR_ACPI_FANS:
7599         case TPACPI_FAN_WR_TPEC:
7600                 rc = fan_get_status(&s);
7601                 if (rc < 0)
7602                         break;
7603
7604                 /* Don't go out of emergency fan mode */
7605                 if (s != 7) {
7606                         s &= 0x07;
7607                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
7608                 }
7609
7610                 if (!acpi_ec_write(fan_status_offset, s))
7611                         rc = -EIO;
7612                 else {
7613                         tp_features.fan_ctrl_status_undef = 0;
7614                         rc = 0;
7615                 }
7616                 break;
7617
7618         case TPACPI_FAN_WR_ACPI_SFAN:
7619                 rc = fan_get_status(&s);
7620                 if (rc < 0)
7621                         break;
7622
7623                 s &= 0x07;
7624
7625                 /* Set fan to at least level 4 */
7626                 s |= 4;
7627
7628                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
7629                         rc = -EIO;
7630                 else
7631                         rc = 0;
7632                 break;
7633
7634         default:
7635                 rc = -ENXIO;
7636         }
7637
7638         mutex_unlock(&fan_mutex);
7639
7640         if (!rc)
7641                 vdbg_printk(TPACPI_DBG_FAN,
7642                         "fan control: set fan control register to 0x%02x\n",
7643                         s);
7644         return rc;
7645 }
7646
7647 static int fan_set_disable(void)
7648 {
7649         int rc;
7650
7651         if (!fan_control_allowed)
7652                 return -EPERM;
7653
7654         if (mutex_lock_killable(&fan_mutex))
7655                 return -ERESTARTSYS;
7656
7657         rc = 0;
7658         switch (fan_control_access_mode) {
7659         case TPACPI_FAN_WR_ACPI_FANS:
7660         case TPACPI_FAN_WR_TPEC:
7661                 if (!acpi_ec_write(fan_status_offset, 0x00))
7662                         rc = -EIO;
7663                 else {
7664                         fan_control_desired_level = 0;
7665                         tp_features.fan_ctrl_status_undef = 0;
7666                 }
7667                 break;
7668
7669         case TPACPI_FAN_WR_ACPI_SFAN:
7670                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
7671                         rc = -EIO;
7672                 else
7673                         fan_control_desired_level = 0;
7674                 break;
7675
7676         default:
7677                 rc = -ENXIO;
7678         }
7679
7680         if (!rc)
7681                 vdbg_printk(TPACPI_DBG_FAN,
7682                         "fan control: set fan control register to 0\n");
7683
7684         mutex_unlock(&fan_mutex);
7685         return rc;
7686 }
7687
7688 static int fan_set_speed(int speed)
7689 {
7690         int rc;
7691
7692         if (!fan_control_allowed)
7693                 return -EPERM;
7694
7695         if (mutex_lock_killable(&fan_mutex))
7696                 return -ERESTARTSYS;
7697
7698         rc = 0;
7699         switch (fan_control_access_mode) {
7700         case TPACPI_FAN_WR_ACPI_FANS:
7701                 if (speed >= 0 && speed <= 65535) {
7702                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
7703                                         speed, speed, speed))
7704                                 rc = -EIO;
7705                 } else
7706                         rc = -EINVAL;
7707                 break;
7708
7709         default:
7710                 rc = -ENXIO;
7711         }
7712
7713         mutex_unlock(&fan_mutex);
7714         return rc;
7715 }
7716
7717 static void fan_watchdog_reset(void)
7718 {
7719         static int fan_watchdog_active;
7720
7721         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
7722                 return;
7723
7724         if (fan_watchdog_active)
7725                 cancel_delayed_work(&fan_watchdog_task);
7726
7727         if (fan_watchdog_maxinterval > 0 &&
7728             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
7729                 fan_watchdog_active = 1;
7730                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
7731                                 msecs_to_jiffies(fan_watchdog_maxinterval
7732                                                  * 1000))) {
7733                         printk(TPACPI_ERR
7734                                "failed to queue the fan watchdog, "
7735                                "watchdog will not trigger\n");
7736                 }
7737         } else
7738                 fan_watchdog_active = 0;
7739 }
7740
7741 static void fan_watchdog_fire(struct work_struct *ignored)
7742 {
7743         int rc;
7744
7745         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
7746                 return;
7747
7748         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
7749         rc = fan_set_enable();
7750         if (rc < 0) {
7751                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
7752                         "will try again later...\n", -rc);
7753                 /* reschedule for later */
7754                 fan_watchdog_reset();
7755         }
7756 }
7757
7758 /*
7759  * SYSFS fan layout: hwmon compatible (device)
7760  *
7761  * pwm*_enable:
7762  *      0: "disengaged" mode
7763  *      1: manual mode
7764  *      2: native EC "auto" mode (recommended, hardware default)
7765  *
7766  * pwm*: set speed in manual mode, ignored otherwise.
7767  *      0 is level 0; 255 is level 7. Intermediate points done with linear
7768  *      interpolation.
7769  *
7770  * fan*_input: tachometer reading, RPM
7771  *
7772  *
7773  * SYSFS fan layout: extensions
7774  *
7775  * fan_watchdog (driver):
7776  *      fan watchdog interval in seconds, 0 disables (default), max 120
7777  */
7778
7779 /* sysfs fan pwm1_enable ----------------------------------------------- */
7780 static ssize_t fan_pwm1_enable_show(struct device *dev,
7781                                     struct device_attribute *attr,
7782                                     char *buf)
7783 {
7784         int res, mode;
7785         u8 status;
7786
7787         res = fan_get_status_safe(&status);
7788         if (res)
7789                 return res;
7790
7791         if (status & TP_EC_FAN_FULLSPEED) {
7792                 mode = 0;
7793         } else if (status & TP_EC_FAN_AUTO) {
7794                 mode = 2;
7795         } else
7796                 mode = 1;
7797
7798         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
7799 }
7800
7801 static ssize_t fan_pwm1_enable_store(struct device *dev,
7802                                      struct device_attribute *attr,
7803                                      const char *buf, size_t count)
7804 {
7805         unsigned long t;
7806         int res, level;
7807
7808         if (parse_strtoul(buf, 2, &t))
7809                 return -EINVAL;
7810
7811         tpacpi_disclose_usertask("hwmon pwm1_enable",
7812                         "set fan mode to %lu\n", t);
7813
7814         switch (t) {
7815         case 0:
7816                 level = TP_EC_FAN_FULLSPEED;
7817                 break;
7818         case 1:
7819                 level = TPACPI_FAN_LAST_LEVEL;
7820                 break;
7821         case 2:
7822                 level = TP_EC_FAN_AUTO;
7823                 break;
7824         case 3:
7825                 /* reserved for software-controlled auto mode */
7826                 return -ENOSYS;
7827         default:
7828                 return -EINVAL;
7829         }
7830
7831         res = fan_set_level_safe(level);
7832         if (res == -ENXIO)
7833                 return -EINVAL;
7834         else if (res < 0)
7835                 return res;
7836
7837         fan_watchdog_reset();
7838
7839         return count;
7840 }
7841
7842 static struct device_attribute dev_attr_fan_pwm1_enable =
7843         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
7844                 fan_pwm1_enable_show, fan_pwm1_enable_store);
7845
7846 /* sysfs fan pwm1 ------------------------------------------------------ */
7847 static ssize_t fan_pwm1_show(struct device *dev,
7848                              struct device_attribute *attr,
7849                              char *buf)
7850 {
7851         int res;
7852         u8 status;
7853
7854         res = fan_get_status_safe(&status);
7855         if (res)
7856                 return res;
7857
7858         if ((status &
7859              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
7860                 status = fan_control_desired_level;
7861
7862         if (status > 7)
7863                 status = 7;
7864
7865         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
7866 }
7867
7868 static ssize_t fan_pwm1_store(struct device *dev,
7869                               struct device_attribute *attr,
7870                               const char *buf, size_t count)
7871 {
7872         unsigned long s;
7873         int rc;
7874         u8 status, newlevel;
7875
7876         if (parse_strtoul(buf, 255, &s))
7877                 return -EINVAL;
7878
7879         tpacpi_disclose_usertask("hwmon pwm1",
7880                         "set fan speed to %lu\n", s);
7881
7882         /* scale down from 0-255 to 0-7 */
7883         newlevel = (s >> 5) & 0x07;
7884
7885         if (mutex_lock_killable(&fan_mutex))
7886                 return -ERESTARTSYS;
7887
7888         rc = fan_get_status(&status);
7889         if (!rc && (status &
7890                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
7891                 rc = fan_set_level(newlevel);
7892                 if (rc == -ENXIO)
7893                         rc = -EINVAL;
7894                 else if (!rc) {
7895                         fan_update_desired_level(newlevel);
7896                         fan_watchdog_reset();
7897                 }
7898         }
7899
7900         mutex_unlock(&fan_mutex);
7901         return (rc)? rc : count;
7902 }
7903
7904 static struct device_attribute dev_attr_fan_pwm1 =
7905         __ATTR(pwm1, S_IWUSR | S_IRUGO,
7906                 fan_pwm1_show, fan_pwm1_store);
7907
7908 /* sysfs fan fan1_input ------------------------------------------------ */
7909 static ssize_t fan_fan1_input_show(struct device *dev,
7910                            struct device_attribute *attr,
7911                            char *buf)
7912 {
7913         int res;
7914         unsigned int speed;
7915
7916         res = fan_get_speed(&speed);
7917         if (res < 0)
7918                 return res;
7919
7920         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7921 }
7922
7923 static struct device_attribute dev_attr_fan_fan1_input =
7924         __ATTR(fan1_input, S_IRUGO,
7925                 fan_fan1_input_show, NULL);
7926
7927 /* sysfs fan fan2_input ------------------------------------------------ */
7928 static ssize_t fan_fan2_input_show(struct device *dev,
7929                            struct device_attribute *attr,
7930                            char *buf)
7931 {
7932         int res;
7933         unsigned int speed;
7934
7935         res = fan2_get_speed(&speed);
7936         if (res < 0)
7937                 return res;
7938
7939         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7940 }
7941
7942 static struct device_attribute dev_attr_fan_fan2_input =
7943         __ATTR(fan2_input, S_IRUGO,
7944                 fan_fan2_input_show, NULL);
7945
7946 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
7947 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
7948                                      char *buf)
7949 {
7950         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
7951 }
7952
7953 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
7954                                       const char *buf, size_t count)
7955 {
7956         unsigned long t;
7957
7958         if (parse_strtoul(buf, 120, &t))
7959                 return -EINVAL;
7960
7961         if (!fan_control_allowed)
7962                 return -EPERM;
7963
7964         fan_watchdog_maxinterval = t;
7965         fan_watchdog_reset();
7966
7967         tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t);
7968
7969         return count;
7970 }
7971
7972 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
7973                 fan_fan_watchdog_show, fan_fan_watchdog_store);
7974
7975 /* --------------------------------------------------------------------- */
7976 static struct attribute *fan_attributes[] = {
7977         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
7978         &dev_attr_fan_fan1_input.attr,
7979         NULL, /* for fan2_input */
7980         NULL
7981 };
7982
7983 static const struct attribute_group fan_attr_group = {
7984         .attrs = fan_attributes,
7985 };
7986
7987 #define TPACPI_FAN_Q1   0x0001          /* Unitialized HFSP */
7988 #define TPACPI_FAN_2FAN 0x0002          /* EC 0x31 bit 0 selects fan2 */
7989
7990 #define TPACPI_FAN_QI(__id1, __id2, __quirks)   \
7991         { .vendor = PCI_VENDOR_ID_IBM,          \
7992           .bios = TPACPI_MATCH_ANY,             \
7993           .ec = TPID(__id1, __id2),             \
7994           .quirks = __quirks }
7995
7996 #define TPACPI_FAN_QL(__id1, __id2, __quirks)   \
7997         { .vendor = PCI_VENDOR_ID_LENOVO,       \
7998           .bios = TPACPI_MATCH_ANY,             \
7999           .ec = TPID(__id1, __id2),             \
8000           .quirks = __quirks }
8001
8002 static const struct tpacpi_quirk fan_quirk_table[] __initconst = {
8003         TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1),
8004         TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1),
8005         TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1),
8006         TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1),
8007         TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN),
8008 };
8009
8010 #undef TPACPI_FAN_QL
8011 #undef TPACPI_FAN_QI
8012
8013 static int __init fan_init(struct ibm_init_struct *iibm)
8014 {
8015         int rc;
8016         unsigned long quirks;
8017
8018         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8019                         "initializing fan subdriver\n");
8020
8021         mutex_init(&fan_mutex);
8022         fan_status_access_mode = TPACPI_FAN_NONE;
8023         fan_control_access_mode = TPACPI_FAN_WR_NONE;
8024         fan_control_commands = 0;
8025         fan_watchdog_maxinterval = 0;
8026         tp_features.fan_ctrl_status_undef = 0;
8027         tp_features.second_fan = 0;
8028         fan_control_desired_level = 7;
8029
8030         if (tpacpi_is_ibm()) {
8031                 TPACPI_ACPIHANDLE_INIT(fans);
8032                 TPACPI_ACPIHANDLE_INIT(gfan);
8033                 TPACPI_ACPIHANDLE_INIT(sfan);
8034         }
8035
8036         quirks = tpacpi_check_quirks(fan_quirk_table,
8037                                      ARRAY_SIZE(fan_quirk_table));
8038
8039         if (gfan_handle) {
8040                 /* 570, 600e/x, 770e, 770x */
8041                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
8042         } else {
8043                 /* all other ThinkPads: note that even old-style
8044                  * ThinkPad ECs supports the fan control register */
8045                 if (likely(acpi_ec_read(fan_status_offset,
8046                                         &fan_control_initial_status))) {
8047                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
8048                         if (quirks & TPACPI_FAN_Q1)
8049                                 fan_quirk1_setup();
8050                         if (quirks & TPACPI_FAN_2FAN) {
8051                                 tp_features.second_fan = 1;
8052                                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8053                                         "secondary fan support enabled\n");
8054                         }
8055                 } else {
8056                         printk(TPACPI_ERR
8057                                "ThinkPad ACPI EC access misbehaving, "
8058                                "fan status and control unavailable\n");
8059                         return 1;
8060                 }
8061         }
8062
8063         if (sfan_handle) {
8064                 /* 570, 770x-JL */
8065                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
8066                 fan_control_commands |=
8067                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
8068         } else {
8069                 if (!gfan_handle) {
8070                         /* gfan without sfan means no fan control */
8071                         /* all other models implement TP EC 0x2f control */
8072
8073                         if (fans_handle) {
8074                                 /* X31, X40, X41 */
8075                                 fan_control_access_mode =
8076                                     TPACPI_FAN_WR_ACPI_FANS;
8077                                 fan_control_commands |=
8078                                     TPACPI_FAN_CMD_SPEED |
8079                                     TPACPI_FAN_CMD_LEVEL |
8080                                     TPACPI_FAN_CMD_ENABLE;
8081                         } else {
8082                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
8083                                 fan_control_commands |=
8084                                     TPACPI_FAN_CMD_LEVEL |
8085                                     TPACPI_FAN_CMD_ENABLE;
8086                         }
8087                 }
8088         }
8089
8090         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8091                 "fan is %s, modes %d, %d\n",
8092                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
8093                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
8094                 fan_status_access_mode, fan_control_access_mode);
8095
8096         /* fan control master switch */
8097         if (!fan_control_allowed) {
8098                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
8099                 fan_control_commands = 0;
8100                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8101                            "fan control features disabled by parameter\n");
8102         }
8103
8104         /* update fan_control_desired_level */
8105         if (fan_status_access_mode != TPACPI_FAN_NONE)
8106                 fan_get_status_safe(NULL);
8107
8108         if (fan_status_access_mode != TPACPI_FAN_NONE ||
8109             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
8110                 if (tp_features.second_fan) {
8111                         /* attach second fan tachometer */
8112                         fan_attributes[ARRAY_SIZE(fan_attributes)-2] =
8113                                         &dev_attr_fan_fan2_input.attr;
8114                 }
8115                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
8116                                          &fan_attr_group);
8117                 if (rc < 0)
8118                         return rc;
8119
8120                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
8121                                         &driver_attr_fan_watchdog);
8122                 if (rc < 0) {
8123                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
8124                                         &fan_attr_group);
8125                         return rc;
8126                 }
8127                 return 0;
8128         } else
8129                 return 1;
8130 }
8131
8132 static void fan_exit(void)
8133 {
8134         vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN,
8135                     "cancelling any pending fan watchdog tasks\n");
8136
8137         /* FIXME: can we really do this unconditionally? */
8138         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
8139         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
8140                            &driver_attr_fan_watchdog);
8141
8142         cancel_delayed_work(&fan_watchdog_task);
8143         flush_workqueue(tpacpi_wq);
8144 }
8145
8146 static void fan_suspend(pm_message_t state)
8147 {
8148         int rc;
8149
8150         if (!fan_control_allowed)
8151                 return;
8152
8153         /* Store fan status in cache */
8154         fan_control_resume_level = 0;
8155         rc = fan_get_status_safe(&fan_control_resume_level);
8156         if (rc < 0)
8157                 printk(TPACPI_NOTICE
8158                         "failed to read fan level for later "
8159                         "restore during resume: %d\n", rc);
8160
8161         /* if it is undefined, don't attempt to restore it.
8162          * KEEP THIS LAST */
8163         if (tp_features.fan_ctrl_status_undef)
8164                 fan_control_resume_level = 0;
8165 }
8166
8167 static void fan_resume(void)
8168 {
8169         u8 current_level = 7;
8170         bool do_set = false;
8171         int rc;
8172
8173         /* DSDT *always* updates status on resume */
8174         tp_features.fan_ctrl_status_undef = 0;
8175
8176         if (!fan_control_allowed ||
8177             !fan_control_resume_level ||
8178             (fan_get_status_safe(&current_level) < 0))
8179                 return;
8180
8181         switch (fan_control_access_mode) {
8182         case TPACPI_FAN_WR_ACPI_SFAN:
8183                 /* never decrease fan level */
8184                 do_set = (fan_control_resume_level > current_level);
8185                 break;
8186         case TPACPI_FAN_WR_ACPI_FANS:
8187         case TPACPI_FAN_WR_TPEC:
8188                 /* never decrease fan level, scale is:
8189                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
8190                  *
8191                  * We expect the firmware to set either 7 or AUTO, but we
8192                  * handle FULLSPEED out of paranoia.
8193                  *
8194                  * So, we can safely only restore FULLSPEED or 7, anything
8195                  * else could slow the fan.  Restoring AUTO is useless, at
8196                  * best that's exactly what the DSDT already set (it is the
8197                  * slower it uses).
8198                  *
8199                  * Always keep in mind that the DSDT *will* have set the
8200                  * fans to what the vendor supposes is the best level.  We
8201                  * muck with it only to speed the fan up.
8202                  */
8203                 if (fan_control_resume_level != 7 &&
8204                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
8205                         return;
8206                 else
8207                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
8208                                  (current_level != fan_control_resume_level);
8209                 break;
8210         default:
8211                 return;
8212         }
8213         if (do_set) {
8214                 printk(TPACPI_NOTICE
8215                         "restoring fan level to 0x%02x\n",
8216                         fan_control_resume_level);
8217                 rc = fan_set_level_safe(fan_control_resume_level);
8218                 if (rc < 0)
8219                         printk(TPACPI_NOTICE
8220                                 "failed to restore fan level: %d\n", rc);
8221         }
8222 }
8223
8224 static int fan_read(struct seq_file *m)
8225 {
8226         int rc;
8227         u8 status;
8228         unsigned int speed = 0;
8229
8230         switch (fan_status_access_mode) {
8231         case TPACPI_FAN_RD_ACPI_GFAN:
8232                 /* 570, 600e/x, 770e, 770x */
8233                 rc = fan_get_status_safe(&status);
8234                 if (rc < 0)
8235                         return rc;
8236
8237                 seq_printf(m, "status:\t\t%s\n"
8238                                "level:\t\t%d\n",
8239                                (status != 0) ? "enabled" : "disabled", status);
8240                 break;
8241
8242         case TPACPI_FAN_RD_TPEC:
8243                 /* all except 570, 600e/x, 770e, 770x */
8244                 rc = fan_get_status_safe(&status);
8245                 if (rc < 0)
8246                         return rc;
8247
8248                 seq_printf(m, "status:\t\t%s\n",
8249                                (status != 0) ? "enabled" : "disabled");
8250
8251                 rc = fan_get_speed(&speed);
8252                 if (rc < 0)
8253                         return rc;
8254
8255                 seq_printf(m, "speed:\t\t%d\n", speed);
8256
8257                 if (status & TP_EC_FAN_FULLSPEED)
8258                         /* Disengaged mode takes precedence */
8259                         seq_printf(m, "level:\t\tdisengaged\n");
8260                 else if (status & TP_EC_FAN_AUTO)
8261                         seq_printf(m, "level:\t\tauto\n");
8262                 else
8263                         seq_printf(m, "level:\t\t%d\n", status);
8264                 break;
8265
8266         case TPACPI_FAN_NONE:
8267         default:
8268                 seq_printf(m, "status:\t\tnot supported\n");
8269         }
8270
8271         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
8272                 seq_printf(m, "commands:\tlevel <level>");
8273
8274                 switch (fan_control_access_mode) {
8275                 case TPACPI_FAN_WR_ACPI_SFAN:
8276                         seq_printf(m, " (<level> is 0-7)\n");
8277                         break;
8278
8279                 default:
8280                         seq_printf(m, " (<level> is 0-7, "
8281                                        "auto, disengaged, full-speed)\n");
8282                         break;
8283                 }
8284         }
8285
8286         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
8287                 seq_printf(m, "commands:\tenable, disable\n"
8288                                "commands:\twatchdog <timeout> (<timeout> "
8289                                "is 0 (off), 1-120 (seconds))\n");
8290
8291         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
8292                 seq_printf(m, "commands:\tspeed <speed>"
8293                                " (<speed> is 0-65535)\n");
8294
8295         return 0;
8296 }
8297
8298 static int fan_write_cmd_level(const char *cmd, int *rc)
8299 {
8300         int level;
8301
8302         if (strlencmp(cmd, "level auto") == 0)
8303                 level = TP_EC_FAN_AUTO;
8304         else if ((strlencmp(cmd, "level disengaged") == 0) |
8305                         (strlencmp(cmd, "level full-speed") == 0))
8306                 level = TP_EC_FAN_FULLSPEED;
8307         else if (sscanf(cmd, "level %d", &level) != 1)
8308                 return 0;
8309
8310         *rc = fan_set_level_safe(level);
8311         if (*rc == -ENXIO)
8312                 printk(TPACPI_ERR "level command accepted for unsupported "
8313                        "access mode %d", fan_control_access_mode);
8314         else if (!*rc)
8315                 tpacpi_disclose_usertask("procfs fan",
8316                         "set level to %d\n", level);
8317
8318         return 1;
8319 }
8320
8321 static int fan_write_cmd_enable(const char *cmd, int *rc)
8322 {
8323         if (strlencmp(cmd, "enable") != 0)
8324                 return 0;
8325
8326         *rc = fan_set_enable();
8327         if (*rc == -ENXIO)
8328                 printk(TPACPI_ERR "enable command accepted for unsupported "
8329                        "access mode %d", fan_control_access_mode);
8330         else if (!*rc)
8331                 tpacpi_disclose_usertask("procfs fan", "enable\n");
8332
8333         return 1;
8334 }
8335
8336 static int fan_write_cmd_disable(const char *cmd, int *rc)
8337 {
8338         if (strlencmp(cmd, "disable") != 0)
8339                 return 0;
8340
8341         *rc = fan_set_disable();
8342         if (*rc == -ENXIO)
8343                 printk(TPACPI_ERR "disable command accepted for unsupported "
8344                        "access mode %d", fan_control_access_mode);
8345         else if (!*rc)
8346                 tpacpi_disclose_usertask("procfs fan", "disable\n");
8347
8348         return 1;
8349 }
8350
8351 static int fan_write_cmd_speed(const char *cmd, int *rc)
8352 {
8353         int speed;
8354
8355         /* TODO:
8356          * Support speed <low> <medium> <high> ? */
8357
8358         if (sscanf(cmd, "speed %d", &speed) != 1)
8359                 return 0;
8360
8361         *rc = fan_set_speed(speed);
8362         if (*rc == -ENXIO)
8363                 printk(TPACPI_ERR "speed command accepted for unsupported "
8364                        "access mode %d", fan_control_access_mode);
8365         else if (!*rc)
8366                 tpacpi_disclose_usertask("procfs fan",
8367                         "set speed to %d\n", speed);
8368
8369         return 1;
8370 }
8371
8372 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
8373 {
8374         int interval;
8375
8376         if (sscanf(cmd, "watchdog %d", &interval) != 1)
8377                 return 0;
8378
8379         if (interval < 0 || interval > 120)
8380                 *rc = -EINVAL;
8381         else {
8382                 fan_watchdog_maxinterval = interval;
8383                 tpacpi_disclose_usertask("procfs fan",
8384                         "set watchdog timer to %d\n",
8385                         interval);
8386         }
8387
8388         return 1;
8389 }
8390
8391 static int fan_write(char *buf)
8392 {
8393         char *cmd;
8394         int rc = 0;
8395
8396         while (!rc && (cmd = next_cmd(&buf))) {
8397                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
8398                       fan_write_cmd_level(cmd, &rc)) &&
8399                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
8400                       (fan_write_cmd_enable(cmd, &rc) ||
8401                        fan_write_cmd_disable(cmd, &rc) ||
8402                        fan_write_cmd_watchdog(cmd, &rc))) &&
8403                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
8404                       fan_write_cmd_speed(cmd, &rc))
8405                     )
8406                         rc = -EINVAL;
8407                 else if (!rc)
8408                         fan_watchdog_reset();
8409         }
8410
8411         return rc;
8412 }
8413
8414 static struct ibm_struct fan_driver_data = {
8415         .name = "fan",
8416         .read = fan_read,
8417         .write = fan_write,
8418         .exit = fan_exit,
8419         .suspend = fan_suspend,
8420         .resume = fan_resume,
8421 };
8422
8423 /****************************************************************************
8424  ****************************************************************************
8425  *
8426  * Infrastructure
8427  *
8428  ****************************************************************************
8429  ****************************************************************************/
8430
8431 /*
8432  * HKEY event callout for other subdrivers go here
8433  * (yes, it is ugly, but it is quick, safe, and gets the job done
8434  */
8435 static void tpacpi_driver_event(const unsigned int hkey_event)
8436 {
8437         if (ibm_backlight_device) {
8438                 switch (hkey_event) {
8439                 case TP_HKEY_EV_BRGHT_UP:
8440                 case TP_HKEY_EV_BRGHT_DOWN:
8441                         tpacpi_brightness_notify_change();
8442                 }
8443         }
8444         if (alsa_card) {
8445                 switch (hkey_event) {
8446                 case TP_HKEY_EV_VOL_UP:
8447                 case TP_HKEY_EV_VOL_DOWN:
8448                 case TP_HKEY_EV_VOL_MUTE:
8449                         volume_alsa_notify_change();
8450                 }
8451         }
8452 }
8453
8454 static void hotkey_driver_event(const unsigned int scancode)
8455 {
8456         tpacpi_driver_event(TP_HKEY_EV_HOTKEY_BASE + scancode);
8457 }
8458
8459 /* sysfs name ---------------------------------------------------------- */
8460 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
8461                            struct device_attribute *attr,
8462                            char *buf)
8463 {
8464         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
8465 }
8466
8467 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
8468         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
8469
8470 /* --------------------------------------------------------------------- */
8471
8472 /* /proc support */
8473 static struct proc_dir_entry *proc_dir;
8474
8475 /*
8476  * Module and infrastructure proble, init and exit handling
8477  */
8478
8479 static int force_load;
8480
8481 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
8482 static const char * __init str_supported(int is_supported)
8483 {
8484         static char text_unsupported[] __initdata = "not supported";
8485
8486         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
8487 }
8488 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
8489
8490 static void ibm_exit(struct ibm_struct *ibm)
8491 {
8492         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
8493
8494         list_del_init(&ibm->all_drivers);
8495
8496         if (ibm->flags.acpi_notify_installed) {
8497                 dbg_printk(TPACPI_DBG_EXIT,
8498                         "%s: acpi_remove_notify_handler\n", ibm->name);
8499                 BUG_ON(!ibm->acpi);
8500                 acpi_remove_notify_handler(*ibm->acpi->handle,
8501                                            ibm->acpi->type,
8502                                            dispatch_acpi_notify);
8503                 ibm->flags.acpi_notify_installed = 0;
8504                 ibm->flags.acpi_notify_installed = 0;
8505         }
8506
8507         if (ibm->flags.proc_created) {
8508                 dbg_printk(TPACPI_DBG_EXIT,
8509                         "%s: remove_proc_entry\n", ibm->name);
8510                 remove_proc_entry(ibm->name, proc_dir);
8511                 ibm->flags.proc_created = 0;
8512         }
8513
8514         if (ibm->flags.acpi_driver_registered) {
8515                 dbg_printk(TPACPI_DBG_EXIT,
8516                         "%s: acpi_bus_unregister_driver\n", ibm->name);
8517                 BUG_ON(!ibm->acpi);
8518                 acpi_bus_unregister_driver(ibm->acpi->driver);
8519                 kfree(ibm->acpi->driver);
8520                 ibm->acpi->driver = NULL;
8521                 ibm->flags.acpi_driver_registered = 0;
8522         }
8523
8524         if (ibm->flags.init_called && ibm->exit) {
8525                 ibm->exit();
8526                 ibm->flags.init_called = 0;
8527         }
8528
8529         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
8530 }
8531
8532 static int __init ibm_init(struct ibm_init_struct *iibm)
8533 {
8534         int ret;
8535         struct ibm_struct *ibm = iibm->data;
8536         struct proc_dir_entry *entry;
8537
8538         BUG_ON(ibm == NULL);
8539
8540         INIT_LIST_HEAD(&ibm->all_drivers);
8541
8542         if (ibm->flags.experimental && !experimental)
8543                 return 0;
8544
8545         dbg_printk(TPACPI_DBG_INIT,
8546                 "probing for %s\n", ibm->name);
8547
8548         if (iibm->init) {
8549                 ret = iibm->init(iibm);
8550                 if (ret > 0)
8551                         return 0;       /* probe failed */
8552                 if (ret)
8553                         return ret;
8554
8555                 ibm->flags.init_called = 1;
8556         }
8557
8558         if (ibm->acpi) {
8559                 if (ibm->acpi->hid) {
8560                         ret = register_tpacpi_subdriver(ibm);
8561                         if (ret)
8562                                 goto err_out;
8563                 }
8564
8565                 if (ibm->acpi->notify) {
8566                         ret = setup_acpi_notify(ibm);
8567                         if (ret == -ENODEV) {
8568                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
8569                                         ibm->name);
8570                                 ret = 0;
8571                                 goto err_out;
8572                         }
8573                         if (ret < 0)
8574                                 goto err_out;
8575                 }
8576         }
8577
8578         dbg_printk(TPACPI_DBG_INIT,
8579                 "%s installed\n", ibm->name);
8580
8581         if (ibm->read) {
8582                 mode_t mode = iibm->base_procfs_mode;
8583
8584                 if (!mode)
8585                         mode = S_IRUGO;
8586                 if (ibm->write)
8587                         mode |= S_IWUSR;
8588                 entry = proc_create_data(ibm->name, mode, proc_dir,
8589                                          &dispatch_proc_fops, ibm);
8590                 if (!entry) {
8591                         printk(TPACPI_ERR "unable to create proc entry %s\n",
8592                                ibm->name);
8593                         ret = -ENODEV;
8594                         goto err_out;
8595                 }
8596                 ibm->flags.proc_created = 1;
8597         }
8598
8599         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
8600
8601         return 0;
8602
8603 err_out:
8604         dbg_printk(TPACPI_DBG_INIT,
8605                 "%s: at error exit path with result %d\n",
8606                 ibm->name, ret);
8607
8608         ibm_exit(ibm);
8609         return (ret < 0)? ret : 0;
8610 }
8611
8612 /* Probing */
8613
8614 static bool __pure __init tpacpi_is_fw_digit(const char c)
8615 {
8616         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z');
8617 }
8618
8619 /* Most models: xxyTkkWW (#.##c); Ancient 570/600 and -SL lacks (#.##c) */
8620 static bool __pure __init tpacpi_is_valid_fw_id(const char* const s,
8621                                                 const char t)
8622 {
8623         return s && strlen(s) >= 8 &&
8624                 tpacpi_is_fw_digit(s[0]) &&
8625                 tpacpi_is_fw_digit(s[1]) &&
8626                 s[2] == t && s[3] == 'T' &&
8627                 tpacpi_is_fw_digit(s[4]) &&
8628                 tpacpi_is_fw_digit(s[5]) &&
8629                 s[6] == 'W' && s[7] == 'W';
8630 }
8631
8632 /* returns 0 - probe ok, or < 0 - probe error.
8633  * Probe ok doesn't mean thinkpad found.
8634  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
8635 static int __must_check __init get_thinkpad_model_data(
8636                                                 struct thinkpad_id_data *tp)
8637 {
8638         const struct dmi_device *dev = NULL;
8639         char ec_fw_string[18];
8640         char const *s;
8641
8642         if (!tp)
8643                 return -EINVAL;
8644
8645         memset(tp, 0, sizeof(*tp));
8646
8647         if (dmi_name_in_vendors("IBM"))
8648                 tp->vendor = PCI_VENDOR_ID_IBM;
8649         else if (dmi_name_in_vendors("LENOVO"))
8650                 tp->vendor = PCI_VENDOR_ID_LENOVO;
8651         else
8652                 return 0;
8653
8654         s = dmi_get_system_info(DMI_BIOS_VERSION);
8655         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
8656         if (s && !tp->bios_version_str)
8657                 return -ENOMEM;
8658
8659         /* Really ancient ThinkPad 240X will fail this, which is fine */
8660         if (!tpacpi_is_valid_fw_id(tp->bios_version_str, 'E'))
8661                 return 0;
8662
8663         tp->bios_model = tp->bios_version_str[0]
8664                          | (tp->bios_version_str[1] << 8);
8665         tp->bios_release = (tp->bios_version_str[4] << 8)
8666                          | tp->bios_version_str[5];
8667
8668         /*
8669          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
8670          * X32 or newer, all Z series;  Some models must have an
8671          * up-to-date BIOS or they will not be detected.
8672          *
8673          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
8674          */
8675         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
8676                 if (sscanf(dev->name,
8677                            "IBM ThinkPad Embedded Controller -[%17c",
8678                            ec_fw_string) == 1) {
8679                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
8680                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
8681
8682                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
8683                         if (!tp->ec_version_str)
8684                                 return -ENOMEM;
8685
8686                         if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) {
8687                                 tp->ec_model = ec_fw_string[0]
8688                                                 | (ec_fw_string[1] << 8);
8689                                 tp->ec_release = (ec_fw_string[4] << 8)
8690                                                 | ec_fw_string[5];
8691                         } else {
8692                                 printk(TPACPI_NOTICE
8693                                         "ThinkPad firmware release %s "
8694                                         "doesn't match the known patterns\n",
8695                                         ec_fw_string);
8696                                 printk(TPACPI_NOTICE
8697                                         "please report this to %s\n",
8698                                         TPACPI_MAIL);
8699                         }
8700                         break;
8701                 }
8702         }
8703
8704         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
8705         if (s && !strnicmp(s, "ThinkPad", 8)) {
8706                 tp->model_str = kstrdup(s, GFP_KERNEL);
8707                 if (!tp->model_str)
8708                         return -ENOMEM;
8709         }
8710
8711         s = dmi_get_system_info(DMI_PRODUCT_NAME);
8712         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
8713         if (s && !tp->nummodel_str)
8714                 return -ENOMEM;
8715
8716         return 0;
8717 }
8718
8719 static int __init probe_for_thinkpad(void)
8720 {
8721         int is_thinkpad;
8722
8723         if (acpi_disabled)
8724                 return -ENODEV;
8725
8726         /* It would be dangerous to run the driver in this case */
8727         if (!tpacpi_is_ibm() && !tpacpi_is_lenovo())
8728                 return -ENODEV;
8729
8730         /*
8731          * Non-ancient models have better DMI tagging, but very old models
8732          * don't.  tpacpi_is_fw_known() is a cheat to help in that case.
8733          */
8734         is_thinkpad = (thinkpad_id.model_str != NULL) ||
8735                       (thinkpad_id.ec_model != 0) ||
8736                       tpacpi_is_fw_known();
8737
8738         /* ec is required because many other handles are relative to it */
8739         TPACPI_ACPIHANDLE_INIT(ec);
8740         if (!ec_handle) {
8741                 if (is_thinkpad)
8742                         printk(TPACPI_ERR
8743                                 "Not yet supported ThinkPad detected!\n");
8744                 return -ENODEV;
8745         }
8746
8747         if (!is_thinkpad && !force_load)
8748                 return -ENODEV;
8749
8750         return 0;
8751 }
8752
8753 static void __init thinkpad_acpi_init_banner(void)
8754 {
8755         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
8756         printk(TPACPI_INFO "%s\n", TPACPI_URL);
8757
8758         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
8759                 (thinkpad_id.bios_version_str) ?
8760                         thinkpad_id.bios_version_str : "unknown",
8761                 (thinkpad_id.ec_version_str) ?
8762                         thinkpad_id.ec_version_str : "unknown");
8763
8764         BUG_ON(!thinkpad_id.vendor);
8765
8766         if (thinkpad_id.model_str)
8767                 printk(TPACPI_INFO "%s %s, model %s\n",
8768                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
8769                                 "IBM" : ((thinkpad_id.vendor ==
8770                                                 PCI_VENDOR_ID_LENOVO) ?
8771                                         "Lenovo" : "Unknown vendor"),
8772                         thinkpad_id.model_str,
8773                         (thinkpad_id.nummodel_str) ?
8774                                 thinkpad_id.nummodel_str : "unknown");
8775 }
8776
8777 /* Module init, exit, parameters */
8778
8779 static struct ibm_init_struct ibms_init[] __initdata = {
8780         {
8781                 .data = &thinkpad_acpi_driver_data,
8782         },
8783         {
8784                 .init = hotkey_init,
8785                 .data = &hotkey_driver_data,
8786         },
8787         {
8788                 .init = bluetooth_init,
8789                 .data = &bluetooth_driver_data,
8790         },
8791         {
8792                 .init = wan_init,
8793                 .data = &wan_driver_data,
8794         },
8795         {
8796                 .init = uwb_init,
8797                 .data = &uwb_driver_data,
8798         },
8799 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
8800         {
8801                 .init = video_init,
8802                 .base_procfs_mode = S_IRUSR,
8803                 .data = &video_driver_data,
8804         },
8805 #endif
8806         {
8807                 .init = light_init,
8808                 .data = &light_driver_data,
8809         },
8810         {
8811                 .init = cmos_init,
8812                 .data = &cmos_driver_data,
8813         },
8814         {
8815                 .init = led_init,
8816                 .data = &led_driver_data,
8817         },
8818         {
8819                 .init = beep_init,
8820                 .data = &beep_driver_data,
8821         },
8822         {
8823                 .init = thermal_init,
8824                 .data = &thermal_driver_data,
8825         },
8826         {
8827                 .data = &ecdump_driver_data,
8828         },
8829         {
8830                 .init = brightness_init,
8831                 .data = &brightness_driver_data,
8832         },
8833         {
8834                 .init = volume_init,
8835                 .data = &volume_driver_data,
8836         },
8837         {
8838                 .init = fan_init,
8839                 .data = &fan_driver_data,
8840         },
8841 };
8842
8843 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
8844 {
8845         unsigned int i;
8846         struct ibm_struct *ibm;
8847
8848         if (!kp || !kp->name || !val)
8849                 return -EINVAL;
8850
8851         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
8852                 ibm = ibms_init[i].data;
8853                 WARN_ON(ibm == NULL);
8854
8855                 if (!ibm || !ibm->name)
8856                         continue;
8857
8858                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
8859                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
8860                                 return -ENOSPC;
8861                         strcpy(ibms_init[i].param, val);
8862                         strcat(ibms_init[i].param, ",");
8863                         return 0;
8864                 }
8865         }
8866
8867         return -EINVAL;
8868 }
8869
8870 module_param(experimental, int, 0444);
8871 MODULE_PARM_DESC(experimental,
8872                  "Enables experimental features when non-zero");
8873
8874 module_param_named(debug, dbg_level, uint, 0);
8875 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
8876
8877 module_param(force_load, bool, 0444);
8878 MODULE_PARM_DESC(force_load,
8879                  "Attempts to load the driver even on a "
8880                  "mis-identified ThinkPad when true");
8881
8882 module_param_named(fan_control, fan_control_allowed, bool, 0444);
8883 MODULE_PARM_DESC(fan_control,
8884                  "Enables setting fan parameters features when true");
8885
8886 module_param_named(brightness_mode, brightness_mode, uint, 0444);
8887 MODULE_PARM_DESC(brightness_mode,
8888                  "Selects brightness control strategy: "
8889                  "0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM");
8890
8891 module_param(brightness_enable, uint, 0444);
8892 MODULE_PARM_DESC(brightness_enable,
8893                  "Enables backlight control when 1, disables when 0");
8894
8895 module_param(hotkey_report_mode, uint, 0444);
8896 MODULE_PARM_DESC(hotkey_report_mode,
8897                  "used for backwards compatibility with userspace, "
8898                  "see documentation");
8899
8900 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
8901 module_param_named(volume_mode, volume_mode, uint, 0444);
8902 MODULE_PARM_DESC(volume_mode,
8903                  "Selects volume control strategy: "
8904                  "0=auto, 1=EC, 2=N/A, 3=EC+NVRAM");
8905
8906 module_param_named(volume_capabilities, volume_capabilities, uint, 0444);
8907 MODULE_PARM_DESC(volume_capabilities,
8908                  "Selects the mixer capabilites: "
8909                  "0=auto, 1=volume and mute, 2=mute only");
8910
8911 module_param_named(volume_control, volume_control_allowed, bool, 0444);
8912 MODULE_PARM_DESC(volume_control,
8913                  "Enables software override for the console audio "
8914                  "control when true");
8915
8916 /* ALSA module API parameters */
8917 module_param_named(index, alsa_index, int, 0444);
8918 MODULE_PARM_DESC(index, "ALSA index for the ACPI EC Mixer");
8919 module_param_named(id, alsa_id, charp, 0444);
8920 MODULE_PARM_DESC(id, "ALSA id for the ACPI EC Mixer");
8921 module_param_named(enable, alsa_enable, bool, 0444);
8922 MODULE_PARM_DESC(enable, "Enable the ALSA interface for the ACPI EC Mixer");
8923 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
8924
8925 #define TPACPI_PARAM(feature) \
8926         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
8927         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
8928                          "at module load, see documentation")
8929
8930 TPACPI_PARAM(hotkey);
8931 TPACPI_PARAM(bluetooth);
8932 TPACPI_PARAM(video);
8933 TPACPI_PARAM(light);
8934 TPACPI_PARAM(cmos);
8935 TPACPI_PARAM(led);
8936 TPACPI_PARAM(beep);
8937 TPACPI_PARAM(ecdump);
8938 TPACPI_PARAM(brightness);
8939 TPACPI_PARAM(volume);
8940 TPACPI_PARAM(fan);
8941
8942 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
8943 module_param(dbg_wlswemul, uint, 0444);
8944 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
8945 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
8946 MODULE_PARM_DESC(wlsw_state,
8947                  "Initial state of the emulated WLSW switch");
8948
8949 module_param(dbg_bluetoothemul, uint, 0444);
8950 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
8951 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
8952 MODULE_PARM_DESC(bluetooth_state,
8953                  "Initial state of the emulated bluetooth switch");
8954
8955 module_param(dbg_wwanemul, uint, 0444);
8956 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
8957 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
8958 MODULE_PARM_DESC(wwan_state,
8959                  "Initial state of the emulated WWAN switch");
8960
8961 module_param(dbg_uwbemul, uint, 0444);
8962 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
8963 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
8964 MODULE_PARM_DESC(uwb_state,
8965                  "Initial state of the emulated UWB switch");
8966 #endif
8967
8968 static void thinkpad_acpi_module_exit(void)
8969 {
8970         struct ibm_struct *ibm, *itmp;
8971
8972         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
8973
8974         list_for_each_entry_safe_reverse(ibm, itmp,
8975                                          &tpacpi_all_drivers,
8976                                          all_drivers) {
8977                 ibm_exit(ibm);
8978         }
8979
8980         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
8981
8982         if (tpacpi_inputdev) {
8983                 if (tp_features.input_device_registered)
8984                         input_unregister_device(tpacpi_inputdev);
8985                 else
8986                         input_free_device(tpacpi_inputdev);
8987         }
8988
8989         if (tpacpi_hwmon)
8990                 hwmon_device_unregister(tpacpi_hwmon);
8991
8992         if (tp_features.sensors_pdev_attrs_registered)
8993                 device_remove_file(&tpacpi_sensors_pdev->dev,
8994                                    &dev_attr_thinkpad_acpi_pdev_name);
8995         if (tpacpi_sensors_pdev)
8996                 platform_device_unregister(tpacpi_sensors_pdev);
8997         if (tpacpi_pdev)
8998                 platform_device_unregister(tpacpi_pdev);
8999
9000         if (tp_features.sensors_pdrv_attrs_registered)
9001                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
9002         if (tp_features.platform_drv_attrs_registered)
9003                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
9004
9005         if (tp_features.sensors_pdrv_registered)
9006                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
9007
9008         if (tp_features.platform_drv_registered)
9009                 platform_driver_unregister(&tpacpi_pdriver);
9010
9011         if (proc_dir)
9012                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
9013
9014         if (tpacpi_wq)
9015                 destroy_workqueue(tpacpi_wq);
9016
9017         kfree(thinkpad_id.bios_version_str);
9018         kfree(thinkpad_id.ec_version_str);
9019         kfree(thinkpad_id.model_str);
9020 }
9021
9022
9023 static int __init thinkpad_acpi_module_init(void)
9024 {
9025         int ret, i;
9026
9027         tpacpi_lifecycle = TPACPI_LIFE_INIT;
9028
9029         /* Parameter checking */
9030         if (hotkey_report_mode > 2)
9031                 return -EINVAL;
9032
9033         /* Driver-level probe */
9034
9035         ret = get_thinkpad_model_data(&thinkpad_id);
9036         if (ret) {
9037                 printk(TPACPI_ERR
9038                         "unable to get DMI data: %d\n", ret);
9039                 thinkpad_acpi_module_exit();
9040                 return ret;
9041         }
9042         ret = probe_for_thinkpad();
9043         if (ret) {
9044                 thinkpad_acpi_module_exit();
9045                 return ret;
9046         }
9047
9048         /* Driver initialization */
9049
9050         thinkpad_acpi_init_banner();
9051         tpacpi_check_outdated_fw();
9052
9053         TPACPI_ACPIHANDLE_INIT(ecrd);
9054         TPACPI_ACPIHANDLE_INIT(ecwr);
9055
9056         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
9057         if (!tpacpi_wq) {
9058                 thinkpad_acpi_module_exit();
9059                 return -ENOMEM;
9060         }
9061
9062         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
9063         if (!proc_dir) {
9064                 printk(TPACPI_ERR
9065                        "unable to create proc dir " TPACPI_PROC_DIR);
9066                 thinkpad_acpi_module_exit();
9067                 return -ENODEV;
9068         }
9069
9070         ret = platform_driver_register(&tpacpi_pdriver);
9071         if (ret) {
9072                 printk(TPACPI_ERR
9073                        "unable to register main platform driver\n");
9074                 thinkpad_acpi_module_exit();
9075                 return ret;
9076         }
9077         tp_features.platform_drv_registered = 1;
9078
9079         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
9080         if (ret) {
9081                 printk(TPACPI_ERR
9082                        "unable to register hwmon platform driver\n");
9083                 thinkpad_acpi_module_exit();
9084                 return ret;
9085         }
9086         tp_features.sensors_pdrv_registered = 1;
9087
9088         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
9089         if (!ret) {
9090                 tp_features.platform_drv_attrs_registered = 1;
9091                 ret = tpacpi_create_driver_attributes(
9092                                         &tpacpi_hwmon_pdriver.driver);
9093         }
9094         if (ret) {
9095                 printk(TPACPI_ERR
9096                        "unable to create sysfs driver attributes\n");
9097                 thinkpad_acpi_module_exit();
9098                 return ret;
9099         }
9100         tp_features.sensors_pdrv_attrs_registered = 1;
9101
9102
9103         /* Device initialization */
9104         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
9105                                                         NULL, 0);
9106         if (IS_ERR(tpacpi_pdev)) {
9107                 ret = PTR_ERR(tpacpi_pdev);
9108                 tpacpi_pdev = NULL;
9109                 printk(TPACPI_ERR "unable to register platform device\n");
9110                 thinkpad_acpi_module_exit();
9111                 return ret;
9112         }
9113         tpacpi_sensors_pdev = platform_device_register_simple(
9114                                                 TPACPI_HWMON_DRVR_NAME,
9115                                                 -1, NULL, 0);
9116         if (IS_ERR(tpacpi_sensors_pdev)) {
9117                 ret = PTR_ERR(tpacpi_sensors_pdev);
9118                 tpacpi_sensors_pdev = NULL;
9119                 printk(TPACPI_ERR
9120                        "unable to register hwmon platform device\n");
9121                 thinkpad_acpi_module_exit();
9122                 return ret;
9123         }
9124         ret = device_create_file(&tpacpi_sensors_pdev->dev,
9125                                  &dev_attr_thinkpad_acpi_pdev_name);
9126         if (ret) {
9127                 printk(TPACPI_ERR
9128                        "unable to create sysfs hwmon device attributes\n");
9129                 thinkpad_acpi_module_exit();
9130                 return ret;
9131         }
9132         tp_features.sensors_pdev_attrs_registered = 1;
9133         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
9134         if (IS_ERR(tpacpi_hwmon)) {
9135                 ret = PTR_ERR(tpacpi_hwmon);
9136                 tpacpi_hwmon = NULL;
9137                 printk(TPACPI_ERR "unable to register hwmon device\n");
9138                 thinkpad_acpi_module_exit();
9139                 return ret;
9140         }
9141         mutex_init(&tpacpi_inputdev_send_mutex);
9142         tpacpi_inputdev = input_allocate_device();
9143         if (!tpacpi_inputdev) {
9144                 printk(TPACPI_ERR "unable to allocate input device\n");
9145                 thinkpad_acpi_module_exit();
9146                 return -ENOMEM;
9147         } else {
9148                 /* Prepare input device, but don't register */
9149                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
9150                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
9151                 tpacpi_inputdev->id.bustype = BUS_HOST;
9152                 tpacpi_inputdev->id.vendor = thinkpad_id.vendor;
9153                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
9154                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
9155                 tpacpi_inputdev->dev.parent = &tpacpi_pdev->dev;
9156         }
9157
9158         /* Init subdriver dependencies */
9159         tpacpi_detect_brightness_capabilities();
9160
9161         /* Init subdrivers */
9162         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
9163                 ret = ibm_init(&ibms_init[i]);
9164                 if (ret >= 0 && *ibms_init[i].param)
9165                         ret = ibms_init[i].data->write(ibms_init[i].param);
9166                 if (ret < 0) {
9167                         thinkpad_acpi_module_exit();
9168                         return ret;
9169                 }
9170         }
9171
9172         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
9173
9174         ret = input_register_device(tpacpi_inputdev);
9175         if (ret < 0) {
9176                 printk(TPACPI_ERR "unable to register input device\n");
9177                 thinkpad_acpi_module_exit();
9178                 return ret;
9179         } else {
9180                 tp_features.input_device_registered = 1;
9181         }
9182
9183         return 0;
9184 }
9185
9186 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
9187
9188 /*
9189  * This will autoload the driver in almost every ThinkPad
9190  * in widespread use.
9191  *
9192  * Only _VERY_ old models, like the 240, 240x and 570 lack
9193  * the HKEY event interface.
9194  */
9195 MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids);
9196
9197 /*
9198  * DMI matching for module autoloading
9199  *
9200  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
9201  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
9202  *
9203  * Only models listed in thinkwiki will be supported, so add yours
9204  * if it is not there yet.
9205  */
9206 #define IBM_BIOS_MODULE_ALIAS(__type) \
9207         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*")
9208
9209 /* Ancient thinkpad BIOSes have to be identified by
9210  * BIOS type or model number, and there are far less
9211  * BIOS types than model numbers... */
9212 IBM_BIOS_MODULE_ALIAS("I[MU]");         /* 570, 570e */
9213
9214 MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>");
9215 MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>");
9216 MODULE_DESCRIPTION(TPACPI_DESC);
9217 MODULE_VERSION(TPACPI_VERSION);
9218 MODULE_LICENSE("GPL");
9219
9220 module_init(thinkpad_acpi_module_init);
9221 module_exit(thinkpad_acpi_module_exit);