thinkpad-acpi: disclose usertask for ALSA callbacks
[platform/kernel/linux-starfive.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         void issue_brightnesschange(const unsigned int oldbrt,
2344                                     const unsigned int newbrt)
2345         {
2346                 unsigned int i = oldbrt;
2347
2348                 while (i > newbrt) {
2349                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2350                         i--;
2351                 }
2352                 while (i < newbrt) {
2353                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2354                         i++;
2355                 }
2356         }
2357
2358         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2359         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2360         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2361         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2362
2363         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2364
2365         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2366
2367         /*
2368          * Handle volume
2369          *
2370          * This code is supposed to duplicate the IBM firmware behaviour:
2371          * - Pressing MUTE issues mute hotkey message, even when already mute
2372          * - Pressing Volume up/down issues volume up/down hotkey messages,
2373          *   even when already at maximum or minumum volume
2374          * - The act of unmuting issues volume up/down notification,
2375          *   depending which key was used to unmute
2376          *
2377          * We are constrained to what the NVRAM can tell us, which is not much
2378          * and certainly not enough if more than one volume hotkey was pressed
2379          * since the last poll cycle.
2380          *
2381          * Just to make our life interesting, some newer Lenovo ThinkPads have
2382          * bugs in the BIOS and may fail to update volume_toggle properly.
2383          */
2384         if (newn->mute) {
2385                 /* muted */
2386                 if (!oldn->mute ||
2387                     oldn->volume_toggle != newn->volume_toggle ||
2388                     oldn->volume_level != newn->volume_level) {
2389                         /* recently muted, or repeated mute keypress, or
2390                          * multiple presses ending in mute */
2391                         issue_volchange(oldn->volume_level, newn->volume_level);
2392                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2393                 }
2394         } else {
2395                 /* unmute */
2396                 if (oldn->mute) {
2397                         /* recently unmuted, issue 'unmute' keypress */
2398                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2399                 }
2400                 if (oldn->volume_level != newn->volume_level) {
2401                         issue_volchange(oldn->volume_level, newn->volume_level);
2402                 } else if (oldn->volume_toggle != newn->volume_toggle) {
2403                         /* repeated vol up/down keypress at end of scale ? */
2404                         if (newn->volume_level == 0)
2405                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2406                         else if (newn->volume_level >= TP_NVRAM_LEVEL_VOLUME_MAX)
2407                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2408                 }
2409         }
2410
2411         /* handle brightness */
2412         if (oldn->brightness_level != newn->brightness_level) {
2413                 issue_brightnesschange(oldn->brightness_level,
2414                                        newn->brightness_level);
2415         } else if (oldn->brightness_toggle != newn->brightness_toggle) {
2416                 /* repeated key presses that didn't change state */
2417                 if (newn->brightness_level == 0)
2418                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2419                 else if (newn->brightness_level >= bright_maxlvl
2420                                 && !tp_features.bright_unkfw)
2421                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2422         }
2423
2424 #undef TPACPI_COMPARE_KEY
2425 #undef TPACPI_MAY_SEND_KEY
2426 }
2427
2428 /*
2429  * Polling driver
2430  *
2431  * We track all events in hotkey_source_mask all the time, since
2432  * most of them are edge-based.  We only issue those requested by
2433  * hotkey_user_mask or hotkey_driver_mask, though.
2434  */
2435 static int hotkey_kthread(void *data)
2436 {
2437         struct tp_nvram_state s[2];
2438         u32 poll_mask, event_mask;
2439         unsigned int si, so;
2440         unsigned long t;
2441         unsigned int change_detector, must_reset;
2442         unsigned int poll_freq;
2443
2444         mutex_lock(&hotkey_thread_mutex);
2445
2446         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2447                 goto exit;
2448
2449         set_freezable();
2450
2451         so = 0;
2452         si = 1;
2453         t = 0;
2454
2455         /* Initial state for compares */
2456         mutex_lock(&hotkey_thread_data_mutex);
2457         change_detector = hotkey_config_change;
2458         poll_mask = hotkey_source_mask;
2459         event_mask = hotkey_source_mask &
2460                         (hotkey_driver_mask | hotkey_user_mask);
2461         poll_freq = hotkey_poll_freq;
2462         mutex_unlock(&hotkey_thread_data_mutex);
2463         hotkey_read_nvram(&s[so], poll_mask);
2464
2465         while (!kthread_should_stop()) {
2466                 if (t == 0) {
2467                         if (likely(poll_freq))
2468                                 t = 1000/poll_freq;
2469                         else
2470                                 t = 100;        /* should never happen... */
2471                 }
2472                 t = msleep_interruptible(t);
2473                 if (unlikely(kthread_should_stop()))
2474                         break;
2475                 must_reset = try_to_freeze();
2476                 if (t > 0 && !must_reset)
2477                         continue;
2478
2479                 mutex_lock(&hotkey_thread_data_mutex);
2480                 if (must_reset || hotkey_config_change != change_detector) {
2481                         /* forget old state on thaw or config change */
2482                         si = so;
2483                         t = 0;
2484                         change_detector = hotkey_config_change;
2485                 }
2486                 poll_mask = hotkey_source_mask;
2487                 event_mask = hotkey_source_mask &
2488                                 (hotkey_driver_mask | hotkey_user_mask);
2489                 poll_freq = hotkey_poll_freq;
2490                 mutex_unlock(&hotkey_thread_data_mutex);
2491
2492                 if (likely(poll_mask)) {
2493                         hotkey_read_nvram(&s[si], poll_mask);
2494                         if (likely(si != so)) {
2495                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2496                                                                 event_mask);
2497                         }
2498                 }
2499
2500                 so = si;
2501                 si ^= 1;
2502         }
2503
2504 exit:
2505         mutex_unlock(&hotkey_thread_mutex);
2506         return 0;
2507 }
2508
2509 /* call with hotkey_mutex held */
2510 static void hotkey_poll_stop_sync(void)
2511 {
2512         if (tpacpi_hotkey_task) {
2513                 if (frozen(tpacpi_hotkey_task) ||
2514                     freezing(tpacpi_hotkey_task))
2515                         thaw_process(tpacpi_hotkey_task);
2516
2517                 kthread_stop(tpacpi_hotkey_task);
2518                 tpacpi_hotkey_task = NULL;
2519                 mutex_lock(&hotkey_thread_mutex);
2520                 /* at this point, the thread did exit */
2521                 mutex_unlock(&hotkey_thread_mutex);
2522         }
2523 }
2524
2525 /* call with hotkey_mutex held */
2526 static void hotkey_poll_setup(const bool may_warn)
2527 {
2528         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2529         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2530
2531         if (hotkey_poll_freq > 0 &&
2532             (poll_driver_mask ||
2533              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2534                 if (!tpacpi_hotkey_task) {
2535                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2536                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2537                         if (IS_ERR(tpacpi_hotkey_task)) {
2538                                 tpacpi_hotkey_task = NULL;
2539                                 printk(TPACPI_ERR
2540                                        "could not create kernel thread "
2541                                        "for hotkey polling\n");
2542                         }
2543                 }
2544         } else {
2545                 hotkey_poll_stop_sync();
2546                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2547                     hotkey_poll_freq == 0) {
2548                         printk(TPACPI_NOTICE
2549                                 "hot keys 0x%08x and/or events 0x%08x "
2550                                 "require polling, which is currently "
2551                                 "disabled\n",
2552                                 poll_user_mask, poll_driver_mask);
2553                 }
2554         }
2555 }
2556
2557 static void hotkey_poll_setup_safe(const bool may_warn)
2558 {
2559         mutex_lock(&hotkey_mutex);
2560         hotkey_poll_setup(may_warn);
2561         mutex_unlock(&hotkey_mutex);
2562 }
2563
2564 /* call with hotkey_mutex held */
2565 static void hotkey_poll_set_freq(unsigned int freq)
2566 {
2567         if (!freq)
2568                 hotkey_poll_stop_sync();
2569
2570         hotkey_poll_freq = freq;
2571 }
2572
2573 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2574
2575 static void hotkey_poll_setup(const bool __unused)
2576 {
2577 }
2578
2579 static void hotkey_poll_setup_safe(const bool __unused)
2580 {
2581 }
2582
2583 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2584
2585 static int hotkey_inputdev_open(struct input_dev *dev)
2586 {
2587         switch (tpacpi_lifecycle) {
2588         case TPACPI_LIFE_INIT:
2589         case TPACPI_LIFE_RUNNING:
2590                 hotkey_poll_setup_safe(false);
2591                 return 0;
2592         case TPACPI_LIFE_EXITING:
2593                 return -EBUSY;
2594         }
2595
2596         /* Should only happen if tpacpi_lifecycle is corrupt */
2597         BUG();
2598         return -EBUSY;
2599 }
2600
2601 static void hotkey_inputdev_close(struct input_dev *dev)
2602 {
2603         /* disable hotkey polling when possible */
2604         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING &&
2605             !(hotkey_source_mask & hotkey_driver_mask))
2606                 hotkey_poll_setup_safe(false);
2607 }
2608
2609 /* sysfs hotkey enable ------------------------------------------------- */
2610 static ssize_t hotkey_enable_show(struct device *dev,
2611                            struct device_attribute *attr,
2612                            char *buf)
2613 {
2614         int res, status;
2615
2616         printk_deprecated_attribute("hotkey_enable",
2617                         "Hotkey reporting is always enabled");
2618
2619         res = hotkey_status_get(&status);
2620         if (res)
2621                 return res;
2622
2623         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2624 }
2625
2626 static ssize_t hotkey_enable_store(struct device *dev,
2627                             struct device_attribute *attr,
2628                             const char *buf, size_t count)
2629 {
2630         unsigned long t;
2631
2632         printk_deprecated_attribute("hotkey_enable",
2633                         "Hotkeys can be disabled through hotkey_mask");
2634
2635         if (parse_strtoul(buf, 1, &t))
2636                 return -EINVAL;
2637
2638         if (t == 0)
2639                 return -EPERM;
2640
2641         return count;
2642 }
2643
2644 static struct device_attribute dev_attr_hotkey_enable =
2645         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2646                 hotkey_enable_show, hotkey_enable_store);
2647
2648 /* sysfs hotkey mask --------------------------------------------------- */
2649 static ssize_t hotkey_mask_show(struct device *dev,
2650                            struct device_attribute *attr,
2651                            char *buf)
2652 {
2653         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2654 }
2655
2656 static ssize_t hotkey_mask_store(struct device *dev,
2657                             struct device_attribute *attr,
2658                             const char *buf, size_t count)
2659 {
2660         unsigned long t;
2661         int res;
2662
2663         if (parse_strtoul(buf, 0xffffffffUL, &t))
2664                 return -EINVAL;
2665
2666         if (mutex_lock_killable(&hotkey_mutex))
2667                 return -ERESTARTSYS;
2668
2669         res = hotkey_user_mask_set(t);
2670
2671 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2672         hotkey_poll_setup(true);
2673 #endif
2674
2675         mutex_unlock(&hotkey_mutex);
2676
2677         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2678
2679         return (res) ? res : count;
2680 }
2681
2682 static struct device_attribute dev_attr_hotkey_mask =
2683         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2684                 hotkey_mask_show, hotkey_mask_store);
2685
2686 /* sysfs hotkey bios_enabled ------------------------------------------- */
2687 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2688                            struct device_attribute *attr,
2689                            char *buf)
2690 {
2691         return sprintf(buf, "0\n");
2692 }
2693
2694 static struct device_attribute dev_attr_hotkey_bios_enabled =
2695         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2696
2697 /* sysfs hotkey bios_mask ---------------------------------------------- */
2698 static ssize_t hotkey_bios_mask_show(struct device *dev,
2699                            struct device_attribute *attr,
2700                            char *buf)
2701 {
2702         printk_deprecated_attribute("hotkey_bios_mask",
2703                         "This attribute is useless.");
2704         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2705 }
2706
2707 static struct device_attribute dev_attr_hotkey_bios_mask =
2708         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2709
2710 /* sysfs hotkey all_mask ----------------------------------------------- */
2711 static ssize_t hotkey_all_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 }
2718
2719 static struct device_attribute dev_attr_hotkey_all_mask =
2720         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2721
2722 /* sysfs hotkey recommended_mask --------------------------------------- */
2723 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2724                                             struct device_attribute *attr,
2725                                             char *buf)
2726 {
2727         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2728                         (hotkey_all_mask | hotkey_source_mask)
2729                         & ~hotkey_reserved_mask);
2730 }
2731
2732 static struct device_attribute dev_attr_hotkey_recommended_mask =
2733         __ATTR(hotkey_recommended_mask, S_IRUGO,
2734                 hotkey_recommended_mask_show, NULL);
2735
2736 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2737
2738 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2739 static ssize_t hotkey_source_mask_show(struct device *dev,
2740                            struct device_attribute *attr,
2741                            char *buf)
2742 {
2743         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2744 }
2745
2746 static ssize_t hotkey_source_mask_store(struct device *dev,
2747                             struct device_attribute *attr,
2748                             const char *buf, size_t count)
2749 {
2750         unsigned long t;
2751         u32 r_ev;
2752         int rc;
2753
2754         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2755                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2756                 return -EINVAL;
2757
2758         if (mutex_lock_killable(&hotkey_mutex))
2759                 return -ERESTARTSYS;
2760
2761         HOTKEY_CONFIG_CRITICAL_START
2762         hotkey_source_mask = t;
2763         HOTKEY_CONFIG_CRITICAL_END
2764
2765         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2766                         ~hotkey_source_mask);
2767         hotkey_poll_setup(true);
2768
2769         /* check if events needed by the driver got disabled */
2770         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2771                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2772
2773         mutex_unlock(&hotkey_mutex);
2774
2775         if (rc < 0)
2776                 printk(TPACPI_ERR "hotkey_source_mask: failed to update the"
2777                         "firmware event mask!\n");
2778
2779         if (r_ev)
2780                 printk(TPACPI_NOTICE "hotkey_source_mask: "
2781                         "some important events were disabled: "
2782                         "0x%04x\n", r_ev);
2783
2784         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2785
2786         return (rc < 0) ? rc : count;
2787 }
2788
2789 static struct device_attribute dev_attr_hotkey_source_mask =
2790         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2791                 hotkey_source_mask_show, hotkey_source_mask_store);
2792
2793 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2794 static ssize_t hotkey_poll_freq_show(struct device *dev,
2795                            struct device_attribute *attr,
2796                            char *buf)
2797 {
2798         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2799 }
2800
2801 static ssize_t hotkey_poll_freq_store(struct device *dev,
2802                             struct device_attribute *attr,
2803                             const char *buf, size_t count)
2804 {
2805         unsigned long t;
2806
2807         if (parse_strtoul(buf, 25, &t))
2808                 return -EINVAL;
2809
2810         if (mutex_lock_killable(&hotkey_mutex))
2811                 return -ERESTARTSYS;
2812
2813         hotkey_poll_set_freq(t);
2814         hotkey_poll_setup(true);
2815
2816         mutex_unlock(&hotkey_mutex);
2817
2818         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2819
2820         return count;
2821 }
2822
2823 static struct device_attribute dev_attr_hotkey_poll_freq =
2824         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2825                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2826
2827 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2828
2829 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2830 static ssize_t hotkey_radio_sw_show(struct device *dev,
2831                            struct device_attribute *attr,
2832                            char *buf)
2833 {
2834         int res;
2835         res = hotkey_get_wlsw();
2836         if (res < 0)
2837                 return res;
2838
2839         /* Opportunistic update */
2840         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2841
2842         return snprintf(buf, PAGE_SIZE, "%d\n",
2843                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2844 }
2845
2846 static struct device_attribute dev_attr_hotkey_radio_sw =
2847         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
2848
2849 static void hotkey_radio_sw_notify_change(void)
2850 {
2851         if (tp_features.hotkey_wlsw)
2852                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2853                              "hotkey_radio_sw");
2854 }
2855
2856 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2857 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2858                            struct device_attribute *attr,
2859                            char *buf)
2860 {
2861         int res, s;
2862         res = hotkey_get_tablet_mode(&s);
2863         if (res < 0)
2864                 return res;
2865
2866         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2867 }
2868
2869 static struct device_attribute dev_attr_hotkey_tablet_mode =
2870         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2871
2872 static void hotkey_tablet_mode_notify_change(void)
2873 {
2874         if (tp_features.hotkey_tablet)
2875                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2876                              "hotkey_tablet_mode");
2877 }
2878
2879 /* sysfs hotkey report_mode -------------------------------------------- */
2880 static ssize_t hotkey_report_mode_show(struct device *dev,
2881                            struct device_attribute *attr,
2882                            char *buf)
2883 {
2884         return snprintf(buf, PAGE_SIZE, "%d\n",
2885                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2886 }
2887
2888 static struct device_attribute dev_attr_hotkey_report_mode =
2889         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2890
2891 /* sysfs wakeup reason (pollable) -------------------------------------- */
2892 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2893                            struct device_attribute *attr,
2894                            char *buf)
2895 {
2896         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2897 }
2898
2899 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2900         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2901
2902 static void hotkey_wakeup_reason_notify_change(void)
2903 {
2904         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2905                      "wakeup_reason");
2906 }
2907
2908 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2909 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2910                            struct device_attribute *attr,
2911                            char *buf)
2912 {
2913         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2914 }
2915
2916 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2917         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2918                hotkey_wakeup_hotunplug_complete_show, NULL);
2919
2920 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2921 {
2922         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2923                      "wakeup_hotunplug_complete");
2924 }
2925
2926 /* --------------------------------------------------------------------- */
2927
2928 static struct attribute *hotkey_attributes[] __initdata = {
2929         &dev_attr_hotkey_enable.attr,
2930         &dev_attr_hotkey_bios_enabled.attr,
2931         &dev_attr_hotkey_bios_mask.attr,
2932         &dev_attr_hotkey_report_mode.attr,
2933         &dev_attr_hotkey_wakeup_reason.attr,
2934         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2935         &dev_attr_hotkey_mask.attr,
2936         &dev_attr_hotkey_all_mask.attr,
2937         &dev_attr_hotkey_recommended_mask.attr,
2938 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2939         &dev_attr_hotkey_source_mask.attr,
2940         &dev_attr_hotkey_poll_freq.attr,
2941 #endif
2942 };
2943
2944 /*
2945  * Sync both the hw and sw blocking state of all switches
2946  */
2947 static void tpacpi_send_radiosw_update(void)
2948 {
2949         int wlsw;
2950
2951         /*
2952          * We must sync all rfkill controllers *before* issuing any
2953          * rfkill input events, or we will race the rfkill core input
2954          * handler.
2955          *
2956          * tpacpi_inputdev_send_mutex works as a syncronization point
2957          * for the above.
2958          *
2959          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2960          */
2961
2962         wlsw = hotkey_get_wlsw();
2963
2964         /* Sync hw blocking state first if it is hw-blocked */
2965         if (wlsw == TPACPI_RFK_RADIO_OFF)
2966                 tpacpi_rfk_update_hwblock_state(true);
2967
2968         /* Sync sw blocking state */
2969         tpacpi_rfk_update_swstate_all();
2970
2971         /* Sync hw blocking state last if it is hw-unblocked */
2972         if (wlsw == TPACPI_RFK_RADIO_ON)
2973                 tpacpi_rfk_update_hwblock_state(false);
2974
2975         /* Issue rfkill input event for WLSW switch */
2976         if (!(wlsw < 0)) {
2977                 mutex_lock(&tpacpi_inputdev_send_mutex);
2978
2979                 input_report_switch(tpacpi_inputdev,
2980                                     SW_RFKILL_ALL, (wlsw > 0));
2981                 input_sync(tpacpi_inputdev);
2982
2983                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2984         }
2985
2986         /*
2987          * this can be unconditional, as we will poll state again
2988          * if userspace uses the notify to read data
2989          */
2990         hotkey_radio_sw_notify_change();
2991 }
2992
2993 static void hotkey_exit(void)
2994 {
2995 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2996         mutex_lock(&hotkey_mutex);
2997         hotkey_poll_stop_sync();
2998         mutex_unlock(&hotkey_mutex);
2999 #endif
3000
3001         if (hotkey_dev_attributes)
3002                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3003
3004         kfree(hotkey_keycode_map);
3005
3006         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
3007                    "restoring original HKEY status and mask\n");
3008         /* yes, there is a bitwise or below, we want the
3009          * functions to be called even if one of them fail */
3010         if (((tp_features.hotkey_mask &&
3011               hotkey_mask_set(hotkey_orig_mask)) |
3012              hotkey_status_set(false)) != 0)
3013                 printk(TPACPI_ERR
3014                        "failed to restore hot key mask "
3015                        "to BIOS defaults\n");
3016 }
3017
3018 static void __init hotkey_unmap(const unsigned int scancode)
3019 {
3020         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
3021                 clear_bit(hotkey_keycode_map[scancode],
3022                           tpacpi_inputdev->keybit);
3023                 hotkey_keycode_map[scancode] = KEY_RESERVED;
3024         }
3025 }
3026
3027 /*
3028  * HKEY quirks:
3029  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
3030  */
3031
3032 #define TPACPI_HK_Q_INIMASK     0x0001
3033
3034 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
3035         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
3036         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
3037         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
3038         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
3039         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
3040         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
3041         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
3042         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
3043         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
3044         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
3045         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
3046         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
3047         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
3048         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
3049         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
3050         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
3051         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
3052         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
3053         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
3054 };
3055
3056 static int __init hotkey_init(struct ibm_init_struct *iibm)
3057 {
3058         /* Requirements for changing the default keymaps:
3059          *
3060          * 1. Many of the keys are mapped to KEY_RESERVED for very
3061          *    good reasons.  Do not change them unless you have deep
3062          *    knowledge on the IBM and Lenovo ThinkPad firmware for
3063          *    the various ThinkPad models.  The driver behaves
3064          *    differently for KEY_RESERVED: such keys have their
3065          *    hot key mask *unset* in mask_recommended, and also
3066          *    in the initial hot key mask programmed into the
3067          *    firmware at driver load time, which means the firm-
3068          *    ware may react very differently if you change them to
3069          *    something else;
3070          *
3071          * 2. You must be subscribed to the linux-thinkpad and
3072          *    ibm-acpi-devel mailing lists, and you should read the
3073          *    list archives since 2007 if you want to change the
3074          *    keymaps.  This requirement exists so that you will
3075          *    know the past history of problems with the thinkpad-
3076          *    acpi driver keymaps, and also that you will be
3077          *    listening to any bug reports;
3078          *
3079          * 3. Do not send thinkpad-acpi specific patches directly to
3080          *    for merging, *ever*.  Send them to the linux-acpi
3081          *    mailinglist for comments.  Merging is to be done only
3082          *    through acpi-test and the ACPI maintainer.
3083          *
3084          * If the above is too much to ask, don't change the keymap.
3085          * Ask the thinkpad-acpi maintainer to do it, instead.
3086          */
3087         static u16 ibm_keycode_map[] __initdata = {
3088                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3089                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
3090                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3091                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3092
3093                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3094                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3095                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3096                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3097
3098                 /* brightness: firmware always reacts to them */
3099                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3100                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3101
3102                 /* Thinklight: firmware always react to it */
3103                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3104
3105                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3106                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3107
3108                 /* Volume: firmware always react to it and reprograms
3109                  * the built-in *extra* mixer.  Never map it to control
3110                  * another mixer by default. */
3111                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3112                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3113                 KEY_RESERVED,   /* 0x16: MUTE */
3114
3115                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3116
3117                 /* (assignments unknown, please report if found) */
3118                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3119                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3120         };
3121         static u16 lenovo_keycode_map[] __initdata = {
3122                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3123                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3124                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3125                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3126
3127                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3128                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3129                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3130                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3131
3132                 /* These should be enabled --only-- when ACPI video
3133                  * is disabled (i.e. in "vendor" mode), and are handled
3134                  * in a special way by the init code */
3135                 KEY_BRIGHTNESSUP,       /* 0x0F: FN+HOME (brightness up) */
3136                 KEY_BRIGHTNESSDOWN,     /* 0x10: FN+END (brightness down) */
3137
3138                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3139
3140                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3141                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3142
3143                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
3144                  * react to it and reprograms the built-in *extra* mixer.
3145                  * Never map it to control another mixer by default.
3146                  *
3147                  * T60?, T61, R60?, R61: firmware and EC tries to send
3148                  * these over the regular keyboard, so these are no-ops,
3149                  * but there are still weird bugs re. MUTE, so do not
3150                  * change unless you get test reports from all Lenovo
3151                  * models.  May cause the BIOS to interfere with the
3152                  * HDA mixer.
3153                  */
3154                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3155                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3156                 KEY_RESERVED,   /* 0x16: MUTE */
3157
3158                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3159
3160                 /* (assignments unknown, please report if found) */
3161                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3162                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3163         };
3164
3165 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
3166 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
3167 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
3168
3169         int res, i;
3170         int status;
3171         int hkeyv;
3172         bool radiosw_state  = false;
3173         bool tabletsw_state = false;
3174
3175         unsigned long quirks;
3176
3177         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3178                         "initializing hotkey subdriver\n");
3179
3180         BUG_ON(!tpacpi_inputdev);
3181         BUG_ON(tpacpi_inputdev->open != NULL ||
3182                tpacpi_inputdev->close != NULL);
3183
3184         TPACPI_ACPIHANDLE_INIT(hkey);
3185         mutex_init(&hotkey_mutex);
3186
3187 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3188         mutex_init(&hotkey_thread_mutex);
3189         mutex_init(&hotkey_thread_data_mutex);
3190 #endif
3191
3192         /* hotkey not supported on 570 */
3193         tp_features.hotkey = hkey_handle != NULL;
3194
3195         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3196                 "hotkeys are %s\n",
3197                 str_supported(tp_features.hotkey));
3198
3199         if (!tp_features.hotkey)
3200                 return 1;
3201
3202         quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable,
3203                                      ARRAY_SIZE(tpacpi_hotkey_qtable));
3204
3205         tpacpi_disable_brightness_delay();
3206
3207         /* MUST have enough space for all attributes to be added to
3208          * hotkey_dev_attributes */
3209         hotkey_dev_attributes = create_attr_set(
3210                                         ARRAY_SIZE(hotkey_attributes) + 2,
3211                                         NULL);
3212         if (!hotkey_dev_attributes)
3213                 return -ENOMEM;
3214         res = add_many_to_attr_set(hotkey_dev_attributes,
3215                         hotkey_attributes,
3216                         ARRAY_SIZE(hotkey_attributes));
3217         if (res)
3218                 goto err_exit;
3219
3220         /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p,
3221            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
3222            for HKEY interface version 0x100 */
3223         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
3224                 if ((hkeyv >> 8) != 1) {
3225                         printk(TPACPI_ERR "unknown version of the "
3226                                "HKEY interface: 0x%x\n", hkeyv);
3227                         printk(TPACPI_ERR "please report this to %s\n",
3228                                TPACPI_MAIL);
3229                 } else {
3230                         /*
3231                          * MHKV 0x100 in A31, R40, R40e,
3232                          * T4x, X31, and later
3233                          */
3234                         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3235                                 "firmware HKEY interface version: 0x%x\n",
3236                                 hkeyv);
3237
3238                         /* Paranoia check AND init hotkey_all_mask */
3239                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3240                                         "MHKA", "qd")) {
3241                                 printk(TPACPI_ERR
3242                                        "missing MHKA handler, "
3243                                        "please report this to %s\n",
3244                                        TPACPI_MAIL);
3245                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3246                                 hotkey_all_mask = 0x080cU;
3247                         } else {
3248                                 tp_features.hotkey_mask = 1;
3249                         }
3250                 }
3251         }
3252
3253         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3254                 "hotkey masks are %s\n",
3255                 str_supported(tp_features.hotkey_mask));
3256
3257         /* Init hotkey_all_mask if not initialized yet */
3258         if (!tp_features.hotkey_mask && !hotkey_all_mask &&
3259             (quirks & TPACPI_HK_Q_INIMASK))
3260                 hotkey_all_mask = 0x080cU;  /* FN+F12, FN+F4, FN+F3 */
3261
3262         /* Init hotkey_acpi_mask and hotkey_orig_mask */
3263         if (tp_features.hotkey_mask) {
3264                 /* hotkey_source_mask *must* be zero for
3265                  * the first hotkey_mask_get to return hotkey_orig_mask */
3266                 res = hotkey_mask_get();
3267                 if (res)
3268                         goto err_exit;
3269
3270                 hotkey_orig_mask = hotkey_acpi_mask;
3271         } else {
3272                 hotkey_orig_mask = hotkey_all_mask;
3273                 hotkey_acpi_mask = hotkey_all_mask;
3274         }
3275
3276 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3277         if (dbg_wlswemul) {
3278                 tp_features.hotkey_wlsw = 1;
3279                 radiosw_state = !!tpacpi_wlsw_emulstate;
3280                 printk(TPACPI_INFO
3281                         "radio switch emulation enabled\n");
3282         } else
3283 #endif
3284         /* Not all thinkpads have a hardware radio switch */
3285         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
3286                 tp_features.hotkey_wlsw = 1;
3287                 radiosw_state = !!status;
3288                 printk(TPACPI_INFO
3289                         "radio switch found; radios are %s\n",
3290                         enabled(status, 0));
3291         }
3292         if (tp_features.hotkey_wlsw)
3293                 res = add_to_attr_set(hotkey_dev_attributes,
3294                                 &dev_attr_hotkey_radio_sw.attr);
3295
3296         /* For X41t, X60t, X61t Tablets... */
3297         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
3298                 tp_features.hotkey_tablet = 1;
3299                 tabletsw_state = !!(status & TP_HOTKEY_TABLET_MASK);
3300                 printk(TPACPI_INFO
3301                         "possible tablet mode switch found; "
3302                         "ThinkPad in %s mode\n",
3303                         (tabletsw_state) ? "tablet" : "laptop");
3304                 res = add_to_attr_set(hotkey_dev_attributes,
3305                                 &dev_attr_hotkey_tablet_mode.attr);
3306         }
3307
3308         if (!res)
3309                 res = register_attr_set_with_sysfs(
3310                                 hotkey_dev_attributes,
3311                                 &tpacpi_pdev->dev.kobj);
3312         if (res)
3313                 goto err_exit;
3314
3315         /* Set up key map */
3316
3317         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
3318                                         GFP_KERNEL);
3319         if (!hotkey_keycode_map) {
3320                 printk(TPACPI_ERR
3321                         "failed to allocate memory for key map\n");
3322                 res = -ENOMEM;
3323                 goto err_exit;
3324         }
3325
3326         if (tpacpi_is_lenovo()) {
3327                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3328                            "using Lenovo default hot key map\n");
3329                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
3330                         TPACPI_HOTKEY_MAP_SIZE);
3331         } else {
3332                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3333                            "using IBM default hot key map\n");
3334                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
3335                         TPACPI_HOTKEY_MAP_SIZE);
3336         }
3337
3338         input_set_capability(tpacpi_inputdev, EV_MSC, MSC_SCAN);
3339         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
3340         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
3341         tpacpi_inputdev->keycode = hotkey_keycode_map;
3342         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
3343                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
3344                         input_set_capability(tpacpi_inputdev, EV_KEY,
3345                                                 hotkey_keycode_map[i]);
3346                 } else {
3347                         if (i < sizeof(hotkey_reserved_mask)*8)
3348                                 hotkey_reserved_mask |= 1 << i;
3349                 }
3350         }
3351
3352         if (tp_features.hotkey_wlsw) {
3353                 input_set_capability(tpacpi_inputdev, EV_SW, SW_RFKILL_ALL);
3354                 input_report_switch(tpacpi_inputdev,
3355                                     SW_RFKILL_ALL, radiosw_state);
3356         }
3357         if (tp_features.hotkey_tablet) {
3358                 input_set_capability(tpacpi_inputdev, EV_SW, SW_TABLET_MODE);
3359                 input_report_switch(tpacpi_inputdev,
3360                                     SW_TABLET_MODE, tabletsw_state);
3361         }
3362
3363         /* Do not issue duplicate brightness change events to
3364          * userspace. tpacpi_detect_brightness_capabilities() must have
3365          * been called before this point  */
3366         if (tp_features.bright_acpimode && acpi_video_backlight_support()) {
3367                 printk(TPACPI_INFO
3368                        "This ThinkPad has standard ACPI backlight "
3369                        "brightness control, supported by the ACPI "
3370                        "video driver\n");
3371                 printk(TPACPI_NOTICE
3372                        "Disabling thinkpad-acpi brightness events "
3373                        "by default...\n");
3374
3375                 /* Disable brightness up/down on Lenovo thinkpads when
3376                  * ACPI is handling them, otherwise it is plain impossible
3377                  * for userspace to do something even remotely sane */
3378                 hotkey_reserved_mask |=
3379                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
3380                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
3381                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME);
3382                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND);
3383         }
3384
3385 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3386         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
3387                                 & ~hotkey_all_mask
3388                                 & ~hotkey_reserved_mask;
3389
3390         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3391                     "hotkey source mask 0x%08x, polling freq %u\n",
3392                     hotkey_source_mask, hotkey_poll_freq);
3393 #endif
3394
3395         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3396                         "enabling firmware HKEY event interface...\n");
3397         res = hotkey_status_set(true);
3398         if (res) {
3399                 hotkey_exit();
3400                 return res;
3401         }
3402         res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask)
3403                                | hotkey_driver_mask)
3404                               & ~hotkey_source_mask);
3405         if (res < 0 && res != -ENXIO) {
3406                 hotkey_exit();
3407                 return res;
3408         }
3409         hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask)
3410                                 & ~hotkey_reserved_mask;
3411         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3412                 "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n",
3413                 hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask);
3414
3415         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3416                         "legacy ibm/hotkey event reporting over procfs %s\n",
3417                         (hotkey_report_mode < 2) ?
3418                                 "enabled" : "disabled");
3419
3420         tpacpi_inputdev->open = &hotkey_inputdev_open;
3421         tpacpi_inputdev->close = &hotkey_inputdev_close;
3422
3423         hotkey_poll_setup_safe(true);
3424
3425         return 0;
3426
3427 err_exit:
3428         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3429         hotkey_dev_attributes = NULL;
3430
3431         return (res < 0)? res : 1;
3432 }
3433
3434 static bool hotkey_notify_hotkey(const u32 hkey,
3435                                  bool *send_acpi_ev,
3436                                  bool *ignore_acpi_ev)
3437 {
3438         /* 0x1000-0x1FFF: key presses */
3439         unsigned int scancode = hkey & 0xfff;
3440         *send_acpi_ev = true;
3441         *ignore_acpi_ev = false;
3442
3443         if (scancode > 0 && scancode < 0x21) {
3444                 scancode--;
3445                 if (!(hotkey_source_mask & (1 << scancode))) {
3446                         tpacpi_input_send_key_masked(scancode);
3447                         *send_acpi_ev = false;
3448                 } else {
3449                         *ignore_acpi_ev = true;
3450                 }
3451                 return true;
3452         }
3453         return false;
3454 }
3455
3456 static bool hotkey_notify_wakeup(const u32 hkey,
3457                                  bool *send_acpi_ev,
3458                                  bool *ignore_acpi_ev)
3459 {
3460         /* 0x2000-0x2FFF: Wakeup reason */
3461         *send_acpi_ev = true;
3462         *ignore_acpi_ev = false;
3463
3464         switch (hkey) {
3465         case TP_HKEY_EV_WKUP_S3_UNDOCK: /* suspend, undock */
3466         case TP_HKEY_EV_WKUP_S4_UNDOCK: /* hibernation, undock */
3467                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3468                 *ignore_acpi_ev = true;
3469                 break;
3470
3471         case TP_HKEY_EV_WKUP_S3_BAYEJ: /* suspend, bay eject */
3472         case TP_HKEY_EV_WKUP_S4_BAYEJ: /* hibernation, bay eject */
3473                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3474                 *ignore_acpi_ev = true;
3475                 break;
3476
3477         case TP_HKEY_EV_WKUP_S3_BATLOW: /* Battery on critical low level/S3 */
3478         case TP_HKEY_EV_WKUP_S4_BATLOW: /* Battery on critical low level/S4 */
3479                 printk(TPACPI_ALERT
3480                         "EMERGENCY WAKEUP: battery almost empty\n");
3481                 /* how to auto-heal: */
3482                 /* 2313: woke up from S3, go to S4/S5 */
3483                 /* 2413: woke up from S4, go to S5 */
3484                 break;
3485
3486         default:
3487                 return false;
3488         }
3489
3490         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3491                 printk(TPACPI_INFO
3492                        "woke up due to a hot-unplug "
3493                        "request...\n");
3494                 hotkey_wakeup_reason_notify_change();
3495         }
3496         return true;
3497 }
3498
3499 static bool hotkey_notify_usrevent(const u32 hkey,
3500                                  bool *send_acpi_ev,
3501                                  bool *ignore_acpi_ev)
3502 {
3503         /* 0x5000-0x5FFF: human interface helpers */
3504         *send_acpi_ev = true;
3505         *ignore_acpi_ev = false;
3506
3507         switch (hkey) {
3508         case TP_HKEY_EV_PEN_INSERTED:  /* X61t: tablet pen inserted into bay */
3509         case TP_HKEY_EV_PEN_REMOVED:   /* X61t: tablet pen removed from bay */
3510                 return true;
3511
3512         case TP_HKEY_EV_TABLET_TABLET:   /* X41t-X61t: tablet mode */
3513         case TP_HKEY_EV_TABLET_NOTEBOOK: /* X41t-X61t: normal mode */
3514                 tpacpi_input_send_tabletsw();
3515                 hotkey_tablet_mode_notify_change();
3516                 *send_acpi_ev = false;
3517                 return true;
3518
3519         case TP_HKEY_EV_LID_CLOSE:      /* Lid closed */
3520         case TP_HKEY_EV_LID_OPEN:       /* Lid opened */
3521         case TP_HKEY_EV_BRGHT_CHANGED:  /* brightness changed */
3522                 /* do not propagate these events */
3523                 *ignore_acpi_ev = true;
3524                 return true;
3525
3526         default:
3527                 return false;
3528         }
3529 }
3530
3531 static void thermal_dump_all_sensors(void);
3532
3533 static bool hotkey_notify_thermal(const u32 hkey,
3534                                  bool *send_acpi_ev,
3535                                  bool *ignore_acpi_ev)
3536 {
3537         bool known = true;
3538
3539         /* 0x6000-0x6FFF: thermal alarms */
3540         *send_acpi_ev = true;
3541         *ignore_acpi_ev = false;
3542
3543         switch (hkey) {
3544         case TP_HKEY_EV_THM_TABLE_CHANGED:
3545                 printk(TPACPI_INFO
3546                         "EC reports that Thermal Table has changed\n");
3547                 /* recommended action: do nothing, we don't have
3548                  * Lenovo ATM information */
3549                 return true;
3550         case TP_HKEY_EV_ALARM_BAT_HOT:
3551                 printk(TPACPI_CRIT
3552                         "THERMAL ALARM: battery is too hot!\n");
3553                 /* recommended action: warn user through gui */
3554                 break;
3555         case TP_HKEY_EV_ALARM_BAT_XHOT:
3556                 printk(TPACPI_ALERT
3557                         "THERMAL EMERGENCY: battery is extremely hot!\n");
3558                 /* recommended action: immediate sleep/hibernate */
3559                 break;
3560         case TP_HKEY_EV_ALARM_SENSOR_HOT:
3561                 printk(TPACPI_CRIT
3562                         "THERMAL ALARM: "
3563                         "a sensor reports something is too hot!\n");
3564                 /* recommended action: warn user through gui, that */
3565                 /* some internal component is too hot */
3566                 break;
3567         case TP_HKEY_EV_ALARM_SENSOR_XHOT:
3568                 printk(TPACPI_ALERT
3569                         "THERMAL EMERGENCY: "
3570                         "a sensor reports something is extremely hot!\n");
3571                 /* recommended action: immediate sleep/hibernate */
3572                 break;
3573         default:
3574                 printk(TPACPI_ALERT
3575                          "THERMAL ALERT: unknown thermal alarm received\n");
3576                 known = false;
3577         }
3578
3579         thermal_dump_all_sensors();
3580
3581         return known;
3582 }
3583
3584 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3585 {
3586         u32 hkey;
3587         bool send_acpi_ev;
3588         bool ignore_acpi_ev;
3589         bool known_ev;
3590
3591         if (event != 0x80) {
3592                 printk(TPACPI_ERR
3593                        "unknown HKEY notification event %d\n", event);
3594                 /* forward it to userspace, maybe it knows how to handle it */
3595                 acpi_bus_generate_netlink_event(
3596                                         ibm->acpi->device->pnp.device_class,
3597                                         dev_name(&ibm->acpi->device->dev),
3598                                         event, 0);
3599                 return;
3600         }
3601
3602         while (1) {
3603                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
3604                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
3605                         return;
3606                 }
3607
3608                 if (hkey == 0) {
3609                         /* queue empty */
3610                         return;
3611                 }
3612
3613                 send_acpi_ev = true;
3614                 ignore_acpi_ev = false;
3615
3616                 switch (hkey >> 12) {
3617                 case 1:
3618                         /* 0x1000-0x1FFF: key presses */
3619                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
3620                                                  &ignore_acpi_ev);
3621                         break;
3622                 case 2:
3623                         /* 0x2000-0x2FFF: Wakeup reason */
3624                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
3625                                                  &ignore_acpi_ev);
3626                         break;
3627                 case 3:
3628                         /* 0x3000-0x3FFF: bay-related wakeups */
3629                         switch (hkey) {
3630                         case TP_HKEY_EV_BAYEJ_ACK:
3631                                 hotkey_autosleep_ack = 1;
3632                                 printk(TPACPI_INFO
3633                                        "bay ejected\n");
3634                                 hotkey_wakeup_hotunplug_complete_notify_change();
3635                                 known_ev = true;
3636                                 break;
3637                         case TP_HKEY_EV_OPTDRV_EJ:
3638                                 /* FIXME: kick libata if SATA link offline */
3639                                 known_ev = true;
3640                                 break;
3641                         default:
3642                                 known_ev = false;
3643                         }
3644                         break;
3645                 case 4:
3646                         /* 0x4000-0x4FFF: dock-related wakeups */
3647                         if (hkey == TP_HKEY_EV_UNDOCK_ACK) {
3648                                 hotkey_autosleep_ack = 1;
3649                                 printk(TPACPI_INFO
3650                                        "undocked\n");
3651                                 hotkey_wakeup_hotunplug_complete_notify_change();
3652                                 known_ev = true;
3653                         } else {
3654                                 known_ev = false;
3655                         }
3656                         break;
3657                 case 5:
3658                         /* 0x5000-0x5FFF: human interface helpers */
3659                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
3660                                                  &ignore_acpi_ev);
3661                         break;
3662                 case 6:
3663                         /* 0x6000-0x6FFF: thermal alarms */
3664                         known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev,
3665                                                  &ignore_acpi_ev);
3666                         break;
3667                 case 7:
3668                         /* 0x7000-0x7FFF: misc */
3669                         if (tp_features.hotkey_wlsw &&
3670                                         hkey == TP_HKEY_EV_RFKILL_CHANGED) {
3671                                 tpacpi_send_radiosw_update();
3672                                 send_acpi_ev = 0;
3673                                 known_ev = true;
3674                                 break;
3675                         }
3676                         /* fallthrough to default */
3677                 default:
3678                         known_ev = false;
3679                 }
3680                 if (!known_ev) {
3681                         printk(TPACPI_NOTICE
3682                                "unhandled HKEY event 0x%04x\n", hkey);
3683                         printk(TPACPI_NOTICE
3684                                "please report the conditions when this "
3685                                "event happened to %s\n", TPACPI_MAIL);
3686                 }
3687
3688                 /* Legacy events */
3689                 if (!ignore_acpi_ev &&
3690                     (send_acpi_ev || hotkey_report_mode < 2)) {
3691                         acpi_bus_generate_proc_event(ibm->acpi->device,
3692                                                      event, hkey);
3693                 }
3694
3695                 /* netlink events */
3696                 if (!ignore_acpi_ev && send_acpi_ev) {
3697                         acpi_bus_generate_netlink_event(
3698                                         ibm->acpi->device->pnp.device_class,
3699                                         dev_name(&ibm->acpi->device->dev),
3700                                         event, hkey);
3701                 }
3702         }
3703 }
3704
3705 static void hotkey_suspend(pm_message_t state)
3706 {
3707         /* Do these on suspend, we get the events on early resume! */
3708         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
3709         hotkey_autosleep_ack = 0;
3710 }
3711
3712 static void hotkey_resume(void)
3713 {
3714         tpacpi_disable_brightness_delay();
3715
3716         if (hotkey_status_set(true) < 0 ||
3717             hotkey_mask_set(hotkey_acpi_mask) < 0)
3718                 printk(TPACPI_ERR
3719                        "error while attempting to reset the event "
3720                        "firmware interface\n");
3721
3722         tpacpi_send_radiosw_update();
3723         hotkey_tablet_mode_notify_change();
3724         hotkey_wakeup_reason_notify_change();
3725         hotkey_wakeup_hotunplug_complete_notify_change();
3726         hotkey_poll_setup_safe(false);
3727 }
3728
3729 /* procfs -------------------------------------------------------------- */
3730 static int hotkey_read(struct seq_file *m)
3731 {
3732         int res, status;
3733
3734         if (!tp_features.hotkey) {
3735                 seq_printf(m, "status:\t\tnot supported\n");
3736                 return 0;
3737         }
3738
3739         if (mutex_lock_killable(&hotkey_mutex))
3740                 return -ERESTARTSYS;
3741         res = hotkey_status_get(&status);
3742         if (!res)
3743                 res = hotkey_mask_get();
3744         mutex_unlock(&hotkey_mutex);
3745         if (res)
3746                 return res;
3747
3748         seq_printf(m, "status:\t\t%s\n", enabled(status, 0));
3749         if (hotkey_all_mask) {
3750                 seq_printf(m, "mask:\t\t0x%08x\n", hotkey_user_mask);
3751                 seq_printf(m, "commands:\tenable, disable, reset, <mask>\n");
3752         } else {
3753                 seq_printf(m, "mask:\t\tnot supported\n");
3754                 seq_printf(m, "commands:\tenable, disable, reset\n");
3755         }
3756
3757         return 0;
3758 }
3759
3760 static void hotkey_enabledisable_warn(bool enable)
3761 {
3762         tpacpi_log_usertask("procfs hotkey enable/disable");
3763         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
3764                         TPACPI_WARN
3765                         "hotkey enable/disable functionality has been "
3766                         "removed from the driver.  Hotkeys are always "
3767                         "enabled\n"))
3768                 printk(TPACPI_ERR
3769                         "Please remove the hotkey=enable module "
3770                         "parameter, it is deprecated.  Hotkeys are always "
3771                         "enabled\n");
3772 }
3773
3774 static int hotkey_write(char *buf)
3775 {
3776         int res;
3777         u32 mask;
3778         char *cmd;
3779
3780         if (!tp_features.hotkey)
3781                 return -ENODEV;
3782
3783         if (mutex_lock_killable(&hotkey_mutex))
3784                 return -ERESTARTSYS;
3785
3786         mask = hotkey_user_mask;
3787
3788         res = 0;
3789         while ((cmd = next_cmd(&buf))) {
3790                 if (strlencmp(cmd, "enable") == 0) {
3791                         hotkey_enabledisable_warn(1);
3792                 } else if (strlencmp(cmd, "disable") == 0) {
3793                         hotkey_enabledisable_warn(0);
3794                         res = -EPERM;
3795                 } else if (strlencmp(cmd, "reset") == 0) {
3796                         mask = (hotkey_all_mask | hotkey_source_mask)
3797                                 & ~hotkey_reserved_mask;
3798                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
3799                         /* mask set */
3800                 } else if (sscanf(cmd, "%x", &mask) == 1) {
3801                         /* mask set */
3802                 } else {
3803                         res = -EINVAL;
3804                         goto errexit;
3805                 }
3806         }
3807
3808         if (!res) {
3809                 tpacpi_disclose_usertask("procfs hotkey",
3810                         "set mask to 0x%08x\n", mask);
3811                 res = hotkey_user_mask_set(mask);
3812         }
3813
3814 errexit:
3815         mutex_unlock(&hotkey_mutex);
3816         return res;
3817 }
3818
3819 static const struct acpi_device_id ibm_htk_device_ids[] = {
3820         {TPACPI_ACPI_HKEY_HID, 0},
3821         {"", 0},
3822 };
3823
3824 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
3825         .hid = ibm_htk_device_ids,
3826         .notify = hotkey_notify,
3827         .handle = &hkey_handle,
3828         .type = ACPI_DEVICE_NOTIFY,
3829 };
3830
3831 static struct ibm_struct hotkey_driver_data = {
3832         .name = "hotkey",
3833         .read = hotkey_read,
3834         .write = hotkey_write,
3835         .exit = hotkey_exit,
3836         .resume = hotkey_resume,
3837         .suspend = hotkey_suspend,
3838         .acpi = &ibm_hotkey_acpidriver,
3839 };
3840
3841 /*************************************************************************
3842  * Bluetooth subdriver
3843  */
3844
3845 enum {
3846         /* ACPI GBDC/SBDC bits */
3847         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
3848         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
3849         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
3850                                                    0 = disable, 1 = enable */
3851 };
3852
3853 enum {
3854         /* ACPI \BLTH commands */
3855         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
3856         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
3857         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
3858         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
3859         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
3860 };
3861
3862 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
3863
3864 static int bluetooth_get_status(void)
3865 {
3866         int status;
3867
3868 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3869         if (dbg_bluetoothemul)
3870                 return (tpacpi_bluetooth_emulstate) ?
3871                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3872 #endif
3873
3874         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
3875                 return -EIO;
3876
3877         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
3878                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3879 }
3880
3881 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
3882 {
3883         int status;
3884
3885         vdbg_printk(TPACPI_DBG_RFKILL,
3886                 "will attempt to %s bluetooth\n",
3887                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3888
3889 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3890         if (dbg_bluetoothemul) {
3891                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
3892                 return 0;
3893         }
3894 #endif
3895
3896         if (state == TPACPI_RFK_RADIO_ON)
3897                 status = TP_ACPI_BLUETOOTH_RADIOSSW
3898                           | TP_ACPI_BLUETOOTH_RESUMECTRL;
3899         else
3900                 status = 0;
3901
3902         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
3903                 return -EIO;
3904
3905         return 0;
3906 }
3907
3908 /* sysfs bluetooth enable ---------------------------------------------- */
3909 static ssize_t bluetooth_enable_show(struct device *dev,
3910                            struct device_attribute *attr,
3911                            char *buf)
3912 {
3913         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
3914                         attr, buf);
3915 }
3916
3917 static ssize_t bluetooth_enable_store(struct device *dev,
3918                             struct device_attribute *attr,
3919                             const char *buf, size_t count)
3920 {
3921         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
3922                                 attr, buf, count);
3923 }
3924
3925 static struct device_attribute dev_attr_bluetooth_enable =
3926         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
3927                 bluetooth_enable_show, bluetooth_enable_store);
3928
3929 /* --------------------------------------------------------------------- */
3930
3931 static struct attribute *bluetooth_attributes[] = {
3932         &dev_attr_bluetooth_enable.attr,
3933         NULL
3934 };
3935
3936 static const struct attribute_group bluetooth_attr_group = {
3937         .attrs = bluetooth_attributes,
3938 };
3939
3940 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
3941         .get_status = bluetooth_get_status,
3942         .set_status = bluetooth_set_status,
3943 };
3944
3945 static void bluetooth_shutdown(void)
3946 {
3947         /* Order firmware to save current state to NVRAM */
3948         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3949                         TP_ACPI_BLTH_SAVE_STATE))
3950                 printk(TPACPI_NOTICE
3951                         "failed to save bluetooth state to NVRAM\n");
3952         else
3953                 vdbg_printk(TPACPI_DBG_RFKILL,
3954                         "bluestooth state saved to NVRAM\n");
3955 }
3956
3957 static void bluetooth_exit(void)
3958 {
3959         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3960                         &bluetooth_attr_group);
3961
3962         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3963
3964         bluetooth_shutdown();
3965 }
3966
3967 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3968 {
3969         int res;
3970         int status = 0;
3971
3972         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3973                         "initializing bluetooth subdriver\n");
3974
3975         TPACPI_ACPIHANDLE_INIT(hkey);
3976
3977         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3978            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
3979         tp_features.bluetooth = hkey_handle &&
3980             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
3981
3982         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3983                 "bluetooth is %s, status 0x%02x\n",
3984                 str_supported(tp_features.bluetooth),
3985                 status);
3986
3987 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3988         if (dbg_bluetoothemul) {
3989                 tp_features.bluetooth = 1;
3990                 printk(TPACPI_INFO
3991                         "bluetooth switch emulation enabled\n");
3992         } else
3993 #endif
3994         if (tp_features.bluetooth &&
3995             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
3996                 /* no bluetooth hardware present in system */
3997                 tp_features.bluetooth = 0;
3998                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3999                            "bluetooth hardware not installed\n");
4000         }
4001
4002         if (!tp_features.bluetooth)
4003                 return 1;
4004
4005         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
4006                                 &bluetooth_tprfk_ops,
4007                                 RFKILL_TYPE_BLUETOOTH,
4008                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
4009                                 true);
4010         if (res)
4011                 return res;
4012
4013         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4014                                 &bluetooth_attr_group);
4015         if (res) {
4016                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
4017                 return res;
4018         }
4019
4020         return 0;
4021 }
4022
4023 /* procfs -------------------------------------------------------------- */
4024 static int bluetooth_read(struct seq_file *m)
4025 {
4026         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, m);
4027 }
4028
4029 static int bluetooth_write(char *buf)
4030 {
4031         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
4032 }
4033
4034 static struct ibm_struct bluetooth_driver_data = {
4035         .name = "bluetooth",
4036         .read = bluetooth_read,
4037         .write = bluetooth_write,
4038         .exit = bluetooth_exit,
4039         .shutdown = bluetooth_shutdown,
4040 };
4041
4042 /*************************************************************************
4043  * Wan subdriver
4044  */
4045
4046 enum {
4047         /* ACPI GWAN/SWAN bits */
4048         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
4049         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
4050         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
4051                                                    0 = disable, 1 = enable */
4052 };
4053
4054 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
4055
4056 static int wan_get_status(void)
4057 {
4058         int status;
4059
4060 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4061         if (dbg_wwanemul)
4062                 return (tpacpi_wwan_emulstate) ?
4063                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4064 #endif
4065
4066         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
4067                 return -EIO;
4068
4069         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
4070                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4071 }
4072
4073 static int wan_set_status(enum tpacpi_rfkill_state state)
4074 {
4075         int status;
4076
4077         vdbg_printk(TPACPI_DBG_RFKILL,
4078                 "will attempt to %s wwan\n",
4079                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4080
4081 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4082         if (dbg_wwanemul) {
4083                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
4084                 return 0;
4085         }
4086 #endif
4087
4088         if (state == TPACPI_RFK_RADIO_ON)
4089                 status = TP_ACPI_WANCARD_RADIOSSW
4090                          | TP_ACPI_WANCARD_RESUMECTRL;
4091         else
4092                 status = 0;
4093
4094         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
4095                 return -EIO;
4096
4097         return 0;
4098 }
4099
4100 /* sysfs wan enable ---------------------------------------------------- */
4101 static ssize_t wan_enable_show(struct device *dev,
4102                            struct device_attribute *attr,
4103                            char *buf)
4104 {
4105         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
4106                         attr, buf);
4107 }
4108
4109 static ssize_t wan_enable_store(struct device *dev,
4110                             struct device_attribute *attr,
4111                             const char *buf, size_t count)
4112 {
4113         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
4114                         attr, buf, count);
4115 }
4116
4117 static struct device_attribute dev_attr_wan_enable =
4118         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
4119                 wan_enable_show, wan_enable_store);
4120
4121 /* --------------------------------------------------------------------- */
4122
4123 static struct attribute *wan_attributes[] = {
4124         &dev_attr_wan_enable.attr,
4125         NULL
4126 };
4127
4128 static const struct attribute_group wan_attr_group = {
4129         .attrs = wan_attributes,
4130 };
4131
4132 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
4133         .get_status = wan_get_status,
4134         .set_status = wan_set_status,
4135 };
4136
4137 static void wan_shutdown(void)
4138 {
4139         /* Order firmware to save current state to NVRAM */
4140         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
4141                         TP_ACPI_WGSV_SAVE_STATE))
4142                 printk(TPACPI_NOTICE
4143                         "failed to save WWAN state to NVRAM\n");
4144         else
4145                 vdbg_printk(TPACPI_DBG_RFKILL,
4146                         "WWAN state saved to NVRAM\n");
4147 }
4148
4149 static void wan_exit(void)
4150 {
4151         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4152                 &wan_attr_group);
4153
4154         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4155
4156         wan_shutdown();
4157 }
4158
4159 static int __init wan_init(struct ibm_init_struct *iibm)
4160 {
4161         int res;
4162         int status = 0;
4163
4164         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4165                         "initializing wan subdriver\n");
4166
4167         TPACPI_ACPIHANDLE_INIT(hkey);
4168
4169         tp_features.wan = hkey_handle &&
4170             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
4171
4172         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4173                 "wan is %s, status 0x%02x\n",
4174                 str_supported(tp_features.wan),
4175                 status);
4176
4177 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4178         if (dbg_wwanemul) {
4179                 tp_features.wan = 1;
4180                 printk(TPACPI_INFO
4181                         "wwan switch emulation enabled\n");
4182         } else
4183 #endif
4184         if (tp_features.wan &&
4185             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
4186                 /* no wan hardware present in system */
4187                 tp_features.wan = 0;
4188                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4189                            "wan hardware not installed\n");
4190         }
4191
4192         if (!tp_features.wan)
4193                 return 1;
4194
4195         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
4196                                 &wan_tprfk_ops,
4197                                 RFKILL_TYPE_WWAN,
4198                                 TPACPI_RFK_WWAN_SW_NAME,
4199                                 true);
4200         if (res)
4201                 return res;
4202
4203         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4204                                 &wan_attr_group);
4205
4206         if (res) {
4207                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4208                 return res;
4209         }
4210
4211         return 0;
4212 }
4213
4214 /* procfs -------------------------------------------------------------- */
4215 static int wan_read(struct seq_file *m)
4216 {
4217         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, m);
4218 }
4219
4220 static int wan_write(char *buf)
4221 {
4222         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
4223 }
4224
4225 static struct ibm_struct wan_driver_data = {
4226         .name = "wan",
4227         .read = wan_read,
4228         .write = wan_write,
4229         .exit = wan_exit,
4230         .shutdown = wan_shutdown,
4231 };
4232
4233 /*************************************************************************
4234  * UWB subdriver
4235  */
4236
4237 enum {
4238         /* ACPI GUWB/SUWB bits */
4239         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
4240         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
4241 };
4242
4243 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
4244
4245 static int uwb_get_status(void)
4246 {
4247         int status;
4248
4249 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4250         if (dbg_uwbemul)
4251                 return (tpacpi_uwb_emulstate) ?
4252                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4253 #endif
4254
4255         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
4256                 return -EIO;
4257
4258         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
4259                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4260 }
4261
4262 static int uwb_set_status(enum tpacpi_rfkill_state state)
4263 {
4264         int status;
4265
4266         vdbg_printk(TPACPI_DBG_RFKILL,
4267                 "will attempt to %s UWB\n",
4268                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4269
4270 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4271         if (dbg_uwbemul) {
4272                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
4273                 return 0;
4274         }
4275 #endif
4276
4277         if (state == TPACPI_RFK_RADIO_ON)
4278                 status = TP_ACPI_UWB_RADIOSSW;
4279         else
4280                 status = 0;
4281
4282         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
4283                 return -EIO;
4284
4285         return 0;
4286 }
4287
4288 /* --------------------------------------------------------------------- */
4289
4290 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
4291         .get_status = uwb_get_status,
4292         .set_status = uwb_set_status,
4293 };
4294
4295 static void uwb_exit(void)
4296 {
4297         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
4298 }
4299
4300 static int __init uwb_init(struct ibm_init_struct *iibm)
4301 {
4302         int res;
4303         int status = 0;
4304
4305         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4306                         "initializing uwb subdriver\n");
4307
4308         TPACPI_ACPIHANDLE_INIT(hkey);
4309
4310         tp_features.uwb = hkey_handle &&
4311             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
4312
4313         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4314                 "uwb is %s, status 0x%02x\n",
4315                 str_supported(tp_features.uwb),
4316                 status);
4317
4318 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4319         if (dbg_uwbemul) {
4320                 tp_features.uwb = 1;
4321                 printk(TPACPI_INFO
4322                         "uwb switch emulation enabled\n");
4323         } else
4324 #endif
4325         if (tp_features.uwb &&
4326             !(status & TP_ACPI_UWB_HWPRESENT)) {
4327                 /* no uwb hardware present in system */
4328                 tp_features.uwb = 0;
4329                 dbg_printk(TPACPI_DBG_INIT,
4330                            "uwb hardware not installed\n");
4331         }
4332
4333         if (!tp_features.uwb)
4334                 return 1;
4335
4336         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
4337                                 &uwb_tprfk_ops,
4338                                 RFKILL_TYPE_UWB,
4339                                 TPACPI_RFK_UWB_SW_NAME,
4340                                 false);
4341         return res;
4342 }
4343
4344 static struct ibm_struct uwb_driver_data = {
4345         .name = "uwb",
4346         .exit = uwb_exit,
4347         .flags.experimental = 1,
4348 };
4349
4350 /*************************************************************************
4351  * Video subdriver
4352  */
4353
4354 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
4355
4356 enum video_access_mode {
4357         TPACPI_VIDEO_NONE = 0,
4358         TPACPI_VIDEO_570,       /* 570 */
4359         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
4360         TPACPI_VIDEO_NEW,       /* all others */
4361 };
4362
4363 enum {  /* video status flags, based on VIDEO_570 */
4364         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
4365         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
4366         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
4367 };
4368
4369 enum {  /* TPACPI_VIDEO_570 constants */
4370         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
4371         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
4372                                                  * video_status_flags */
4373         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
4374         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
4375 };
4376
4377 static enum video_access_mode video_supported;
4378 static int video_orig_autosw;
4379
4380 static int video_autosw_get(void);
4381 static int video_autosw_set(int enable);
4382
4383 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
4384
4385 static int __init video_init(struct ibm_init_struct *iibm)
4386 {
4387         int ivga;
4388
4389         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
4390
4391         TPACPI_ACPIHANDLE_INIT(vid);
4392         if (tpacpi_is_ibm())
4393                 TPACPI_ACPIHANDLE_INIT(vid2);
4394
4395         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
4396                 /* G41, assume IVGA doesn't change */
4397                 vid_handle = vid2_handle;
4398
4399         if (!vid_handle)
4400                 /* video switching not supported on R30, R31 */
4401                 video_supported = TPACPI_VIDEO_NONE;
4402         else if (tpacpi_is_ibm() &&
4403                  acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
4404                 /* 570 */
4405                 video_supported = TPACPI_VIDEO_570;
4406         else if (tpacpi_is_ibm() &&
4407                  acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
4408                 /* 600e/x, 770e, 770x */
4409                 video_supported = TPACPI_VIDEO_770;
4410         else
4411                 /* all others */
4412                 video_supported = TPACPI_VIDEO_NEW;
4413
4414         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
4415                 str_supported(video_supported != TPACPI_VIDEO_NONE),
4416                 video_supported);
4417
4418         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
4419 }
4420
4421 static void video_exit(void)
4422 {
4423         dbg_printk(TPACPI_DBG_EXIT,
4424                    "restoring original video autoswitch mode\n");
4425         if (video_autosw_set(video_orig_autosw))
4426                 printk(TPACPI_ERR "error while trying to restore original "
4427                         "video autoswitch mode\n");
4428 }
4429
4430 static int video_outputsw_get(void)
4431 {
4432         int status = 0;
4433         int i;
4434
4435         switch (video_supported) {
4436         case TPACPI_VIDEO_570:
4437                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4438                                  TP_ACPI_VIDEO_570_PHSCMD))
4439                         return -EIO;
4440                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4441                 break;
4442         case TPACPI_VIDEO_770:
4443                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4444                         return -EIO;
4445                 if (i)
4446                         status |= TP_ACPI_VIDEO_S_LCD;
4447                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4448                         return -EIO;
4449                 if (i)
4450                         status |= TP_ACPI_VIDEO_S_CRT;
4451                 break;
4452         case TPACPI_VIDEO_NEW:
4453                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4454                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4455                         return -EIO;
4456                 if (i)
4457                         status |= TP_ACPI_VIDEO_S_CRT;
4458
4459                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4460                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4461                         return -EIO;
4462                 if (i)
4463                         status |= TP_ACPI_VIDEO_S_LCD;
4464                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4465                         return -EIO;
4466                 if (i)
4467                         status |= TP_ACPI_VIDEO_S_DVI;
4468                 break;
4469         default:
4470                 return -ENOSYS;
4471         }
4472
4473         return status;
4474 }
4475
4476 static int video_outputsw_set(int status)
4477 {
4478         int autosw;
4479         int res = 0;
4480
4481         switch (video_supported) {
4482         case TPACPI_VIDEO_570:
4483                 res = acpi_evalf(NULL, NULL,
4484                                  "\\_SB.PHS2", "vdd",
4485                                  TP_ACPI_VIDEO_570_PHS2CMD,
4486                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4487                 break;
4488         case TPACPI_VIDEO_770:
4489                 autosw = video_autosw_get();
4490                 if (autosw < 0)
4491                         return autosw;
4492
4493                 res = video_autosw_set(1);
4494                 if (res)
4495                         return res;
4496                 res = acpi_evalf(vid_handle, NULL,
4497                                  "ASWT", "vdd", status * 0x100, 0);
4498                 if (!autosw && video_autosw_set(autosw)) {
4499                         printk(TPACPI_ERR
4500                                "video auto-switch left enabled due to error\n");
4501                         return -EIO;
4502                 }
4503                 break;
4504         case TPACPI_VIDEO_NEW:
4505                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4506                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4507                 break;
4508         default:
4509                 return -ENOSYS;
4510         }
4511
4512         return (res)? 0 : -EIO;
4513 }
4514
4515 static int video_autosw_get(void)
4516 {
4517         int autosw = 0;
4518
4519         switch (video_supported) {
4520         case TPACPI_VIDEO_570:
4521                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4522                         return -EIO;
4523                 break;
4524         case TPACPI_VIDEO_770:
4525         case TPACPI_VIDEO_NEW:
4526                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4527                         return -EIO;
4528                 break;
4529         default:
4530                 return -ENOSYS;
4531         }
4532
4533         return autosw & 1;
4534 }
4535
4536 static int video_autosw_set(int enable)
4537 {
4538         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
4539                 return -EIO;
4540         return 0;
4541 }
4542
4543 static int video_outputsw_cycle(void)
4544 {
4545         int autosw = video_autosw_get();
4546         int res;
4547
4548         if (autosw < 0)
4549                 return autosw;
4550
4551         switch (video_supported) {
4552         case TPACPI_VIDEO_570:
4553                 res = video_autosw_set(1);
4554                 if (res)
4555                         return res;
4556                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4557                 break;
4558         case TPACPI_VIDEO_770:
4559         case TPACPI_VIDEO_NEW:
4560                 res = video_autosw_set(1);
4561                 if (res)
4562                         return res;
4563                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4564                 break;
4565         default:
4566                 return -ENOSYS;
4567         }
4568         if (!autosw && video_autosw_set(autosw)) {
4569                 printk(TPACPI_ERR
4570                        "video auto-switch left enabled due to error\n");
4571                 return -EIO;
4572         }
4573
4574         return (res)? 0 : -EIO;
4575 }
4576
4577 static int video_expand_toggle(void)
4578 {
4579         switch (video_supported) {
4580         case TPACPI_VIDEO_570:
4581                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
4582                         0 : -EIO;
4583         case TPACPI_VIDEO_770:
4584                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
4585                         0 : -EIO;
4586         case TPACPI_VIDEO_NEW:
4587                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
4588                         0 : -EIO;
4589         default:
4590                 return -ENOSYS;
4591         }
4592         /* not reached */
4593 }
4594
4595 static int video_read(struct seq_file *m)
4596 {
4597         int status, autosw;
4598
4599         if (video_supported == TPACPI_VIDEO_NONE) {
4600                 seq_printf(m, "status:\t\tnot supported\n");
4601                 return 0;
4602         }
4603
4604         /* Even reads can crash X.org, so... */
4605         if (!capable(CAP_SYS_ADMIN))
4606                 return -EPERM;
4607
4608         status = video_outputsw_get();
4609         if (status < 0)
4610                 return status;
4611
4612         autosw = video_autosw_get();
4613         if (autosw < 0)
4614                 return autosw;
4615
4616         seq_printf(m, "status:\t\tsupported\n");
4617         seq_printf(m, "lcd:\t\t%s\n", enabled(status, 0));
4618         seq_printf(m, "crt:\t\t%s\n", enabled(status, 1));
4619         if (video_supported == TPACPI_VIDEO_NEW)
4620                 seq_printf(m, "dvi:\t\t%s\n", enabled(status, 3));
4621         seq_printf(m, "auto:\t\t%s\n", enabled(autosw, 0));
4622         seq_printf(m, "commands:\tlcd_enable, lcd_disable\n");
4623         seq_printf(m, "commands:\tcrt_enable, crt_disable\n");
4624         if (video_supported == TPACPI_VIDEO_NEW)
4625                 seq_printf(m, "commands:\tdvi_enable, dvi_disable\n");
4626         seq_printf(m, "commands:\tauto_enable, auto_disable\n");
4627         seq_printf(m, "commands:\tvideo_switch, expand_toggle\n");
4628
4629         return 0;
4630 }
4631
4632 static int video_write(char *buf)
4633 {
4634         char *cmd;
4635         int enable, disable, status;
4636         int res;
4637
4638         if (video_supported == TPACPI_VIDEO_NONE)
4639                 return -ENODEV;
4640
4641         /* Even reads can crash X.org, let alone writes... */
4642         if (!capable(CAP_SYS_ADMIN))
4643                 return -EPERM;
4644
4645         enable = 0;
4646         disable = 0;
4647
4648         while ((cmd = next_cmd(&buf))) {
4649                 if (strlencmp(cmd, "lcd_enable") == 0) {
4650                         enable |= TP_ACPI_VIDEO_S_LCD;
4651                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
4652                         disable |= TP_ACPI_VIDEO_S_LCD;
4653                 } else if (strlencmp(cmd, "crt_enable") == 0) {
4654                         enable |= TP_ACPI_VIDEO_S_CRT;
4655                 } else if (strlencmp(cmd, "crt_disable") == 0) {
4656                         disable |= TP_ACPI_VIDEO_S_CRT;
4657                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4658                            strlencmp(cmd, "dvi_enable") == 0) {
4659                         enable |= TP_ACPI_VIDEO_S_DVI;
4660                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4661                            strlencmp(cmd, "dvi_disable") == 0) {
4662                         disable |= TP_ACPI_VIDEO_S_DVI;
4663                 } else if (strlencmp(cmd, "auto_enable") == 0) {
4664                         res = video_autosw_set(1);
4665                         if (res)
4666                                 return res;
4667                 } else if (strlencmp(cmd, "auto_disable") == 0) {
4668                         res = video_autosw_set(0);
4669                         if (res)
4670                                 return res;
4671                 } else if (strlencmp(cmd, "video_switch") == 0) {
4672                         res = video_outputsw_cycle();
4673                         if (res)
4674                                 return res;
4675                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
4676                         res = video_expand_toggle();
4677                         if (res)
4678                                 return res;
4679                 } else
4680                         return -EINVAL;
4681         }
4682
4683         if (enable || disable) {
4684                 status = video_outputsw_get();
4685                 if (status < 0)
4686                         return status;
4687                 res = video_outputsw_set((status & ~disable) | enable);
4688                 if (res)
4689                         return res;
4690         }
4691
4692         return 0;
4693 }
4694
4695 static struct ibm_struct video_driver_data = {
4696         .name = "video",
4697         .read = video_read,
4698         .write = video_write,
4699         .exit = video_exit,
4700 };
4701
4702 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
4703
4704 /*************************************************************************
4705  * Light (thinklight) subdriver
4706  */
4707
4708 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
4709 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
4710
4711 static int light_get_status(void)
4712 {
4713         int status = 0;
4714
4715         if (tp_features.light_status) {
4716                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
4717                         return -EIO;
4718                 return (!!status);
4719         }
4720
4721         return -ENXIO;
4722 }
4723
4724 static int light_set_status(int status)
4725 {
4726         int rc;
4727
4728         if (tp_features.light) {
4729                 if (cmos_handle) {
4730                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
4731                                         (status)?
4732                                                 TP_CMOS_THINKLIGHT_ON :
4733                                                 TP_CMOS_THINKLIGHT_OFF);
4734                 } else {
4735                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
4736                                         (status)? 1 : 0);
4737                 }
4738                 return (rc)? 0 : -EIO;
4739         }
4740
4741         return -ENXIO;
4742 }
4743
4744 static void light_set_status_worker(struct work_struct *work)
4745 {
4746         struct tpacpi_led_classdev *data =
4747                         container_of(work, struct tpacpi_led_classdev, work);
4748
4749         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4750                 light_set_status((data->new_state != TPACPI_LED_OFF));
4751 }
4752
4753 static void light_sysfs_set(struct led_classdev *led_cdev,
4754                         enum led_brightness brightness)
4755 {
4756         struct tpacpi_led_classdev *data =
4757                 container_of(led_cdev,
4758                              struct tpacpi_led_classdev,
4759                              led_classdev);
4760         data->new_state = (brightness != LED_OFF) ?
4761                                 TPACPI_LED_ON : TPACPI_LED_OFF;
4762         queue_work(tpacpi_wq, &data->work);
4763 }
4764
4765 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
4766 {
4767         return (light_get_status() == 1)? LED_FULL : LED_OFF;
4768 }
4769
4770 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
4771         .led_classdev = {
4772                 .name           = "tpacpi::thinklight",
4773                 .brightness_set = &light_sysfs_set,
4774                 .brightness_get = &light_sysfs_get,
4775         }
4776 };
4777
4778 static int __init light_init(struct ibm_init_struct *iibm)
4779 {
4780         int rc;
4781
4782         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
4783
4784         if (tpacpi_is_ibm()) {
4785                 TPACPI_ACPIHANDLE_INIT(ledb);
4786                 TPACPI_ACPIHANDLE_INIT(lght);
4787         }
4788         TPACPI_ACPIHANDLE_INIT(cmos);
4789         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
4790
4791         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
4792         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
4793
4794         if (tp_features.light)
4795                 /* light status not supported on
4796                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
4797                 tp_features.light_status =
4798                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
4799
4800         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4801                 str_supported(tp_features.light),
4802                 str_supported(tp_features.light_status));
4803
4804         if (!tp_features.light)
4805                 return 1;
4806
4807         rc = led_classdev_register(&tpacpi_pdev->dev,
4808                                    &tpacpi_led_thinklight.led_classdev);
4809
4810         if (rc < 0) {
4811                 tp_features.light = 0;
4812                 tp_features.light_status = 0;
4813         } else  {
4814                 rc = 0;
4815         }
4816
4817         return rc;
4818 }
4819
4820 static void light_exit(void)
4821 {
4822         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4823         if (work_pending(&tpacpi_led_thinklight.work))
4824                 flush_workqueue(tpacpi_wq);
4825 }
4826
4827 static int light_read(struct seq_file *m)
4828 {
4829         int status;
4830
4831         if (!tp_features.light) {
4832                 seq_printf(m, "status:\t\tnot supported\n");
4833         } else if (!tp_features.light_status) {
4834                 seq_printf(m, "status:\t\tunknown\n");
4835                 seq_printf(m, "commands:\ton, off\n");
4836         } else {
4837                 status = light_get_status();
4838                 if (status < 0)
4839                         return status;
4840                 seq_printf(m, "status:\t\t%s\n", onoff(status, 0));
4841                 seq_printf(m, "commands:\ton, off\n");
4842         }
4843
4844         return 0;
4845 }
4846
4847 static int light_write(char *buf)
4848 {
4849         char *cmd;
4850         int newstatus = 0;
4851
4852         if (!tp_features.light)
4853                 return -ENODEV;
4854
4855         while ((cmd = next_cmd(&buf))) {
4856                 if (strlencmp(cmd, "on") == 0) {
4857                         newstatus = 1;
4858                 } else if (strlencmp(cmd, "off") == 0) {
4859                         newstatus = 0;
4860                 } else
4861                         return -EINVAL;
4862         }
4863
4864         return light_set_status(newstatus);
4865 }
4866
4867 static struct ibm_struct light_driver_data = {
4868         .name = "light",
4869         .read = light_read,
4870         .write = light_write,
4871         .exit = light_exit,
4872 };
4873
4874 /*************************************************************************
4875  * CMOS subdriver
4876  */
4877
4878 /* sysfs cmos_command -------------------------------------------------- */
4879 static ssize_t cmos_command_store(struct device *dev,
4880                             struct device_attribute *attr,
4881                             const char *buf, size_t count)
4882 {
4883         unsigned long cmos_cmd;
4884         int res;
4885
4886         if (parse_strtoul(buf, 21, &cmos_cmd))
4887                 return -EINVAL;
4888
4889         res = issue_thinkpad_cmos_command(cmos_cmd);
4890         return (res)? res : count;
4891 }
4892
4893 static struct device_attribute dev_attr_cmos_command =
4894         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4895
4896 /* --------------------------------------------------------------------- */
4897
4898 static int __init cmos_init(struct ibm_init_struct *iibm)
4899 {
4900         int res;
4901
4902         vdbg_printk(TPACPI_DBG_INIT,
4903                 "initializing cmos commands subdriver\n");
4904
4905         TPACPI_ACPIHANDLE_INIT(cmos);
4906
4907         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4908                 str_supported(cmos_handle != NULL));
4909
4910         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4911         if (res)
4912                 return res;
4913
4914         return (cmos_handle)? 0 : 1;
4915 }
4916
4917 static void cmos_exit(void)
4918 {
4919         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4920 }
4921
4922 static int cmos_read(struct seq_file *m)
4923 {
4924         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4925            R30, R31, T20-22, X20-21 */
4926         if (!cmos_handle)
4927                 seq_printf(m, "status:\t\tnot supported\n");
4928         else {
4929                 seq_printf(m, "status:\t\tsupported\n");
4930                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-21)\n");
4931         }
4932
4933         return 0;
4934 }
4935
4936 static int cmos_write(char *buf)
4937 {
4938         char *cmd;
4939         int cmos_cmd, res;
4940
4941         while ((cmd = next_cmd(&buf))) {
4942                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4943                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4944                         /* cmos_cmd set */
4945                 } else
4946                         return -EINVAL;
4947
4948                 res = issue_thinkpad_cmos_command(cmos_cmd);
4949                 if (res)
4950                         return res;
4951         }
4952
4953         return 0;
4954 }
4955
4956 static struct ibm_struct cmos_driver_data = {
4957         .name = "cmos",
4958         .read = cmos_read,
4959         .write = cmos_write,
4960         .exit = cmos_exit,
4961 };
4962
4963 /*************************************************************************
4964  * LED subdriver
4965  */
4966
4967 enum led_access_mode {
4968         TPACPI_LED_NONE = 0,
4969         TPACPI_LED_570, /* 570 */
4970         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4971         TPACPI_LED_NEW, /* all others */
4972 };
4973
4974 enum {  /* For TPACPI_LED_OLD */
4975         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4976         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4977         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4978 };
4979
4980 static enum led_access_mode led_supported;
4981
4982 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4983            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4984                                 /* T20-22, X20-21 */
4985            "LED",               /* all others */
4986            );                   /* R30, R31 */
4987
4988 #define TPACPI_LED_NUMLEDS 16
4989 static struct tpacpi_led_classdev *tpacpi_leds;
4990 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4991 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4992         /* there's a limit of 19 chars + NULL before 2.6.26 */
4993         "tpacpi::power",
4994         "tpacpi:orange:batt",
4995         "tpacpi:green:batt",
4996         "tpacpi::dock_active",
4997         "tpacpi::bay_active",
4998         "tpacpi::dock_batt",
4999         "tpacpi::unknown_led",
5000         "tpacpi::standby",
5001         "tpacpi::dock_status1",
5002         "tpacpi::dock_status2",
5003         "tpacpi::unknown_led2",
5004         "tpacpi::unknown_led3",
5005         "tpacpi::thinkvantage",
5006 };
5007 #define TPACPI_SAFE_LEDS        0x1081U
5008
5009 static inline bool tpacpi_is_led_restricted(const unsigned int led)
5010 {
5011 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5012         return false;
5013 #else
5014         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
5015 #endif
5016 }
5017
5018 static int led_get_status(const unsigned int led)
5019 {
5020         int status;
5021         enum led_status_t led_s;
5022
5023         switch (led_supported) {
5024         case TPACPI_LED_570:
5025                 if (!acpi_evalf(ec_handle,
5026                                 &status, "GLED", "dd", 1 << led))
5027                         return -EIO;
5028                 led_s = (status == 0)?
5029                                 TPACPI_LED_OFF :
5030                                 ((status == 1)?
5031                                         TPACPI_LED_ON :
5032                                         TPACPI_LED_BLINK);
5033                 tpacpi_led_state_cache[led] = led_s;
5034                 return led_s;
5035         default:
5036                 return -ENXIO;
5037         }
5038
5039         /* not reached */
5040 }
5041
5042 static int led_set_status(const unsigned int led,
5043                           const enum led_status_t ledstatus)
5044 {
5045         /* off, on, blink. Index is led_status_t */
5046         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
5047         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
5048
5049         int rc = 0;
5050
5051         switch (led_supported) {
5052         case TPACPI_LED_570:
5053                 /* 570 */
5054                 if (unlikely(led > 7))
5055                         return -EINVAL;
5056                 if (unlikely(tpacpi_is_led_restricted(led)))
5057                         return -EPERM;
5058                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5059                                 (1 << led), led_sled_arg1[ledstatus]))
5060                         rc = -EIO;
5061                 break;
5062         case TPACPI_LED_OLD:
5063                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
5064                 if (unlikely(led > 7))
5065                         return -EINVAL;
5066                 if (unlikely(tpacpi_is_led_restricted(led)))
5067                         return -EPERM;
5068                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
5069                 if (rc >= 0)
5070                         rc = ec_write(TPACPI_LED_EC_HLBL,
5071                                       (ledstatus == TPACPI_LED_BLINK) << led);
5072                 if (rc >= 0)
5073                         rc = ec_write(TPACPI_LED_EC_HLCL,
5074                                       (ledstatus != TPACPI_LED_OFF) << led);
5075                 break;
5076         case TPACPI_LED_NEW:
5077                 /* all others */
5078                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
5079                         return -EINVAL;
5080                 if (unlikely(tpacpi_is_led_restricted(led)))
5081                         return -EPERM;
5082                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5083                                 led, led_led_arg1[ledstatus]))
5084                         rc = -EIO;
5085                 break;
5086         default:
5087                 rc = -ENXIO;
5088         }
5089
5090         if (!rc)
5091                 tpacpi_led_state_cache[led] = ledstatus;
5092
5093         return rc;
5094 }
5095
5096 static void led_set_status_worker(struct work_struct *work)
5097 {
5098         struct tpacpi_led_classdev *data =
5099                 container_of(work, struct tpacpi_led_classdev, work);
5100
5101         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
5102                 led_set_status(data->led, data->new_state);
5103 }
5104
5105 static void led_sysfs_set(struct led_classdev *led_cdev,
5106                         enum led_brightness brightness)
5107 {
5108         struct tpacpi_led_classdev *data = container_of(led_cdev,
5109                              struct tpacpi_led_classdev, led_classdev);
5110
5111         if (brightness == LED_OFF)
5112                 data->new_state = TPACPI_LED_OFF;
5113         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
5114                 data->new_state = TPACPI_LED_ON;
5115         else
5116                 data->new_state = TPACPI_LED_BLINK;
5117
5118         queue_work(tpacpi_wq, &data->work);
5119 }
5120
5121 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
5122                         unsigned long *delay_on, unsigned long *delay_off)
5123 {
5124         struct tpacpi_led_classdev *data = container_of(led_cdev,
5125                              struct tpacpi_led_classdev, led_classdev);
5126
5127         /* Can we choose the flash rate? */
5128         if (*delay_on == 0 && *delay_off == 0) {
5129                 /* yes. set them to the hardware blink rate (1 Hz) */
5130                 *delay_on = 500; /* ms */
5131                 *delay_off = 500; /* ms */
5132         } else if ((*delay_on != 500) || (*delay_off != 500))
5133                 return -EINVAL;
5134
5135         data->new_state = TPACPI_LED_BLINK;
5136         queue_work(tpacpi_wq, &data->work);
5137
5138         return 0;
5139 }
5140
5141 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5142 {
5143         int rc;
5144
5145         struct tpacpi_led_classdev *data = container_of(led_cdev,
5146                              struct tpacpi_led_classdev, led_classdev);
5147
5148         rc = led_get_status(data->led);
5149
5150         if (rc == TPACPI_LED_OFF || rc < 0)
5151                 rc = LED_OFF;   /* no error handling in led class :( */
5152         else
5153                 rc = LED_FULL;
5154
5155         return rc;
5156 }
5157
5158 static void led_exit(void)
5159 {
5160         unsigned int i;
5161
5162         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5163                 if (tpacpi_leds[i].led_classdev.name)
5164                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5165         }
5166
5167         kfree(tpacpi_leds);
5168 }
5169
5170 static int __init tpacpi_init_led(unsigned int led)
5171 {
5172         int rc;
5173
5174         tpacpi_leds[led].led = led;
5175
5176         /* LEDs with no name don't get registered */
5177         if (!tpacpi_led_names[led])
5178                 return 0;
5179
5180         tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set;
5181         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5182         if (led_supported == TPACPI_LED_570)
5183                 tpacpi_leds[led].led_classdev.brightness_get =
5184                                                 &led_sysfs_get;
5185
5186         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5187
5188         INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker);
5189
5190         rc = led_classdev_register(&tpacpi_pdev->dev,
5191                                 &tpacpi_leds[led].led_classdev);
5192         if (rc < 0)
5193                 tpacpi_leds[led].led_classdev.name = NULL;
5194
5195         return rc;
5196 }
5197
5198 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5199         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5200         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5201         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5202
5203         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5204         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5205         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5206         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5207         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5208         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5209         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5210         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5211
5212         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5213         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5214         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5215         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5216         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5217
5218         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5219         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5220         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5221         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5222
5223         /* (1) - may have excess leds enabled on MSB */
5224
5225         /* Defaults (order matters, keep last, don't reorder!) */
5226         { /* Lenovo */
5227           .vendor = PCI_VENDOR_ID_LENOVO,
5228           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5229           .quirks = 0x1fffU,
5230         },
5231         { /* IBM ThinkPads with no EC version string */
5232           .vendor = PCI_VENDOR_ID_IBM,
5233           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5234           .quirks = 0x00ffU,
5235         },
5236         { /* IBM ThinkPads with EC version string */
5237           .vendor = PCI_VENDOR_ID_IBM,
5238           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5239           .quirks = 0x00bfU,
5240         },
5241 };
5242
5243 #undef TPACPI_LEDQ_IBM
5244 #undef TPACPI_LEDQ_LNV
5245
5246 static int __init led_init(struct ibm_init_struct *iibm)
5247 {
5248         unsigned int i;
5249         int rc;
5250         unsigned long useful_leds;
5251
5252         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5253
5254         TPACPI_ACPIHANDLE_INIT(led);
5255
5256         if (!led_handle)
5257                 /* led not supported on R30, R31 */
5258                 led_supported = TPACPI_LED_NONE;
5259         else if (tpacpi_is_ibm() && strlencmp(led_path, "SLED") == 0)
5260                 /* 570 */
5261                 led_supported = TPACPI_LED_570;
5262         else if (tpacpi_is_ibm() && strlencmp(led_path, "SYSL") == 0)
5263                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5264                 led_supported = TPACPI_LED_OLD;
5265         else
5266                 /* all others */
5267                 led_supported = TPACPI_LED_NEW;
5268
5269         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5270                 str_supported(led_supported), led_supported);
5271
5272         if (led_supported == TPACPI_LED_NONE)
5273                 return 1;
5274
5275         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5276                               GFP_KERNEL);
5277         if (!tpacpi_leds) {
5278                 printk(TPACPI_ERR "Out of memory for LED data\n");
5279                 return -ENOMEM;
5280         }
5281
5282         useful_leds = tpacpi_check_quirks(led_useful_qtable,
5283                                           ARRAY_SIZE(led_useful_qtable));
5284
5285         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5286                 if (!tpacpi_is_led_restricted(i) &&
5287                     test_bit(i, &useful_leds)) {
5288                         rc = tpacpi_init_led(i);
5289                         if (rc < 0) {
5290                                 led_exit();
5291                                 return rc;
5292                         }
5293                 }
5294         }
5295
5296 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5297         printk(TPACPI_NOTICE
5298                 "warning: userspace override of important "
5299                 "firmware LEDs is enabled\n");
5300 #endif
5301         return 0;
5302 }
5303
5304 #define str_led_status(s) \
5305         ((s) == TPACPI_LED_OFF ? "off" : \
5306                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5307
5308 static int led_read(struct seq_file *m)
5309 {
5310         if (!led_supported) {
5311                 seq_printf(m, "status:\t\tnot supported\n");
5312                 return 0;
5313         }
5314         seq_printf(m, "status:\t\tsupported\n");
5315
5316         if (led_supported == TPACPI_LED_570) {
5317                 /* 570 */
5318                 int i, status;
5319                 for (i = 0; i < 8; i++) {
5320                         status = led_get_status(i);
5321                         if (status < 0)
5322                                 return -EIO;
5323                         seq_printf(m, "%d:\t\t%s\n",
5324                                        i, str_led_status(status));
5325                 }
5326         }
5327
5328         seq_printf(m, "commands:\t"
5329                        "<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5330
5331         return 0;
5332 }
5333
5334 static int led_write(char *buf)
5335 {
5336         char *cmd;
5337         int led, rc;
5338         enum led_status_t s;
5339
5340         if (!led_supported)
5341                 return -ENODEV;
5342
5343         while ((cmd = next_cmd(&buf))) {
5344                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15)
5345                         return -EINVAL;
5346
5347                 if (strstr(cmd, "off")) {
5348                         s = TPACPI_LED_OFF;
5349                 } else if (strstr(cmd, "on")) {
5350                         s = TPACPI_LED_ON;
5351                 } else if (strstr(cmd, "blink")) {
5352                         s = TPACPI_LED_BLINK;
5353                 } else {
5354                         return -EINVAL;
5355                 }
5356
5357                 rc = led_set_status(led, s);
5358                 if (rc < 0)
5359                         return rc;
5360         }
5361
5362         return 0;
5363 }
5364
5365 static struct ibm_struct led_driver_data = {
5366         .name = "led",
5367         .read = led_read,
5368         .write = led_write,
5369         .exit = led_exit,
5370 };
5371
5372 /*************************************************************************
5373  * Beep subdriver
5374  */
5375
5376 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
5377
5378 #define TPACPI_BEEP_Q1 0x0001
5379
5380 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
5381         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
5382         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
5383 };
5384
5385 static int __init beep_init(struct ibm_init_struct *iibm)
5386 {
5387         unsigned long quirks;
5388
5389         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
5390
5391         TPACPI_ACPIHANDLE_INIT(beep);
5392
5393         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
5394                 str_supported(beep_handle != NULL));
5395
5396         quirks = tpacpi_check_quirks(beep_quirk_table,
5397                                      ARRAY_SIZE(beep_quirk_table));
5398
5399         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
5400
5401         return (beep_handle)? 0 : 1;
5402 }
5403
5404 static int beep_read(struct seq_file *m)
5405 {
5406         if (!beep_handle)
5407                 seq_printf(m, "status:\t\tnot supported\n");
5408         else {
5409                 seq_printf(m, "status:\t\tsupported\n");
5410                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-17)\n");
5411         }
5412
5413         return 0;
5414 }
5415
5416 static int beep_write(char *buf)
5417 {
5418         char *cmd;
5419         int beep_cmd;
5420
5421         if (!beep_handle)
5422                 return -ENODEV;
5423
5424         while ((cmd = next_cmd(&buf))) {
5425                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
5426                     beep_cmd >= 0 && beep_cmd <= 17) {
5427                         /* beep_cmd set */
5428                 } else
5429                         return -EINVAL;
5430                 if (tp_features.beep_needs_two_args) {
5431                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
5432                                         beep_cmd, 0))
5433                                 return -EIO;
5434                 } else {
5435                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
5436                                         beep_cmd))
5437                                 return -EIO;
5438                 }
5439         }
5440
5441         return 0;
5442 }
5443
5444 static struct ibm_struct beep_driver_data = {
5445         .name = "beep",
5446         .read = beep_read,
5447         .write = beep_write,
5448 };
5449
5450 /*************************************************************************
5451  * Thermal subdriver
5452  */
5453
5454 enum thermal_access_mode {
5455         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
5456         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
5457         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
5458         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
5459         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
5460 };
5461
5462 enum { /* TPACPI_THERMAL_TPEC_* */
5463         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
5464         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
5465         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
5466
5467         TPACPI_THERMAL_SENSOR_NA = -128000, /* Sensor not available */
5468 };
5469
5470
5471 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
5472 struct ibm_thermal_sensors_struct {
5473         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
5474 };
5475
5476 static enum thermal_access_mode thermal_read_mode;
5477
5478 /* idx is zero-based */
5479 static int thermal_get_sensor(int idx, s32 *value)
5480 {
5481         int t;
5482         s8 tmp;
5483         char tmpi[5];
5484
5485         t = TP_EC_THERMAL_TMP0;
5486
5487         switch (thermal_read_mode) {
5488 #if TPACPI_MAX_THERMAL_SENSORS >= 16
5489         case TPACPI_THERMAL_TPEC_16:
5490                 if (idx >= 8 && idx <= 15) {
5491                         t = TP_EC_THERMAL_TMP8;
5492                         idx -= 8;
5493                 }
5494                 /* fallthrough */
5495 #endif
5496         case TPACPI_THERMAL_TPEC_8:
5497                 if (idx <= 7) {
5498                         if (!acpi_ec_read(t + idx, &tmp))
5499                                 return -EIO;
5500                         *value = tmp * 1000;
5501                         return 0;
5502                 }
5503                 break;
5504
5505         case TPACPI_THERMAL_ACPI_UPDT:
5506                 if (idx <= 7) {
5507                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5508                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
5509                                 return -EIO;
5510                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5511                                 return -EIO;
5512                         *value = (t - 2732) * 100;
5513                         return 0;
5514                 }
5515                 break;
5516
5517         case TPACPI_THERMAL_ACPI_TMP07:
5518                 if (idx <= 7) {
5519                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5520                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5521                                 return -EIO;
5522                         if (t > 127 || t < -127)
5523                                 t = TP_EC_THERMAL_TMP_NA;
5524                         *value = t * 1000;
5525                         return 0;
5526                 }
5527                 break;
5528
5529         case TPACPI_THERMAL_NONE:
5530         default:
5531                 return -ENOSYS;
5532         }
5533
5534         return -EINVAL;
5535 }
5536
5537 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
5538 {
5539         int res, i;
5540         int n;
5541
5542         n = 8;
5543         i = 0;
5544
5545         if (!s)
5546                 return -EINVAL;
5547
5548         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
5549                 n = 16;
5550
5551         for (i = 0 ; i < n; i++) {
5552                 res = thermal_get_sensor(i, &s->temp[i]);
5553                 if (res)
5554                         return res;
5555         }
5556
5557         return n;
5558 }
5559
5560 static void thermal_dump_all_sensors(void)
5561 {
5562         int n, i;
5563         struct ibm_thermal_sensors_struct t;
5564
5565         n = thermal_get_sensors(&t);
5566         if (n <= 0)
5567                 return;
5568
5569         printk(TPACPI_NOTICE
5570                 "temperatures (Celsius):");
5571
5572         for (i = 0; i < n; i++) {
5573                 if (t.temp[i] != TPACPI_THERMAL_SENSOR_NA)
5574                         printk(KERN_CONT " %d", (int)(t.temp[i] / 1000));
5575                 else
5576                         printk(KERN_CONT " N/A");
5577         }
5578
5579         printk(KERN_CONT "\n");
5580 }
5581
5582 /* sysfs temp##_input -------------------------------------------------- */
5583
5584 static ssize_t thermal_temp_input_show(struct device *dev,
5585                            struct device_attribute *attr,
5586                            char *buf)
5587 {
5588         struct sensor_device_attribute *sensor_attr =
5589                                         to_sensor_dev_attr(attr);
5590         int idx = sensor_attr->index;
5591         s32 value;
5592         int res;
5593
5594         res = thermal_get_sensor(idx, &value);
5595         if (res)
5596                 return res;
5597         if (value == TPACPI_THERMAL_SENSOR_NA)
5598                 return -ENXIO;
5599
5600         return snprintf(buf, PAGE_SIZE, "%d\n", value);
5601 }
5602
5603 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
5604          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
5605                      thermal_temp_input_show, NULL, _idxB)
5606
5607 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
5608         THERMAL_SENSOR_ATTR_TEMP(1, 0),
5609         THERMAL_SENSOR_ATTR_TEMP(2, 1),
5610         THERMAL_SENSOR_ATTR_TEMP(3, 2),
5611         THERMAL_SENSOR_ATTR_TEMP(4, 3),
5612         THERMAL_SENSOR_ATTR_TEMP(5, 4),
5613         THERMAL_SENSOR_ATTR_TEMP(6, 5),
5614         THERMAL_SENSOR_ATTR_TEMP(7, 6),
5615         THERMAL_SENSOR_ATTR_TEMP(8, 7),
5616         THERMAL_SENSOR_ATTR_TEMP(9, 8),
5617         THERMAL_SENSOR_ATTR_TEMP(10, 9),
5618         THERMAL_SENSOR_ATTR_TEMP(11, 10),
5619         THERMAL_SENSOR_ATTR_TEMP(12, 11),
5620         THERMAL_SENSOR_ATTR_TEMP(13, 12),
5621         THERMAL_SENSOR_ATTR_TEMP(14, 13),
5622         THERMAL_SENSOR_ATTR_TEMP(15, 14),
5623         THERMAL_SENSOR_ATTR_TEMP(16, 15),
5624 };
5625
5626 #define THERMAL_ATTRS(X) \
5627         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
5628
5629 static struct attribute *thermal_temp_input_attr[] = {
5630         THERMAL_ATTRS(8),
5631         THERMAL_ATTRS(9),
5632         THERMAL_ATTRS(10),
5633         THERMAL_ATTRS(11),
5634         THERMAL_ATTRS(12),
5635         THERMAL_ATTRS(13),
5636         THERMAL_ATTRS(14),
5637         THERMAL_ATTRS(15),
5638         THERMAL_ATTRS(0),
5639         THERMAL_ATTRS(1),
5640         THERMAL_ATTRS(2),
5641         THERMAL_ATTRS(3),
5642         THERMAL_ATTRS(4),
5643         THERMAL_ATTRS(5),
5644         THERMAL_ATTRS(6),
5645         THERMAL_ATTRS(7),
5646         NULL
5647 };
5648
5649 static const struct attribute_group thermal_temp_input16_group = {
5650         .attrs = thermal_temp_input_attr
5651 };
5652
5653 static const struct attribute_group thermal_temp_input8_group = {
5654         .attrs = &thermal_temp_input_attr[8]
5655 };
5656
5657 #undef THERMAL_SENSOR_ATTR_TEMP
5658 #undef THERMAL_ATTRS
5659
5660 /* --------------------------------------------------------------------- */
5661
5662 static int __init thermal_init(struct ibm_init_struct *iibm)
5663 {
5664         u8 t, ta1, ta2;
5665         int i;
5666         int acpi_tmp7;
5667         int res;
5668
5669         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5670
5671         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5672
5673         if (thinkpad_id.ec_model) {
5674                 /*
5675                  * Direct EC access mode: sensors at registers
5676                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5677                  * non-implemented, thermal sensors return 0x80 when
5678                  * not available
5679                  */
5680
5681                 ta1 = ta2 = 0;
5682                 for (i = 0; i < 8; i++) {
5683                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5684                                 ta1 |= t;
5685                         } else {
5686                                 ta1 = 0;
5687                                 break;
5688                         }
5689                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5690                                 ta2 |= t;
5691                         } else {
5692                                 ta1 = 0;
5693                                 break;
5694                         }
5695                 }
5696                 if (ta1 == 0) {
5697                         /* This is sheer paranoia, but we handle it anyway */
5698                         if (acpi_tmp7) {
5699                                 printk(TPACPI_ERR
5700                                        "ThinkPad ACPI EC access misbehaving, "
5701                                        "falling back to ACPI TMPx access "
5702                                        "mode\n");
5703                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5704                         } else {
5705                                 printk(TPACPI_ERR
5706                                        "ThinkPad ACPI EC access misbehaving, "
5707                                        "disabling thermal sensors access\n");
5708                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5709                         }
5710                 } else {
5711                         thermal_read_mode =
5712                             (ta2 != 0) ?
5713                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5714                 }
5715         } else if (acpi_tmp7) {
5716                 if (tpacpi_is_ibm() &&
5717                     acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5718                         /* 600e/x, 770e, 770x */
5719                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5720                 } else {
5721                         /* IBM/LENOVO DSDT EC.TMPx access, max 8 sensors */
5722                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5723                 }
5724         } else {
5725                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5726                 thermal_read_mode = TPACPI_THERMAL_NONE;
5727         }
5728
5729         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5730                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5731                 thermal_read_mode);
5732
5733         switch (thermal_read_mode) {
5734         case TPACPI_THERMAL_TPEC_16:
5735                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5736                                 &thermal_temp_input16_group);
5737                 if (res)
5738                         return res;
5739                 break;
5740         case TPACPI_THERMAL_TPEC_8:
5741         case TPACPI_THERMAL_ACPI_TMP07:
5742         case TPACPI_THERMAL_ACPI_UPDT:
5743                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5744                                 &thermal_temp_input8_group);
5745                 if (res)
5746                         return res;
5747                 break;
5748         case TPACPI_THERMAL_NONE:
5749         default:
5750                 return 1;
5751         }
5752
5753         return 0;
5754 }
5755
5756 static void thermal_exit(void)
5757 {
5758         switch (thermal_read_mode) {
5759         case TPACPI_THERMAL_TPEC_16:
5760                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5761                                    &thermal_temp_input16_group);
5762                 break;
5763         case TPACPI_THERMAL_TPEC_8:
5764         case TPACPI_THERMAL_ACPI_TMP07:
5765         case TPACPI_THERMAL_ACPI_UPDT:
5766                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5767                                    &thermal_temp_input8_group);
5768                 break;
5769         case TPACPI_THERMAL_NONE:
5770         default:
5771                 break;
5772         }
5773 }
5774
5775 static int thermal_read(struct seq_file *m)
5776 {
5777         int n, i;
5778         struct ibm_thermal_sensors_struct t;
5779
5780         n = thermal_get_sensors(&t);
5781         if (unlikely(n < 0))
5782                 return n;
5783
5784         seq_printf(m, "temperatures:\t");
5785
5786         if (n > 0) {
5787                 for (i = 0; i < (n - 1); i++)
5788                         seq_printf(m, "%d ", t.temp[i] / 1000);
5789                 seq_printf(m, "%d\n", t.temp[i] / 1000);
5790         } else
5791                 seq_printf(m, "not supported\n");
5792
5793         return 0;
5794 }
5795
5796 static struct ibm_struct thermal_driver_data = {
5797         .name = "thermal",
5798         .read = thermal_read,
5799         .exit = thermal_exit,
5800 };
5801
5802 /*************************************************************************
5803  * EC Dump subdriver
5804  */
5805
5806 static u8 ecdump_regs[256];
5807
5808 static int ecdump_read(struct seq_file *m)
5809 {
5810         int i, j;
5811         u8 v;
5812
5813         seq_printf(m, "EC      "
5814                        " +00 +01 +02 +03 +04 +05 +06 +07"
5815                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5816         for (i = 0; i < 256; i += 16) {
5817                 seq_printf(m, "EC 0x%02x:", i);
5818                 for (j = 0; j < 16; j++) {
5819                         if (!acpi_ec_read(i + j, &v))
5820                                 break;
5821                         if (v != ecdump_regs[i + j])
5822                                 seq_printf(m, " *%02x", v);
5823                         else
5824                                 seq_printf(m, "  %02x", v);
5825                         ecdump_regs[i + j] = v;
5826                 }
5827                 seq_putc(m, '\n');
5828                 if (j != 16)
5829                         break;
5830         }
5831
5832         /* These are way too dangerous to advertise openly... */
5833 #if 0
5834         seq_printf(m, "commands:\t0x<offset> 0x<value>"
5835                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5836         seq_printf(m, "commands:\t0x<offset> <value>  "
5837                        " (<offset> is 00-ff, <value> is 0-255)\n");
5838 #endif
5839         return 0;
5840 }
5841
5842 static int ecdump_write(char *buf)
5843 {
5844         char *cmd;
5845         int i, v;
5846
5847         while ((cmd = next_cmd(&buf))) {
5848                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5849                         /* i and v set */
5850                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5851                         /* i and v set */
5852                 } else
5853                         return -EINVAL;
5854                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5855                         if (!acpi_ec_write(i, v))
5856                                 return -EIO;
5857                 } else
5858                         return -EINVAL;
5859         }
5860
5861         return 0;
5862 }
5863
5864 static struct ibm_struct ecdump_driver_data = {
5865         .name = "ecdump",
5866         .read = ecdump_read,
5867         .write = ecdump_write,
5868         .flags.experimental = 1,
5869 };
5870
5871 /*************************************************************************
5872  * Backlight/brightness subdriver
5873  */
5874
5875 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5876
5877 /*
5878  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
5879  * CMOS NVRAM byte 0x5E, bits 0-3.
5880  *
5881  * EC HBRV (0x31) has the following layout
5882  *   Bit 7: unknown function
5883  *   Bit 6: unknown function
5884  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5885  *   Bit 4: must be set to zero to avoid problems
5886  *   Bit 3-0: backlight brightness level
5887  *
5888  * brightness_get_raw returns status data in the HBRV layout
5889  *
5890  * WARNING: The X61 has been verified to use HBRV for something else, so
5891  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
5892  * testing on the very early *60 Lenovo models...
5893  */
5894
5895 enum {
5896         TP_EC_BACKLIGHT = 0x31,
5897
5898         /* TP_EC_BACKLIGHT bitmasks */
5899         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5900         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5901         TP_EC_BACKLIGHT_MAPSW = 0x20,
5902 };
5903
5904 enum tpacpi_brightness_access_mode {
5905         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
5906         TPACPI_BRGHT_MODE_EC,           /* EC control */
5907         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
5908         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
5909         TPACPI_BRGHT_MODE_MAX
5910 };
5911
5912 static struct backlight_device *ibm_backlight_device;
5913
5914 static enum tpacpi_brightness_access_mode brightness_mode =
5915                 TPACPI_BRGHT_MODE_MAX;
5916
5917 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5918
5919 static struct mutex brightness_mutex;
5920
5921 /* NVRAM brightness access,
5922  * call with brightness_mutex held! */
5923 static unsigned int tpacpi_brightness_nvram_get(void)
5924 {
5925         u8 lnvram;
5926
5927         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5928                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5929                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5930         lnvram &= bright_maxlvl;
5931
5932         return lnvram;
5933 }
5934
5935 static void tpacpi_brightness_checkpoint_nvram(void)
5936 {
5937         u8 lec = 0;
5938         u8 b_nvram;
5939
5940         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
5941                 return;
5942
5943         vdbg_printk(TPACPI_DBG_BRGHT,
5944                 "trying to checkpoint backlight level to NVRAM...\n");
5945
5946         if (mutex_lock_killable(&brightness_mutex) < 0)
5947                 return;
5948
5949         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5950                 goto unlock;
5951         lec &= TP_EC_BACKLIGHT_LVLMSK;
5952         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
5953
5954         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5955                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
5956                 /* NVRAM needs update */
5957                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
5958                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
5959                 b_nvram |= lec;
5960                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
5961                 dbg_printk(TPACPI_DBG_BRGHT,
5962                            "updated NVRAM backlight level to %u (0x%02x)\n",
5963                            (unsigned int) lec, (unsigned int) b_nvram);
5964         } else
5965                 vdbg_printk(TPACPI_DBG_BRGHT,
5966                            "NVRAM backlight level already is %u (0x%02x)\n",
5967                            (unsigned int) lec, (unsigned int) b_nvram);
5968
5969 unlock:
5970         mutex_unlock(&brightness_mutex);
5971 }
5972
5973
5974 /* call with brightness_mutex held! */
5975 static int tpacpi_brightness_get_raw(int *status)
5976 {
5977         u8 lec = 0;
5978
5979         switch (brightness_mode) {
5980         case TPACPI_BRGHT_MODE_UCMS_STEP:
5981                 *status = tpacpi_brightness_nvram_get();
5982                 return 0;
5983         case TPACPI_BRGHT_MODE_EC:
5984         case TPACPI_BRGHT_MODE_ECNVRAM:
5985                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5986                         return -EIO;
5987                 *status = lec;
5988                 return 0;
5989         default:
5990                 return -ENXIO;
5991         }
5992 }
5993
5994 /* call with brightness_mutex held! */
5995 /* do NOT call with illegal backlight level value */
5996 static int tpacpi_brightness_set_ec(unsigned int value)
5997 {
5998         u8 lec = 0;
5999
6000         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6001                 return -EIO;
6002
6003         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
6004                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
6005                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
6006                 return -EIO;
6007
6008         return 0;
6009 }
6010
6011 /* call with brightness_mutex held! */
6012 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
6013 {
6014         int cmos_cmd, inc;
6015         unsigned int current_value, i;
6016
6017         current_value = tpacpi_brightness_nvram_get();
6018
6019         if (value == current_value)
6020                 return 0;
6021
6022         cmos_cmd = (value > current_value) ?
6023                         TP_CMOS_BRIGHTNESS_UP :
6024                         TP_CMOS_BRIGHTNESS_DOWN;
6025         inc = (value > current_value) ? 1 : -1;
6026
6027         for (i = current_value; i != value; i += inc)
6028                 if (issue_thinkpad_cmos_command(cmos_cmd))
6029                         return -EIO;
6030
6031         return 0;
6032 }
6033
6034 /* May return EINTR which can always be mapped to ERESTARTSYS */
6035 static int brightness_set(unsigned int value)
6036 {
6037         int res;
6038
6039         if (value > bright_maxlvl || value < 0)
6040                 return -EINVAL;
6041
6042         vdbg_printk(TPACPI_DBG_BRGHT,
6043                         "set backlight level to %d\n", value);
6044
6045         res = mutex_lock_killable(&brightness_mutex);
6046         if (res < 0)
6047                 return res;
6048
6049         switch (brightness_mode) {
6050         case TPACPI_BRGHT_MODE_EC:
6051         case TPACPI_BRGHT_MODE_ECNVRAM:
6052                 res = tpacpi_brightness_set_ec(value);
6053                 break;
6054         case TPACPI_BRGHT_MODE_UCMS_STEP:
6055                 res = tpacpi_brightness_set_ucmsstep(value);
6056                 break;
6057         default:
6058                 res = -ENXIO;
6059         }
6060
6061         mutex_unlock(&brightness_mutex);
6062         return res;
6063 }
6064
6065 /* sysfs backlight class ----------------------------------------------- */
6066
6067 static int brightness_update_status(struct backlight_device *bd)
6068 {
6069         unsigned int level =
6070                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
6071                  bd->props.power == FB_BLANK_UNBLANK) ?
6072                                 bd->props.brightness : 0;
6073
6074         dbg_printk(TPACPI_DBG_BRGHT,
6075                         "backlight: attempt to set level to %d\n",
6076                         level);
6077
6078         /* it is the backlight class's job (caller) to handle
6079          * EINTR and other errors properly */
6080         return brightness_set(level);
6081 }
6082
6083 static int brightness_get(struct backlight_device *bd)
6084 {
6085         int status, res;
6086
6087         res = mutex_lock_killable(&brightness_mutex);
6088         if (res < 0)
6089                 return 0;
6090
6091         res = tpacpi_brightness_get_raw(&status);
6092
6093         mutex_unlock(&brightness_mutex);
6094
6095         if (res < 0)
6096                 return 0;
6097
6098         return status & TP_EC_BACKLIGHT_LVLMSK;
6099 }
6100
6101 static void tpacpi_brightness_notify_change(void)
6102 {
6103         backlight_force_update(ibm_backlight_device,
6104                                BACKLIGHT_UPDATE_HOTKEY);
6105 }
6106
6107 static struct backlight_ops ibm_backlight_data = {
6108         .get_brightness = brightness_get,
6109         .update_status  = brightness_update_status,
6110 };
6111
6112 /* --------------------------------------------------------------------- */
6113
6114 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
6115 {
6116         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
6117         union acpi_object *obj;
6118         int rc;
6119
6120         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
6121                 obj = (union acpi_object *)buffer.pointer;
6122                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
6123                         printk(TPACPI_ERR "Unknown _BCL data, "
6124                                "please report this to %s\n", TPACPI_MAIL);
6125                         rc = 0;
6126                 } else {
6127                         rc = obj->package.count;
6128                 }
6129         } else {
6130                 return 0;
6131         }
6132
6133         kfree(buffer.pointer);
6134         return rc;
6135 }
6136
6137 static acpi_status __init tpacpi_acpi_walk_find_bcl(acpi_handle handle,
6138                                         u32 lvl, void *context, void **rv)
6139 {
6140         char name[ACPI_PATH_SEGMENT_LENGTH];
6141         struct acpi_buffer buffer = { sizeof(name), &name };
6142
6143         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
6144             !strncmp("_BCL", name, sizeof(name) - 1)) {
6145                 BUG_ON(!rv || !*rv);
6146                 **(int **)rv = tpacpi_query_bcl_levels(handle);
6147                 return AE_CTRL_TERMINATE;
6148         } else {
6149                 return AE_OK;
6150         }
6151 }
6152
6153 /*
6154  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
6155  */
6156 static unsigned int __init tpacpi_check_std_acpi_brightness_support(void)
6157 {
6158         int status;
6159         int bcl_levels = 0;
6160         void *bcl_ptr = &bcl_levels;
6161
6162         if (!vid_handle)
6163                 TPACPI_ACPIHANDLE_INIT(vid);
6164
6165         if (!vid_handle)
6166                 return 0;
6167
6168         /*
6169          * Search for a _BCL method, and execute it.  This is safe on all
6170          * ThinkPads, and as a side-effect, _BCL will place a Lenovo Vista
6171          * BIOS in ACPI backlight control mode.  We do NOT have to care
6172          * about calling the _BCL method in an enabled video device, any
6173          * will do for our purposes.
6174          */
6175
6176         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
6177                                      tpacpi_acpi_walk_find_bcl, NULL, NULL,
6178                                      &bcl_ptr);
6179
6180         if (ACPI_SUCCESS(status) && bcl_levels > 2) {
6181                 tp_features.bright_acpimode = 1;
6182                 return bcl_levels - 2;
6183         }
6184
6185         return 0;
6186 }
6187
6188 /*
6189  * These are only useful for models that have only one possibility
6190  * of GPU.  If the BIOS model handles both ATI and Intel, don't use
6191  * these quirks.
6192  */
6193 #define TPACPI_BRGHT_Q_NOEC     0x0001  /* Must NOT use EC HBRV */
6194 #define TPACPI_BRGHT_Q_EC       0x0002  /* Should or must use EC HBRV */
6195 #define TPACPI_BRGHT_Q_ASK      0x8000  /* Ask for user report */
6196
6197 static const struct tpacpi_quirk brightness_quirk_table[] __initconst = {
6198         /* Models with ATI GPUs known to require ECNVRAM mode */
6199         TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC),      /* T43/p ATI */
6200
6201         /* Models with ATI GPUs that can use ECNVRAM */
6202         TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC),      /* R50,51 T40-42 */
6203         TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6204         TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_EC),      /* R52 */
6205         TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6206
6207         /* Models with Intel Extreme Graphics 2 */
6208         TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC),    /* X40 */
6209         TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6210         TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6211
6212         /* Models with Intel GMA900 */
6213         TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC),    /* T43, R52 */
6214         TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC),    /* X41 */
6215         TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC),    /* X41 Tablet */
6216 };
6217
6218 /*
6219  * Returns < 0 for error, otherwise sets tp_features.bright_*
6220  * and bright_maxlvl.
6221  */
6222 static void __init tpacpi_detect_brightness_capabilities(void)
6223 {
6224         unsigned int b;
6225
6226         vdbg_printk(TPACPI_DBG_INIT,
6227                     "detecting firmware brightness interface capabilities\n");
6228
6229         /* we could run a quirks check here (same table used by
6230          * brightness_init) if needed */
6231
6232         /*
6233          * We always attempt to detect acpi support, so as to switch
6234          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
6235          * going to publish a backlight interface
6236          */
6237         b = tpacpi_check_std_acpi_brightness_support();
6238         switch (b) {
6239         case 16:
6240                 bright_maxlvl = 15;
6241                 printk(TPACPI_INFO
6242                        "detected a 16-level brightness capable ThinkPad\n");
6243                 break;
6244         case 8:
6245         case 0:
6246                 bright_maxlvl = 7;
6247                 printk(TPACPI_INFO
6248                        "detected a 8-level brightness capable ThinkPad\n");
6249                 break;
6250         default:
6251                 printk(TPACPI_ERR
6252                        "Unsupported brightness interface, "
6253                        "please contact %s\n", TPACPI_MAIL);
6254                 tp_features.bright_unkfw = 1;
6255                 bright_maxlvl = b - 1;
6256         }
6257 }
6258
6259 static int __init brightness_init(struct ibm_init_struct *iibm)
6260 {
6261         struct backlight_properties props;
6262         int b;
6263         unsigned long quirks;
6264
6265         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
6266
6267         mutex_init(&brightness_mutex);
6268
6269         quirks = tpacpi_check_quirks(brightness_quirk_table,
6270                                 ARRAY_SIZE(brightness_quirk_table));
6271
6272         /* tpacpi_detect_brightness_capabilities() must have run already */
6273
6274         /* if it is unknown, we don't handle it: it wouldn't be safe */
6275         if (tp_features.bright_unkfw)
6276                 return 1;
6277
6278         if (tp_features.bright_acpimode) {
6279                 if (acpi_video_backlight_support()) {
6280                         if (brightness_enable > 1) {
6281                                 printk(TPACPI_NOTICE
6282                                        "Standard ACPI backlight interface "
6283                                        "available, not loading native one.\n");
6284                                 return 1;
6285                         } else if (brightness_enable == 1) {
6286                                 printk(TPACPI_NOTICE
6287                                        "Backlight control force enabled, even if standard "
6288                                        "ACPI backlight interface is available\n");
6289                         }
6290                 } else {
6291                         if (brightness_enable > 1) {
6292                                 printk(TPACPI_NOTICE
6293                                        "Standard ACPI backlight interface not "
6294                                        "available, thinkpad_acpi native "
6295                                        "brightness control enabled\n");
6296                         }
6297                 }
6298         }
6299
6300         if (!brightness_enable) {
6301                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6302                            "brightness support disabled by "
6303                            "module parameter\n");
6304                 return 1;
6305         }
6306
6307         /*
6308          * Check for module parameter bogosity, note that we
6309          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6310          * able to detect "unspecified"
6311          */
6312         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6313                 return -EINVAL;
6314
6315         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6316         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6317             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6318                 if (quirks & TPACPI_BRGHT_Q_EC)
6319                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6320                 else
6321                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6322
6323                 dbg_printk(TPACPI_DBG_BRGHT,
6324                            "driver auto-selected brightness_mode=%d\n",
6325                            brightness_mode);
6326         }
6327
6328         /* Safety */
6329         if (!tpacpi_is_ibm() &&
6330             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6331              brightness_mode == TPACPI_BRGHT_MODE_EC))
6332                 return -EINVAL;
6333
6334         if (tpacpi_brightness_get_raw(&b) < 0)
6335                 return 1;
6336
6337         memset(&props, 0, sizeof(struct backlight_properties));
6338         props.max_brightness = bright_maxlvl;
6339         props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6340         ibm_backlight_device = backlight_device_register(TPACPI_BACKLIGHT_DEV_NAME,
6341                                                          NULL, NULL,
6342                                                          &ibm_backlight_data,
6343                                                          &props);
6344         if (IS_ERR(ibm_backlight_device)) {
6345                 int rc = PTR_ERR(ibm_backlight_device);
6346                 ibm_backlight_device = NULL;
6347                 printk(TPACPI_ERR "Could not register backlight device\n");
6348                 return rc;
6349         }
6350         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6351                         "brightness is supported\n");
6352
6353         if (quirks & TPACPI_BRGHT_Q_ASK) {
6354                 printk(TPACPI_NOTICE
6355                         "brightness: will use unverified default: "
6356                         "brightness_mode=%d\n", brightness_mode);
6357                 printk(TPACPI_NOTICE
6358                         "brightness: please report to %s whether it works well "
6359                         "or not on your ThinkPad\n", TPACPI_MAIL);
6360         }
6361
6362         backlight_update_status(ibm_backlight_device);
6363
6364         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6365                         "brightness: registering brightness hotkeys "
6366                         "as change notification\n");
6367         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
6368                                 | TP_ACPI_HKEY_BRGHTUP_MASK
6369                                 | TP_ACPI_HKEY_BRGHTDWN_MASK);;
6370         return 0;
6371 }
6372
6373 static void brightness_suspend(pm_message_t state)
6374 {
6375         tpacpi_brightness_checkpoint_nvram();
6376 }
6377
6378 static void brightness_shutdown(void)
6379 {
6380         tpacpi_brightness_checkpoint_nvram();
6381 }
6382
6383 static void brightness_exit(void)
6384 {
6385         if (ibm_backlight_device) {
6386                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6387                             "calling backlight_device_unregister()\n");
6388                 backlight_device_unregister(ibm_backlight_device);
6389         }
6390
6391         tpacpi_brightness_checkpoint_nvram();
6392 }
6393
6394 static int brightness_read(struct seq_file *m)
6395 {
6396         int level;
6397
6398         level = brightness_get(NULL);
6399         if (level < 0) {
6400                 seq_printf(m, "level:\t\tunreadable\n");
6401         } else {
6402                 seq_printf(m, "level:\t\t%d\n", level);
6403                 seq_printf(m, "commands:\tup, down\n");
6404                 seq_printf(m, "commands:\tlevel <level> (<level> is 0-%d)\n",
6405                                bright_maxlvl);
6406         }
6407
6408         return 0;
6409 }
6410
6411 static int brightness_write(char *buf)
6412 {
6413         int level;
6414         int rc;
6415         char *cmd;
6416
6417         level = brightness_get(NULL);
6418         if (level < 0)
6419                 return level;
6420
6421         while ((cmd = next_cmd(&buf))) {
6422                 if (strlencmp(cmd, "up") == 0) {
6423                         if (level < bright_maxlvl)
6424                                 level++;
6425                 } else if (strlencmp(cmd, "down") == 0) {
6426                         if (level > 0)
6427                                 level--;
6428                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6429                            level >= 0 && level <= bright_maxlvl) {
6430                         /* new level set */
6431                 } else
6432                         return -EINVAL;
6433         }
6434
6435         tpacpi_disclose_usertask("procfs brightness",
6436                         "set level to %d\n", level);
6437
6438         /*
6439          * Now we know what the final level should be, so we try to set it.
6440          * Doing it this way makes the syscall restartable in case of EINTR
6441          */
6442         rc = brightness_set(level);
6443         if (!rc && ibm_backlight_device)
6444                 backlight_force_update(ibm_backlight_device,
6445                                         BACKLIGHT_UPDATE_SYSFS);
6446         return (rc == -EINTR)? -ERESTARTSYS : rc;
6447 }
6448
6449 static struct ibm_struct brightness_driver_data = {
6450         .name = "brightness",
6451         .read = brightness_read,
6452         .write = brightness_write,
6453         .exit = brightness_exit,
6454         .suspend = brightness_suspend,
6455         .shutdown = brightness_shutdown,
6456 };
6457
6458 /*************************************************************************
6459  * Volume subdriver
6460  */
6461
6462 /*
6463  * IBM ThinkPads have a simple volume controller with MUTE gating.
6464  * Very early Lenovo ThinkPads follow the IBM ThinkPad spec.
6465  *
6466  * Since the *61 series (and probably also the later *60 series), Lenovo
6467  * ThinkPads only implement the MUTE gate.
6468  *
6469  * EC register 0x30
6470  *   Bit 6: MUTE (1 mutes sound)
6471  *   Bit 3-0: Volume
6472  *   Other bits should be zero as far as we know.
6473  *
6474  * This is also stored in CMOS NVRAM, byte 0x60, bit 6 (MUTE), and
6475  * bits 3-0 (volume).  Other bits in NVRAM may have other functions,
6476  * such as bit 7 which is used to detect repeated presses of MUTE,
6477  * and we leave them unchanged.
6478  */
6479
6480 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
6481
6482 #define TPACPI_ALSA_DRVNAME  "ThinkPad EC"
6483 #define TPACPI_ALSA_SHRTNAME "ThinkPad Console Audio Control"
6484 #define TPACPI_ALSA_MIXERNAME TPACPI_ALSA_SHRTNAME
6485
6486 static int alsa_index = ~((1 << (SNDRV_CARDS - 3)) - 1); /* last three slots */
6487 static char *alsa_id = "ThinkPadEC";
6488 static int alsa_enable = SNDRV_DEFAULT_ENABLE1;
6489
6490 struct tpacpi_alsa_data {
6491         struct snd_card *card;
6492         struct snd_ctl_elem_id *ctl_mute_id;
6493         struct snd_ctl_elem_id *ctl_vol_id;
6494 };
6495
6496 static struct snd_card *alsa_card;
6497
6498 enum {
6499         TP_EC_AUDIO = 0x30,
6500
6501         /* TP_EC_AUDIO bits */
6502         TP_EC_AUDIO_MUTESW = 6,
6503
6504         /* TP_EC_AUDIO bitmasks */
6505         TP_EC_AUDIO_LVL_MSK = 0x0F,
6506         TP_EC_AUDIO_MUTESW_MSK = (1 << TP_EC_AUDIO_MUTESW),
6507
6508         /* Maximum volume */
6509         TP_EC_VOLUME_MAX = 14,
6510 };
6511
6512 enum tpacpi_volume_access_mode {
6513         TPACPI_VOL_MODE_AUTO = 0,       /* Not implemented yet */
6514         TPACPI_VOL_MODE_EC,             /* Pure EC control */
6515         TPACPI_VOL_MODE_UCMS_STEP,      /* UCMS step-based control: N/A */
6516         TPACPI_VOL_MODE_ECNVRAM,        /* EC control w/ NVRAM store */
6517         TPACPI_VOL_MODE_MAX
6518 };
6519
6520 enum tpacpi_volume_capabilities {
6521         TPACPI_VOL_CAP_AUTO = 0,        /* Use white/blacklist */
6522         TPACPI_VOL_CAP_VOLMUTE,         /* Output vol and mute */
6523         TPACPI_VOL_CAP_MUTEONLY,        /* Output mute only */
6524         TPACPI_VOL_CAP_MAX
6525 };
6526
6527 static enum tpacpi_volume_access_mode volume_mode =
6528         TPACPI_VOL_MODE_MAX;
6529
6530 static enum tpacpi_volume_capabilities volume_capabilities;
6531 static int volume_control_allowed;
6532
6533 /*
6534  * Used to syncronize writers to TP_EC_AUDIO and
6535  * TP_NVRAM_ADDR_MIXER, as we need to do read-modify-write
6536  */
6537 static struct mutex volume_mutex;
6538
6539 static void tpacpi_volume_checkpoint_nvram(void)
6540 {
6541         u8 lec = 0;
6542         u8 b_nvram;
6543         u8 ec_mask;
6544
6545         if (volume_mode != TPACPI_VOL_MODE_ECNVRAM)
6546                 return;
6547         if (!volume_control_allowed)
6548                 return;
6549
6550         vdbg_printk(TPACPI_DBG_MIXER,
6551                 "trying to checkpoint mixer state to NVRAM...\n");
6552
6553         if (tp_features.mixer_no_level_control)
6554                 ec_mask = TP_EC_AUDIO_MUTESW_MSK;
6555         else
6556                 ec_mask = TP_EC_AUDIO_MUTESW_MSK | TP_EC_AUDIO_LVL_MSK;
6557
6558         if (mutex_lock_killable(&volume_mutex) < 0)
6559                 return;
6560
6561         if (unlikely(!acpi_ec_read(TP_EC_AUDIO, &lec)))
6562                 goto unlock;
6563         lec &= ec_mask;
6564         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
6565
6566         if (lec != (b_nvram & ec_mask)) {
6567                 /* NVRAM needs update */
6568                 b_nvram &= ~ec_mask;
6569                 b_nvram |= lec;
6570                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_MIXER);
6571                 dbg_printk(TPACPI_DBG_MIXER,
6572                            "updated NVRAM mixer status to 0x%02x (0x%02x)\n",
6573                            (unsigned int) lec, (unsigned int) b_nvram);
6574         } else {
6575                 vdbg_printk(TPACPI_DBG_MIXER,
6576                            "NVRAM mixer status already is 0x%02x (0x%02x)\n",
6577                            (unsigned int) lec, (unsigned int) b_nvram);
6578         }
6579
6580 unlock:
6581         mutex_unlock(&volume_mutex);
6582 }
6583
6584 static int volume_get_status_ec(u8 *status)
6585 {
6586         u8 s;
6587
6588         if (!acpi_ec_read(TP_EC_AUDIO, &s))
6589                 return -EIO;
6590
6591         *status = s;
6592
6593         dbg_printk(TPACPI_DBG_MIXER, "status 0x%02x\n", s);
6594
6595         return 0;
6596 }
6597
6598 static int volume_get_status(u8 *status)
6599 {
6600         return volume_get_status_ec(status);
6601 }
6602
6603 static int volume_set_status_ec(const u8 status)
6604 {
6605         if (!acpi_ec_write(TP_EC_AUDIO, status))
6606                 return -EIO;
6607
6608         dbg_printk(TPACPI_DBG_MIXER, "set EC mixer to 0x%02x\n", status);
6609
6610         return 0;
6611 }
6612
6613 static int volume_set_status(const u8 status)
6614 {
6615         return volume_set_status_ec(status);
6616 }
6617
6618 /* returns < 0 on error, 0 on no change, 1 on change */
6619 static int __volume_set_mute_ec(const bool mute)
6620 {
6621         int rc;
6622         u8 s, n;
6623
6624         if (mutex_lock_killable(&volume_mutex) < 0)
6625                 return -EINTR;
6626
6627         rc = volume_get_status_ec(&s);
6628         if (rc)
6629                 goto unlock;
6630
6631         n = (mute) ? s | TP_EC_AUDIO_MUTESW_MSK :
6632                      s & ~TP_EC_AUDIO_MUTESW_MSK;
6633
6634         if (n != s) {
6635                 rc = volume_set_status_ec(n);
6636                 if (!rc)
6637                         rc = 1;
6638         }
6639
6640 unlock:
6641         mutex_unlock(&volume_mutex);
6642         return rc;
6643 }
6644
6645 static int volume_alsa_set_mute(const bool mute)
6646 {
6647         dbg_printk(TPACPI_DBG_MIXER, "ALSA: trying to %smute\n",
6648                    (mute) ? "" : "un");
6649         return __volume_set_mute_ec(mute);
6650 }
6651
6652 static int volume_set_mute(const bool mute)
6653 {
6654         int rc;
6655
6656         dbg_printk(TPACPI_DBG_MIXER, "trying to %smute\n",
6657                    (mute) ? "" : "un");
6658
6659         rc = __volume_set_mute_ec(mute);
6660         return (rc < 0) ? rc : 0;
6661 }
6662
6663 /* returns < 0 on error, 0 on no change, 1 on change */
6664 static int __volume_set_volume_ec(const u8 vol)
6665 {
6666         int rc;
6667         u8 s, n;
6668
6669         if (vol > TP_EC_VOLUME_MAX)
6670                 return -EINVAL;
6671
6672         if (mutex_lock_killable(&volume_mutex) < 0)
6673                 return -EINTR;
6674
6675         rc = volume_get_status_ec(&s);
6676         if (rc)
6677                 goto unlock;
6678
6679         n = (s & ~TP_EC_AUDIO_LVL_MSK) | vol;
6680
6681         if (n != s) {
6682                 rc = volume_set_status_ec(n);
6683                 if (!rc)
6684                         rc = 1;
6685         }
6686
6687 unlock:
6688         mutex_unlock(&volume_mutex);
6689         return rc;
6690 }
6691
6692 static int volume_alsa_set_volume(const u8 vol)
6693 {
6694         dbg_printk(TPACPI_DBG_MIXER,
6695                    "ALSA: trying to set volume level to %hu\n", vol);
6696         return __volume_set_volume_ec(vol);
6697 }
6698
6699 static void volume_alsa_notify_change(void)
6700 {
6701         struct tpacpi_alsa_data *d;
6702
6703         if (alsa_card && alsa_card->private_data) {
6704                 d = alsa_card->private_data;
6705                 if (d->ctl_mute_id)
6706                         snd_ctl_notify(alsa_card,
6707                                         SNDRV_CTL_EVENT_MASK_VALUE,
6708                                         d->ctl_mute_id);
6709                 if (d->ctl_vol_id)
6710                         snd_ctl_notify(alsa_card,
6711                                         SNDRV_CTL_EVENT_MASK_VALUE,
6712                                         d->ctl_vol_id);
6713         }
6714 }
6715
6716 static int volume_alsa_vol_info(struct snd_kcontrol *kcontrol,
6717                                 struct snd_ctl_elem_info *uinfo)
6718 {
6719         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
6720         uinfo->count = 1;
6721         uinfo->value.integer.min = 0;
6722         uinfo->value.integer.max = TP_EC_VOLUME_MAX;
6723         return 0;
6724 }
6725
6726 static int volume_alsa_vol_get(struct snd_kcontrol *kcontrol,
6727                                 struct snd_ctl_elem_value *ucontrol)
6728 {
6729         u8 s;
6730         int rc;
6731
6732         rc = volume_get_status(&s);
6733         if (rc < 0)
6734                 return rc;
6735
6736         ucontrol->value.integer.value[0] = s & TP_EC_AUDIO_LVL_MSK;
6737         return 0;
6738 }
6739
6740 static int volume_alsa_vol_put(struct snd_kcontrol *kcontrol,
6741                                 struct snd_ctl_elem_value *ucontrol)
6742 {
6743         tpacpi_disclose_usertask("ALSA", "set volume to %ld\n",
6744                                  ucontrol->value.integer.value[0]);
6745         return volume_alsa_set_volume(ucontrol->value.integer.value[0]);
6746 }
6747
6748 #define volume_alsa_mute_info snd_ctl_boolean_mono_info
6749
6750 static int volume_alsa_mute_get(struct snd_kcontrol *kcontrol,
6751                                 struct snd_ctl_elem_value *ucontrol)
6752 {
6753         u8 s;
6754         int rc;
6755
6756         rc = volume_get_status(&s);
6757         if (rc < 0)
6758                 return rc;
6759
6760         ucontrol->value.integer.value[0] =
6761                                 (s & TP_EC_AUDIO_MUTESW_MSK) ? 0 : 1;
6762         return 0;
6763 }
6764
6765 static int volume_alsa_mute_put(struct snd_kcontrol *kcontrol,
6766                                 struct snd_ctl_elem_value *ucontrol)
6767 {
6768         tpacpi_disclose_usertask("ALSA", "%smute\n",
6769                                  ucontrol->value.integer.value[0] ?
6770                                         "un" : "");
6771         return volume_alsa_set_mute(!ucontrol->value.integer.value[0]);
6772 }
6773
6774 static struct snd_kcontrol_new volume_alsa_control_vol __devinitdata = {
6775         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
6776         .name = "Console Playback Volume",
6777         .index = 0,
6778         .access = SNDRV_CTL_ELEM_ACCESS_READ,
6779         .info = volume_alsa_vol_info,
6780         .get = volume_alsa_vol_get,
6781 };
6782
6783 static struct snd_kcontrol_new volume_alsa_control_mute __devinitdata = {
6784         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
6785         .name = "Console Playback Switch",
6786         .index = 0,
6787         .access = SNDRV_CTL_ELEM_ACCESS_READ,
6788         .info = volume_alsa_mute_info,
6789         .get = volume_alsa_mute_get,
6790 };
6791
6792 static void volume_suspend(pm_message_t state)
6793 {
6794         tpacpi_volume_checkpoint_nvram();
6795 }
6796
6797 static void volume_resume(void)
6798 {
6799         volume_alsa_notify_change();
6800 }
6801
6802 static void volume_shutdown(void)
6803 {
6804         tpacpi_volume_checkpoint_nvram();
6805 }
6806
6807 static void volume_exit(void)
6808 {
6809         if (alsa_card) {
6810                 snd_card_free(alsa_card);
6811                 alsa_card = NULL;
6812         }
6813
6814         tpacpi_volume_checkpoint_nvram();
6815 }
6816
6817 static int __init volume_create_alsa_mixer(void)
6818 {
6819         struct snd_card *card;
6820         struct tpacpi_alsa_data *data;
6821         struct snd_kcontrol *ctl_vol;
6822         struct snd_kcontrol *ctl_mute;
6823         int rc;
6824
6825         rc = snd_card_create(alsa_index, alsa_id, THIS_MODULE,
6826                             sizeof(struct tpacpi_alsa_data), &card);
6827         if (rc < 0 || !card) {
6828                 printk(TPACPI_ERR
6829                         "Failed to create ALSA card structures: %d\n", rc);
6830                 return 1;
6831         }
6832
6833         BUG_ON(!card->private_data);
6834         data = card->private_data;
6835         data->card = card;
6836
6837         strlcpy(card->driver, TPACPI_ALSA_DRVNAME,
6838                 sizeof(card->driver));
6839         strlcpy(card->shortname, TPACPI_ALSA_SHRTNAME,
6840                 sizeof(card->shortname));
6841         snprintf(card->mixername, sizeof(card->mixername), "ThinkPad EC %s",
6842                  (thinkpad_id.ec_version_str) ?
6843                         thinkpad_id.ec_version_str : "(unknown)");
6844         snprintf(card->longname, sizeof(card->longname),
6845                  "%s at EC reg 0x%02x, fw %s", card->shortname, TP_EC_AUDIO,
6846                  (thinkpad_id.ec_version_str) ?
6847                         thinkpad_id.ec_version_str : "unknown");
6848
6849         if (volume_control_allowed) {
6850                 volume_alsa_control_vol.put = volume_alsa_vol_put;
6851                 volume_alsa_control_vol.access =
6852                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
6853
6854                 volume_alsa_control_mute.put = volume_alsa_mute_put;
6855                 volume_alsa_control_mute.access =
6856                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
6857         }
6858
6859         if (!tp_features.mixer_no_level_control) {
6860                 ctl_vol = snd_ctl_new1(&volume_alsa_control_vol, NULL);
6861                 rc = snd_ctl_add(card, ctl_vol);
6862                 if (rc < 0) {
6863                         printk(TPACPI_ERR
6864                                 "Failed to create ALSA volume control: %d\n",
6865                                 rc);
6866                         goto err_exit;
6867                 }
6868                 data->ctl_vol_id = &ctl_vol->id;
6869         }
6870
6871         ctl_mute = snd_ctl_new1(&volume_alsa_control_mute, NULL);
6872         rc = snd_ctl_add(card, ctl_mute);
6873         if (rc < 0) {
6874                 printk(TPACPI_ERR "Failed to create ALSA mute control: %d\n",
6875                         rc);
6876                 goto err_exit;
6877         }
6878         data->ctl_mute_id = &ctl_mute->id;
6879
6880         snd_card_set_dev(card, &tpacpi_pdev->dev);
6881         rc = snd_card_register(card);
6882         if (rc < 0) {
6883                 printk(TPACPI_ERR "Failed to register ALSA card: %d\n", rc);
6884                 goto err_exit;
6885         }
6886
6887         alsa_card = card;
6888         return 0;
6889
6890 err_exit:
6891         snd_card_free(card);
6892         return 1;
6893 }
6894
6895 #define TPACPI_VOL_Q_MUTEONLY   0x0001  /* Mute-only control available */
6896 #define TPACPI_VOL_Q_LEVEL      0x0002  /* Volume control available */
6897
6898 static const struct tpacpi_quirk volume_quirk_table[] __initconst = {
6899         /* Whitelist volume level on all IBM by default */
6900         { .vendor = PCI_VENDOR_ID_IBM,
6901           .bios   = TPACPI_MATCH_ANY,
6902           .ec     = TPACPI_MATCH_ANY,
6903           .quirks = TPACPI_VOL_Q_LEVEL },
6904
6905         /* Lenovo models with volume control (needs confirmation) */
6906         TPACPI_QEC_LNV('7', 'C', TPACPI_VOL_Q_LEVEL), /* R60/i */
6907         TPACPI_QEC_LNV('7', 'E', TPACPI_VOL_Q_LEVEL), /* R60e/i */
6908         TPACPI_QEC_LNV('7', '9', TPACPI_VOL_Q_LEVEL), /* T60/p */
6909         TPACPI_QEC_LNV('7', 'B', TPACPI_VOL_Q_LEVEL), /* X60/s */
6910         TPACPI_QEC_LNV('7', 'J', TPACPI_VOL_Q_LEVEL), /* X60t */
6911         TPACPI_QEC_LNV('7', '7', TPACPI_VOL_Q_LEVEL), /* Z60 */
6912         TPACPI_QEC_LNV('7', 'F', TPACPI_VOL_Q_LEVEL), /* Z61 */
6913
6914         /* Whitelist mute-only on all Lenovo by default */
6915         { .vendor = PCI_VENDOR_ID_LENOVO,
6916           .bios   = TPACPI_MATCH_ANY,
6917           .ec     = TPACPI_MATCH_ANY,
6918           .quirks = TPACPI_VOL_Q_MUTEONLY }
6919 };
6920
6921 static int __init volume_init(struct ibm_init_struct *iibm)
6922 {
6923         unsigned long quirks;
6924         int rc;
6925
6926         vdbg_printk(TPACPI_DBG_INIT, "initializing volume subdriver\n");
6927
6928         mutex_init(&volume_mutex);
6929
6930         /*
6931          * Check for module parameter bogosity, note that we
6932          * init volume_mode to TPACPI_VOL_MODE_MAX in order to be
6933          * able to detect "unspecified"
6934          */
6935         if (volume_mode > TPACPI_VOL_MODE_MAX)
6936                 return -EINVAL;
6937
6938         if (volume_mode == TPACPI_VOL_MODE_UCMS_STEP) {
6939                 printk(TPACPI_ERR
6940                         "UCMS step volume mode not implemented, "
6941                         "please contact %s\n", TPACPI_MAIL);
6942                 return 1;
6943         }
6944
6945         if (volume_capabilities >= TPACPI_VOL_CAP_MAX)
6946                 return -EINVAL;
6947
6948         /*
6949          * The ALSA mixer is our primary interface.
6950          * When disabled, don't install the subdriver at all
6951          */
6952         if (!alsa_enable) {
6953                 vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6954                             "ALSA mixer disabled by parameter, "
6955                             "not loading volume subdriver...\n");
6956                 return 1;
6957         }
6958
6959         quirks = tpacpi_check_quirks(volume_quirk_table,
6960                                      ARRAY_SIZE(volume_quirk_table));
6961
6962         switch (volume_capabilities) {
6963         case TPACPI_VOL_CAP_AUTO:
6964                 if (quirks & TPACPI_VOL_Q_MUTEONLY)
6965                         tp_features.mixer_no_level_control = 1;
6966                 else if (quirks & TPACPI_VOL_Q_LEVEL)
6967                         tp_features.mixer_no_level_control = 0;
6968                 else
6969                         return 1; /* no mixer */
6970                 break;
6971         case TPACPI_VOL_CAP_VOLMUTE:
6972                 tp_features.mixer_no_level_control = 0;
6973                 break;
6974         case TPACPI_VOL_CAP_MUTEONLY:
6975                 tp_features.mixer_no_level_control = 1;
6976                 break;
6977         default:
6978                 return 1;
6979         }
6980
6981         if (volume_capabilities != TPACPI_VOL_CAP_AUTO)
6982                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6983                                 "using user-supplied volume_capabilities=%d\n",
6984                                 volume_capabilities);
6985
6986         if (volume_mode == TPACPI_VOL_MODE_AUTO ||
6987             volume_mode == TPACPI_VOL_MODE_MAX) {
6988                 volume_mode = TPACPI_VOL_MODE_ECNVRAM;
6989
6990                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6991                                 "driver auto-selected volume_mode=%d\n",
6992                                 volume_mode);
6993         } else {
6994                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
6995                                 "using user-supplied volume_mode=%d\n",
6996                                 volume_mode);
6997         }
6998
6999         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7000                         "mute is supported, volume control is %s\n",
7001                         str_supported(!tp_features.mixer_no_level_control));
7002
7003         rc = volume_create_alsa_mixer();
7004         if (rc) {
7005                 printk(TPACPI_ERR
7006                         "Could not create the ALSA mixer interface\n");
7007                 return rc;
7008         }
7009
7010         printk(TPACPI_INFO
7011                 "Console audio control enabled, mode: %s\n",
7012                 (volume_control_allowed) ?
7013                         "override (read/write)" :
7014                         "monitor (read only)");
7015
7016         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7017                 "registering volume hotkeys as change notification\n");
7018         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
7019                         | TP_ACPI_HKEY_VOLUP_MASK
7020                         | TP_ACPI_HKEY_VOLDWN_MASK
7021                         | TP_ACPI_HKEY_MUTE_MASK);
7022
7023         return 0;
7024 }
7025
7026 static int volume_read(struct seq_file *m)
7027 {
7028         u8 status;
7029
7030         if (volume_get_status(&status) < 0) {
7031                 seq_printf(m, "level:\t\tunreadable\n");
7032         } else {
7033                 if (tp_features.mixer_no_level_control)
7034                         seq_printf(m, "level:\t\tunsupported\n");
7035                 else
7036                         seq_printf(m, "level:\t\t%d\n",
7037                                         status & TP_EC_AUDIO_LVL_MSK);
7038
7039                 seq_printf(m, "mute:\t\t%s\n",
7040                                 onoff(status, TP_EC_AUDIO_MUTESW));
7041
7042                 if (volume_control_allowed) {
7043                         seq_printf(m, "commands:\tunmute, mute\n");
7044                         if (!tp_features.mixer_no_level_control) {
7045                                 seq_printf(m,
7046                                                "commands:\tup, down\n");
7047                                 seq_printf(m,
7048                                                "commands:\tlevel <level>"
7049                                                " (<level> is 0-%d)\n",
7050                                                TP_EC_VOLUME_MAX);
7051                         }
7052                 }
7053         }
7054
7055         return 0;
7056 }
7057
7058 static int volume_write(char *buf)
7059 {
7060         u8 s;
7061         u8 new_level, new_mute;
7062         int l;
7063         char *cmd;
7064         int rc;
7065
7066         /*
7067          * We do allow volume control at driver startup, so that the
7068          * user can set initial state through the volume=... parameter hack.
7069          */
7070         if (!volume_control_allowed && tpacpi_lifecycle != TPACPI_LIFE_INIT) {
7071                 if (unlikely(!tp_warned.volume_ctrl_forbidden)) {
7072                         tp_warned.volume_ctrl_forbidden = 1;
7073                         printk(TPACPI_NOTICE
7074                                 "Console audio control in monitor mode, "
7075                                 "changes are not allowed.\n");
7076                         printk(TPACPI_NOTICE
7077                                 "Use the volume_control=1 module parameter "
7078                                 "to enable volume control\n");
7079                 }
7080                 return -EPERM;
7081         }
7082
7083         rc = volume_get_status(&s);
7084         if (rc < 0)
7085                 return rc;
7086
7087         new_level = s & TP_EC_AUDIO_LVL_MSK;
7088         new_mute  = s & TP_EC_AUDIO_MUTESW_MSK;
7089
7090         while ((cmd = next_cmd(&buf))) {
7091                 if (!tp_features.mixer_no_level_control) {
7092                         if (strlencmp(cmd, "up") == 0) {
7093                                 if (new_mute)
7094                                         new_mute = 0;
7095                                 else if (new_level < TP_EC_VOLUME_MAX)
7096                                         new_level++;
7097                                 continue;
7098                         } else if (strlencmp(cmd, "down") == 0) {
7099                                 if (new_mute)
7100                                         new_mute = 0;
7101                                 else if (new_level > 0)
7102                                         new_level--;
7103                                 continue;
7104                         } else if (sscanf(cmd, "level %u", &l) == 1 &&
7105                                    l >= 0 && l <= TP_EC_VOLUME_MAX) {
7106                                         new_level = l;
7107                                 continue;
7108                         }
7109                 }
7110                 if (strlencmp(cmd, "mute") == 0)
7111                         new_mute = TP_EC_AUDIO_MUTESW_MSK;
7112                 else if (strlencmp(cmd, "unmute") == 0)
7113                         new_mute = 0;
7114                 else
7115                         return -EINVAL;
7116         }
7117
7118         if (tp_features.mixer_no_level_control) {
7119                 tpacpi_disclose_usertask("procfs volume", "%smute\n",
7120                                         new_mute ? "" : "un");
7121                 rc = volume_set_mute(!!new_mute);
7122         } else {
7123                 tpacpi_disclose_usertask("procfs volume",
7124                                         "%smute and set level to %d\n",
7125                                         new_mute ? "" : "un", new_level);
7126                 rc = volume_set_status(new_mute | new_level);
7127         }
7128         volume_alsa_notify_change();
7129
7130         return (rc == -EINTR) ? -ERESTARTSYS : rc;
7131 }
7132
7133 static struct ibm_struct volume_driver_data = {
7134         .name = "volume",
7135         .read = volume_read,
7136         .write = volume_write,
7137         .exit = volume_exit,
7138         .suspend = volume_suspend,
7139         .resume = volume_resume,
7140         .shutdown = volume_shutdown,
7141 };
7142
7143 #else /* !CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7144
7145 #define alsa_card NULL
7146
7147 static void inline volume_alsa_notify_change(void)
7148 {
7149 }
7150
7151 static int __init volume_init(struct ibm_init_struct *iibm)
7152 {
7153         printk(TPACPI_INFO
7154                 "volume: disabled as there is no ALSA support in this kernel\n");
7155
7156         return 1;
7157 }
7158
7159 static struct ibm_struct volume_driver_data = {
7160         .name = "volume",
7161 };
7162
7163 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7164
7165 /*************************************************************************
7166  * Fan subdriver
7167  */
7168
7169 /*
7170  * FAN ACCESS MODES
7171  *
7172  * TPACPI_FAN_RD_ACPI_GFAN:
7173  *      ACPI GFAN method: returns fan level
7174  *
7175  *      see TPACPI_FAN_WR_ACPI_SFAN
7176  *      EC 0x2f (HFSP) not available if GFAN exists
7177  *
7178  * TPACPI_FAN_WR_ACPI_SFAN:
7179  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
7180  *
7181  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
7182  *      it for writing.
7183  *
7184  * TPACPI_FAN_WR_TPEC:
7185  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
7186  *      Supported on almost all ThinkPads
7187  *
7188  *      Fan speed changes of any sort (including those caused by the
7189  *      disengaged mode) are usually done slowly by the firmware as the
7190  *      maximum amount of fan duty cycle change per second seems to be
7191  *      limited.
7192  *
7193  *      Reading is not available if GFAN exists.
7194  *      Writing is not available if SFAN exists.
7195  *
7196  *      Bits
7197  *       7      automatic mode engaged;
7198  *              (default operation mode of the ThinkPad)
7199  *              fan level is ignored in this mode.
7200  *       6      full speed mode (takes precedence over bit 7);
7201  *              not available on all thinkpads.  May disable
7202  *              the tachometer while the fan controller ramps up
7203  *              the speed (which can take up to a few *minutes*).
7204  *              Speeds up fan to 100% duty-cycle, which is far above
7205  *              the standard RPM levels.  It is not impossible that
7206  *              it could cause hardware damage.
7207  *      5-3     unused in some models.  Extra bits for fan level
7208  *              in others, but still useless as all values above
7209  *              7 map to the same speed as level 7 in these models.
7210  *      2-0     fan level (0..7 usually)
7211  *                      0x00 = stop
7212  *                      0x07 = max (set when temperatures critical)
7213  *              Some ThinkPads may have other levels, see
7214  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
7215  *
7216  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
7217  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
7218  *      does so, its initial value is meaningless (0x07).
7219  *
7220  *      For firmware bugs, refer to:
7221  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7222  *
7223  *      ----
7224  *
7225  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
7226  *      Main fan tachometer reading (in RPM)
7227  *
7228  *      This register is present on all ThinkPads with a new-style EC, and
7229  *      it is known not to be present on the A21m/e, and T22, as there is
7230  *      something else in offset 0x84 according to the ACPI DSDT.  Other
7231  *      ThinkPads from this same time period (and earlier) probably lack the
7232  *      tachometer as well.
7233  *
7234  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
7235  *      was never fixed by IBM to report the EC firmware version string
7236  *      probably support the tachometer (like the early X models), so
7237  *      detecting it is quite hard.  We need more data to know for sure.
7238  *
7239  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
7240  *      might result.
7241  *
7242  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
7243  *      mode.
7244  *
7245  *      For firmware bugs, refer to:
7246  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7247  *
7248  *      ----
7249  *
7250  *      ThinkPad EC register 0x31 bit 0 (only on select models)
7251  *
7252  *      When bit 0 of EC register 0x31 is zero, the tachometer registers
7253  *      show the speed of the main fan.  When bit 0 of EC register 0x31
7254  *      is one, the tachometer registers show the speed of the auxiliary
7255  *      fan.
7256  *
7257  *      Fan control seems to affect both fans, regardless of the state
7258  *      of this bit.
7259  *
7260  *      So far, only the firmware for the X60/X61 non-tablet versions
7261  *      seem to support this (firmware TP-7M).
7262  *
7263  * TPACPI_FAN_WR_ACPI_FANS:
7264  *      ThinkPad X31, X40, X41.  Not available in the X60.
7265  *
7266  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
7267  *      high speed.  ACPI DSDT seems to map these three speeds to levels
7268  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
7269  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
7270  *
7271  *      The speeds are stored on handles
7272  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
7273  *
7274  *      There are three default speed sets, accessible as handles:
7275  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
7276  *
7277  *      ACPI DSDT switches which set is in use depending on various
7278  *      factors.
7279  *
7280  *      TPACPI_FAN_WR_TPEC is also available and should be used to
7281  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
7282  *      but the ACPI tables just mention level 7.
7283  */
7284
7285 enum {                                  /* Fan control constants */
7286         fan_status_offset = 0x2f,       /* EC register 0x2f */
7287         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
7288                                          * 0x84 must be read before 0x85 */
7289         fan_select_offset = 0x31,       /* EC register 0x31 (Firmware 7M)
7290                                            bit 0 selects which fan is active */
7291
7292         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
7293         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
7294
7295         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
7296 };
7297
7298 enum fan_status_access_mode {
7299         TPACPI_FAN_NONE = 0,            /* No fan status or control */
7300         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
7301         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
7302 };
7303
7304 enum fan_control_access_mode {
7305         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
7306         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
7307         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
7308         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
7309 };
7310
7311 enum fan_control_commands {
7312         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
7313         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
7314         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
7315                                                  * and also watchdog cmd */
7316 };
7317
7318 static int fan_control_allowed;
7319
7320 static enum fan_status_access_mode fan_status_access_mode;
7321 static enum fan_control_access_mode fan_control_access_mode;
7322 static enum fan_control_commands fan_control_commands;
7323
7324 static u8 fan_control_initial_status;
7325 static u8 fan_control_desired_level;
7326 static u8 fan_control_resume_level;
7327 static int fan_watchdog_maxinterval;
7328
7329 static struct mutex fan_mutex;
7330
7331 static void fan_watchdog_fire(struct work_struct *ignored);
7332 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
7333
7334 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
7335 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
7336            "\\FSPD",            /* 600e/x, 770e, 770x */
7337            );                   /* all others */
7338 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
7339            "JFNS",              /* 770x-JL */
7340            );                   /* all others */
7341
7342 /*
7343  * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the
7344  * HFSP register at boot, so it contains 0x07 but the Thinkpad could
7345  * be in auto mode (0x80).
7346  *
7347  * This is corrected by any write to HFSP either by the driver, or
7348  * by the firmware.
7349  *
7350  * We assume 0x07 really means auto mode while this quirk is active,
7351  * as this is far more likely than the ThinkPad being in level 7,
7352  * which is only used by the firmware during thermal emergencies.
7353  *
7354  * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52),
7355  * TP-70 (T43, R52), which are known to be buggy.
7356  */
7357
7358 static void fan_quirk1_setup(void)
7359 {
7360         if (fan_control_initial_status == 0x07) {
7361                 printk(TPACPI_NOTICE
7362                        "fan_init: initial fan status is unknown, "
7363                        "assuming it is in auto mode\n");
7364                 tp_features.fan_ctrl_status_undef = 1;
7365         }
7366 }
7367
7368 static void fan_quirk1_handle(u8 *fan_status)
7369 {
7370         if (unlikely(tp_features.fan_ctrl_status_undef)) {
7371                 if (*fan_status != fan_control_initial_status) {
7372                         /* something changed the HFSP regisnter since
7373                          * driver init time, so it is not undefined
7374                          * anymore */
7375                         tp_features.fan_ctrl_status_undef = 0;
7376                 } else {
7377                         /* Return most likely status. In fact, it
7378                          * might be the only possible status */
7379                         *fan_status = TP_EC_FAN_AUTO;
7380                 }
7381         }
7382 }
7383
7384 /* Select main fan on X60/X61, NOOP on others */
7385 static bool fan_select_fan1(void)
7386 {
7387         if (tp_features.second_fan) {
7388                 u8 val;
7389
7390                 if (ec_read(fan_select_offset, &val) < 0)
7391                         return false;
7392                 val &= 0xFEU;
7393                 if (ec_write(fan_select_offset, val) < 0)
7394                         return false;
7395         }
7396         return true;
7397 }
7398
7399 /* Select secondary fan on X60/X61 */
7400 static bool fan_select_fan2(void)
7401 {
7402         u8 val;
7403
7404         if (!tp_features.second_fan)
7405                 return false;
7406
7407         if (ec_read(fan_select_offset, &val) < 0)
7408                 return false;
7409         val |= 0x01U;
7410         if (ec_write(fan_select_offset, val) < 0)
7411                 return false;
7412
7413         return true;
7414 }
7415
7416 /*
7417  * Call with fan_mutex held
7418  */
7419 static void fan_update_desired_level(u8 status)
7420 {
7421         if ((status &
7422              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
7423                 if (status > 7)
7424                         fan_control_desired_level = 7;
7425                 else
7426                         fan_control_desired_level = status;
7427         }
7428 }
7429
7430 static int fan_get_status(u8 *status)
7431 {
7432         u8 s;
7433
7434         /* TODO:
7435          * Add TPACPI_FAN_RD_ACPI_FANS ? */
7436
7437         switch (fan_status_access_mode) {
7438         case TPACPI_FAN_RD_ACPI_GFAN:
7439                 /* 570, 600e/x, 770e, 770x */
7440
7441                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
7442                         return -EIO;
7443
7444                 if (likely(status))
7445                         *status = s & 0x07;
7446
7447                 break;
7448
7449         case TPACPI_FAN_RD_TPEC:
7450                 /* all except 570, 600e/x, 770e, 770x */
7451                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
7452                         return -EIO;
7453
7454                 if (likely(status)) {
7455                         *status = s;
7456                         fan_quirk1_handle(status);
7457                 }
7458
7459                 break;
7460
7461         default:
7462                 return -ENXIO;
7463         }
7464
7465         return 0;
7466 }
7467
7468 static int fan_get_status_safe(u8 *status)
7469 {
7470         int rc;
7471         u8 s;
7472
7473         if (mutex_lock_killable(&fan_mutex))
7474                 return -ERESTARTSYS;
7475         rc = fan_get_status(&s);
7476         if (!rc)
7477                 fan_update_desired_level(s);
7478         mutex_unlock(&fan_mutex);
7479
7480         if (status)
7481                 *status = s;
7482
7483         return rc;
7484 }
7485
7486 static int fan_get_speed(unsigned int *speed)
7487 {
7488         u8 hi, lo;
7489
7490         switch (fan_status_access_mode) {
7491         case TPACPI_FAN_RD_TPEC:
7492                 /* all except 570, 600e/x, 770e, 770x */
7493                 if (unlikely(!fan_select_fan1()))
7494                         return -EIO;
7495                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
7496                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
7497                         return -EIO;
7498
7499                 if (likely(speed))
7500                         *speed = (hi << 8) | lo;
7501
7502                 break;
7503
7504         default:
7505                 return -ENXIO;
7506         }
7507
7508         return 0;
7509 }
7510
7511 static int fan2_get_speed(unsigned int *speed)
7512 {
7513         u8 hi, lo;
7514         bool rc;
7515
7516         switch (fan_status_access_mode) {
7517         case TPACPI_FAN_RD_TPEC:
7518                 /* all except 570, 600e/x, 770e, 770x */
7519                 if (unlikely(!fan_select_fan2()))
7520                         return -EIO;
7521                 rc = !acpi_ec_read(fan_rpm_offset, &lo) ||
7522                              !acpi_ec_read(fan_rpm_offset + 1, &hi);
7523                 fan_select_fan1(); /* play it safe */
7524                 if (rc)
7525                         return -EIO;
7526
7527                 if (likely(speed))
7528                         *speed = (hi << 8) | lo;
7529
7530                 break;
7531
7532         default:
7533                 return -ENXIO;
7534         }
7535
7536         return 0;
7537 }
7538
7539 static int fan_set_level(int level)
7540 {
7541         if (!fan_control_allowed)
7542                 return -EPERM;
7543
7544         switch (fan_control_access_mode) {
7545         case TPACPI_FAN_WR_ACPI_SFAN:
7546                 if (level >= 0 && level <= 7) {
7547                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
7548                                 return -EIO;
7549                 } else
7550                         return -EINVAL;
7551                 break;
7552
7553         case TPACPI_FAN_WR_ACPI_FANS:
7554         case TPACPI_FAN_WR_TPEC:
7555                 if (!(level & TP_EC_FAN_AUTO) &&
7556                     !(level & TP_EC_FAN_FULLSPEED) &&
7557                     ((level < 0) || (level > 7)))
7558                         return -EINVAL;
7559
7560                 /* safety net should the EC not support AUTO
7561                  * or FULLSPEED mode bits and just ignore them */
7562                 if (level & TP_EC_FAN_FULLSPEED)
7563                         level |= 7;     /* safety min speed 7 */
7564                 else if (level & TP_EC_FAN_AUTO)
7565                         level |= 4;     /* safety min speed 4 */
7566
7567                 if (!acpi_ec_write(fan_status_offset, level))
7568                         return -EIO;
7569                 else
7570                         tp_features.fan_ctrl_status_undef = 0;
7571                 break;
7572
7573         default:
7574                 return -ENXIO;
7575         }
7576
7577         vdbg_printk(TPACPI_DBG_FAN,
7578                 "fan control: set fan control register to 0x%02x\n", level);
7579         return 0;
7580 }
7581
7582 static int fan_set_level_safe(int level)
7583 {
7584         int rc;
7585
7586         if (!fan_control_allowed)
7587                 return -EPERM;
7588
7589         if (mutex_lock_killable(&fan_mutex))
7590                 return -ERESTARTSYS;
7591
7592         if (level == TPACPI_FAN_LAST_LEVEL)
7593                 level = fan_control_desired_level;
7594
7595         rc = fan_set_level(level);
7596         if (!rc)
7597                 fan_update_desired_level(level);
7598
7599         mutex_unlock(&fan_mutex);
7600         return rc;
7601 }
7602
7603 static int fan_set_enable(void)
7604 {
7605         u8 s;
7606         int rc;
7607
7608         if (!fan_control_allowed)
7609                 return -EPERM;
7610
7611         if (mutex_lock_killable(&fan_mutex))
7612                 return -ERESTARTSYS;
7613
7614         switch (fan_control_access_mode) {
7615         case TPACPI_FAN_WR_ACPI_FANS:
7616         case TPACPI_FAN_WR_TPEC:
7617                 rc = fan_get_status(&s);
7618                 if (rc < 0)
7619                         break;
7620
7621                 /* Don't go out of emergency fan mode */
7622                 if (s != 7) {
7623                         s &= 0x07;
7624                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
7625                 }
7626
7627                 if (!acpi_ec_write(fan_status_offset, s))
7628                         rc = -EIO;
7629                 else {
7630                         tp_features.fan_ctrl_status_undef = 0;
7631                         rc = 0;
7632                 }
7633                 break;
7634
7635         case TPACPI_FAN_WR_ACPI_SFAN:
7636                 rc = fan_get_status(&s);
7637                 if (rc < 0)
7638                         break;
7639
7640                 s &= 0x07;
7641
7642                 /* Set fan to at least level 4 */
7643                 s |= 4;
7644
7645                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
7646                         rc = -EIO;
7647                 else
7648                         rc = 0;
7649                 break;
7650
7651         default:
7652                 rc = -ENXIO;
7653         }
7654
7655         mutex_unlock(&fan_mutex);
7656
7657         if (!rc)
7658                 vdbg_printk(TPACPI_DBG_FAN,
7659                         "fan control: set fan control register to 0x%02x\n",
7660                         s);
7661         return rc;
7662 }
7663
7664 static int fan_set_disable(void)
7665 {
7666         int rc;
7667
7668         if (!fan_control_allowed)
7669                 return -EPERM;
7670
7671         if (mutex_lock_killable(&fan_mutex))
7672                 return -ERESTARTSYS;
7673
7674         rc = 0;
7675         switch (fan_control_access_mode) {
7676         case TPACPI_FAN_WR_ACPI_FANS:
7677         case TPACPI_FAN_WR_TPEC:
7678                 if (!acpi_ec_write(fan_status_offset, 0x00))
7679                         rc = -EIO;
7680                 else {
7681                         fan_control_desired_level = 0;
7682                         tp_features.fan_ctrl_status_undef = 0;
7683                 }
7684                 break;
7685
7686         case TPACPI_FAN_WR_ACPI_SFAN:
7687                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
7688                         rc = -EIO;
7689                 else
7690                         fan_control_desired_level = 0;
7691                 break;
7692
7693         default:
7694                 rc = -ENXIO;
7695         }
7696
7697         if (!rc)
7698                 vdbg_printk(TPACPI_DBG_FAN,
7699                         "fan control: set fan control register to 0\n");
7700
7701         mutex_unlock(&fan_mutex);
7702         return rc;
7703 }
7704
7705 static int fan_set_speed(int speed)
7706 {
7707         int rc;
7708
7709         if (!fan_control_allowed)
7710                 return -EPERM;
7711
7712         if (mutex_lock_killable(&fan_mutex))
7713                 return -ERESTARTSYS;
7714
7715         rc = 0;
7716         switch (fan_control_access_mode) {
7717         case TPACPI_FAN_WR_ACPI_FANS:
7718                 if (speed >= 0 && speed <= 65535) {
7719                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
7720                                         speed, speed, speed))
7721                                 rc = -EIO;
7722                 } else
7723                         rc = -EINVAL;
7724                 break;
7725
7726         default:
7727                 rc = -ENXIO;
7728         }
7729
7730         mutex_unlock(&fan_mutex);
7731         return rc;
7732 }
7733
7734 static void fan_watchdog_reset(void)
7735 {
7736         static int fan_watchdog_active;
7737
7738         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
7739                 return;
7740
7741         if (fan_watchdog_active)
7742                 cancel_delayed_work(&fan_watchdog_task);
7743
7744         if (fan_watchdog_maxinterval > 0 &&
7745             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
7746                 fan_watchdog_active = 1;
7747                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
7748                                 msecs_to_jiffies(fan_watchdog_maxinterval
7749                                                  * 1000))) {
7750                         printk(TPACPI_ERR
7751                                "failed to queue the fan watchdog, "
7752                                "watchdog will not trigger\n");
7753                 }
7754         } else
7755                 fan_watchdog_active = 0;
7756 }
7757
7758 static void fan_watchdog_fire(struct work_struct *ignored)
7759 {
7760         int rc;
7761
7762         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
7763                 return;
7764
7765         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
7766         rc = fan_set_enable();
7767         if (rc < 0) {
7768                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
7769                         "will try again later...\n", -rc);
7770                 /* reschedule for later */
7771                 fan_watchdog_reset();
7772         }
7773 }
7774
7775 /*
7776  * SYSFS fan layout: hwmon compatible (device)
7777  *
7778  * pwm*_enable:
7779  *      0: "disengaged" mode
7780  *      1: manual mode
7781  *      2: native EC "auto" mode (recommended, hardware default)
7782  *
7783  * pwm*: set speed in manual mode, ignored otherwise.
7784  *      0 is level 0; 255 is level 7. Intermediate points done with linear
7785  *      interpolation.
7786  *
7787  * fan*_input: tachometer reading, RPM
7788  *
7789  *
7790  * SYSFS fan layout: extensions
7791  *
7792  * fan_watchdog (driver):
7793  *      fan watchdog interval in seconds, 0 disables (default), max 120
7794  */
7795
7796 /* sysfs fan pwm1_enable ----------------------------------------------- */
7797 static ssize_t fan_pwm1_enable_show(struct device *dev,
7798                                     struct device_attribute *attr,
7799                                     char *buf)
7800 {
7801         int res, mode;
7802         u8 status;
7803
7804         res = fan_get_status_safe(&status);
7805         if (res)
7806                 return res;
7807
7808         if (status & TP_EC_FAN_FULLSPEED) {
7809                 mode = 0;
7810         } else if (status & TP_EC_FAN_AUTO) {
7811                 mode = 2;
7812         } else
7813                 mode = 1;
7814
7815         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
7816 }
7817
7818 static ssize_t fan_pwm1_enable_store(struct device *dev,
7819                                      struct device_attribute *attr,
7820                                      const char *buf, size_t count)
7821 {
7822         unsigned long t;
7823         int res, level;
7824
7825         if (parse_strtoul(buf, 2, &t))
7826                 return -EINVAL;
7827
7828         tpacpi_disclose_usertask("hwmon pwm1_enable",
7829                         "set fan mode to %lu\n", t);
7830
7831         switch (t) {
7832         case 0:
7833                 level = TP_EC_FAN_FULLSPEED;
7834                 break;
7835         case 1:
7836                 level = TPACPI_FAN_LAST_LEVEL;
7837                 break;
7838         case 2:
7839                 level = TP_EC_FAN_AUTO;
7840                 break;
7841         case 3:
7842                 /* reserved for software-controlled auto mode */
7843                 return -ENOSYS;
7844         default:
7845                 return -EINVAL;
7846         }
7847
7848         res = fan_set_level_safe(level);
7849         if (res == -ENXIO)
7850                 return -EINVAL;
7851         else if (res < 0)
7852                 return res;
7853
7854         fan_watchdog_reset();
7855
7856         return count;
7857 }
7858
7859 static struct device_attribute dev_attr_fan_pwm1_enable =
7860         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
7861                 fan_pwm1_enable_show, fan_pwm1_enable_store);
7862
7863 /* sysfs fan pwm1 ------------------------------------------------------ */
7864 static ssize_t fan_pwm1_show(struct device *dev,
7865                              struct device_attribute *attr,
7866                              char *buf)
7867 {
7868         int res;
7869         u8 status;
7870
7871         res = fan_get_status_safe(&status);
7872         if (res)
7873                 return res;
7874
7875         if ((status &
7876              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
7877                 status = fan_control_desired_level;
7878
7879         if (status > 7)
7880                 status = 7;
7881
7882         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
7883 }
7884
7885 static ssize_t fan_pwm1_store(struct device *dev,
7886                               struct device_attribute *attr,
7887                               const char *buf, size_t count)
7888 {
7889         unsigned long s;
7890         int rc;
7891         u8 status, newlevel;
7892
7893         if (parse_strtoul(buf, 255, &s))
7894                 return -EINVAL;
7895
7896         tpacpi_disclose_usertask("hwmon pwm1",
7897                         "set fan speed to %lu\n", s);
7898
7899         /* scale down from 0-255 to 0-7 */
7900         newlevel = (s >> 5) & 0x07;
7901
7902         if (mutex_lock_killable(&fan_mutex))
7903                 return -ERESTARTSYS;
7904
7905         rc = fan_get_status(&status);
7906         if (!rc && (status &
7907                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
7908                 rc = fan_set_level(newlevel);
7909                 if (rc == -ENXIO)
7910                         rc = -EINVAL;
7911                 else if (!rc) {
7912                         fan_update_desired_level(newlevel);
7913                         fan_watchdog_reset();
7914                 }
7915         }
7916
7917         mutex_unlock(&fan_mutex);
7918         return (rc)? rc : count;
7919 }
7920
7921 static struct device_attribute dev_attr_fan_pwm1 =
7922         __ATTR(pwm1, S_IWUSR | S_IRUGO,
7923                 fan_pwm1_show, fan_pwm1_store);
7924
7925 /* sysfs fan fan1_input ------------------------------------------------ */
7926 static ssize_t fan_fan1_input_show(struct device *dev,
7927                            struct device_attribute *attr,
7928                            char *buf)
7929 {
7930         int res;
7931         unsigned int speed;
7932
7933         res = fan_get_speed(&speed);
7934         if (res < 0)
7935                 return res;
7936
7937         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7938 }
7939
7940 static struct device_attribute dev_attr_fan_fan1_input =
7941         __ATTR(fan1_input, S_IRUGO,
7942                 fan_fan1_input_show, NULL);
7943
7944 /* sysfs fan fan2_input ------------------------------------------------ */
7945 static ssize_t fan_fan2_input_show(struct device *dev,
7946                            struct device_attribute *attr,
7947                            char *buf)
7948 {
7949         int res;
7950         unsigned int speed;
7951
7952         res = fan2_get_speed(&speed);
7953         if (res < 0)
7954                 return res;
7955
7956         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7957 }
7958
7959 static struct device_attribute dev_attr_fan_fan2_input =
7960         __ATTR(fan2_input, S_IRUGO,
7961                 fan_fan2_input_show, NULL);
7962
7963 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
7964 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
7965                                      char *buf)
7966 {
7967         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
7968 }
7969
7970 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
7971                                       const char *buf, size_t count)
7972 {
7973         unsigned long t;
7974
7975         if (parse_strtoul(buf, 120, &t))
7976                 return -EINVAL;
7977
7978         if (!fan_control_allowed)
7979                 return -EPERM;
7980
7981         fan_watchdog_maxinterval = t;
7982         fan_watchdog_reset();
7983
7984         tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t);
7985
7986         return count;
7987 }
7988
7989 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
7990                 fan_fan_watchdog_show, fan_fan_watchdog_store);
7991
7992 /* --------------------------------------------------------------------- */
7993 static struct attribute *fan_attributes[] = {
7994         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
7995         &dev_attr_fan_fan1_input.attr,
7996         NULL, /* for fan2_input */
7997         NULL
7998 };
7999
8000 static const struct attribute_group fan_attr_group = {
8001         .attrs = fan_attributes,
8002 };
8003
8004 #define TPACPI_FAN_Q1   0x0001          /* Unitialized HFSP */
8005 #define TPACPI_FAN_2FAN 0x0002          /* EC 0x31 bit 0 selects fan2 */
8006
8007 #define TPACPI_FAN_QI(__id1, __id2, __quirks)   \
8008         { .vendor = PCI_VENDOR_ID_IBM,          \
8009           .bios = TPACPI_MATCH_ANY,             \
8010           .ec = TPID(__id1, __id2),             \
8011           .quirks = __quirks }
8012
8013 #define TPACPI_FAN_QL(__id1, __id2, __quirks)   \
8014         { .vendor = PCI_VENDOR_ID_LENOVO,       \
8015           .bios = TPACPI_MATCH_ANY,             \
8016           .ec = TPID(__id1, __id2),             \
8017           .quirks = __quirks }
8018
8019 static const struct tpacpi_quirk fan_quirk_table[] __initconst = {
8020         TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1),
8021         TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1),
8022         TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1),
8023         TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1),
8024         TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN),
8025 };
8026
8027 #undef TPACPI_FAN_QL
8028 #undef TPACPI_FAN_QI
8029
8030 static int __init fan_init(struct ibm_init_struct *iibm)
8031 {
8032         int rc;
8033         unsigned long quirks;
8034
8035         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8036                         "initializing fan subdriver\n");
8037
8038         mutex_init(&fan_mutex);
8039         fan_status_access_mode = TPACPI_FAN_NONE;
8040         fan_control_access_mode = TPACPI_FAN_WR_NONE;
8041         fan_control_commands = 0;
8042         fan_watchdog_maxinterval = 0;
8043         tp_features.fan_ctrl_status_undef = 0;
8044         tp_features.second_fan = 0;
8045         fan_control_desired_level = 7;
8046
8047         if (tpacpi_is_ibm()) {
8048                 TPACPI_ACPIHANDLE_INIT(fans);
8049                 TPACPI_ACPIHANDLE_INIT(gfan);
8050                 TPACPI_ACPIHANDLE_INIT(sfan);
8051         }
8052
8053         quirks = tpacpi_check_quirks(fan_quirk_table,
8054                                      ARRAY_SIZE(fan_quirk_table));
8055
8056         if (gfan_handle) {
8057                 /* 570, 600e/x, 770e, 770x */
8058                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
8059         } else {
8060                 /* all other ThinkPads: note that even old-style
8061                  * ThinkPad ECs supports the fan control register */
8062                 if (likely(acpi_ec_read(fan_status_offset,
8063                                         &fan_control_initial_status))) {
8064                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
8065                         if (quirks & TPACPI_FAN_Q1)
8066                                 fan_quirk1_setup();
8067                         if (quirks & TPACPI_FAN_2FAN) {
8068                                 tp_features.second_fan = 1;
8069                                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8070                                         "secondary fan support enabled\n");
8071                         }
8072                 } else {
8073                         printk(TPACPI_ERR
8074                                "ThinkPad ACPI EC access misbehaving, "
8075                                "fan status and control unavailable\n");
8076                         return 1;
8077                 }
8078         }
8079
8080         if (sfan_handle) {
8081                 /* 570, 770x-JL */
8082                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
8083                 fan_control_commands |=
8084                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
8085         } else {
8086                 if (!gfan_handle) {
8087                         /* gfan without sfan means no fan control */
8088                         /* all other models implement TP EC 0x2f control */
8089
8090                         if (fans_handle) {
8091                                 /* X31, X40, X41 */
8092                                 fan_control_access_mode =
8093                                     TPACPI_FAN_WR_ACPI_FANS;
8094                                 fan_control_commands |=
8095                                     TPACPI_FAN_CMD_SPEED |
8096                                     TPACPI_FAN_CMD_LEVEL |
8097                                     TPACPI_FAN_CMD_ENABLE;
8098                         } else {
8099                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
8100                                 fan_control_commands |=
8101                                     TPACPI_FAN_CMD_LEVEL |
8102                                     TPACPI_FAN_CMD_ENABLE;
8103                         }
8104                 }
8105         }
8106
8107         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8108                 "fan is %s, modes %d, %d\n",
8109                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
8110                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
8111                 fan_status_access_mode, fan_control_access_mode);
8112
8113         /* fan control master switch */
8114         if (!fan_control_allowed) {
8115                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
8116                 fan_control_commands = 0;
8117                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8118                            "fan control features disabled by parameter\n");
8119         }
8120
8121         /* update fan_control_desired_level */
8122         if (fan_status_access_mode != TPACPI_FAN_NONE)
8123                 fan_get_status_safe(NULL);
8124
8125         if (fan_status_access_mode != TPACPI_FAN_NONE ||
8126             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
8127                 if (tp_features.second_fan) {
8128                         /* attach second fan tachometer */
8129                         fan_attributes[ARRAY_SIZE(fan_attributes)-2] =
8130                                         &dev_attr_fan_fan2_input.attr;
8131                 }
8132                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
8133                                          &fan_attr_group);
8134                 if (rc < 0)
8135                         return rc;
8136
8137                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
8138                                         &driver_attr_fan_watchdog);
8139                 if (rc < 0) {
8140                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
8141                                         &fan_attr_group);
8142                         return rc;
8143                 }
8144                 return 0;
8145         } else
8146                 return 1;
8147 }
8148
8149 static void fan_exit(void)
8150 {
8151         vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN,
8152                     "cancelling any pending fan watchdog tasks\n");
8153
8154         /* FIXME: can we really do this unconditionally? */
8155         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
8156         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
8157                            &driver_attr_fan_watchdog);
8158
8159         cancel_delayed_work(&fan_watchdog_task);
8160         flush_workqueue(tpacpi_wq);
8161 }
8162
8163 static void fan_suspend(pm_message_t state)
8164 {
8165         int rc;
8166
8167         if (!fan_control_allowed)
8168                 return;
8169
8170         /* Store fan status in cache */
8171         fan_control_resume_level = 0;
8172         rc = fan_get_status_safe(&fan_control_resume_level);
8173         if (rc < 0)
8174                 printk(TPACPI_NOTICE
8175                         "failed to read fan level for later "
8176                         "restore during resume: %d\n", rc);
8177
8178         /* if it is undefined, don't attempt to restore it.
8179          * KEEP THIS LAST */
8180         if (tp_features.fan_ctrl_status_undef)
8181                 fan_control_resume_level = 0;
8182 }
8183
8184 static void fan_resume(void)
8185 {
8186         u8 current_level = 7;
8187         bool do_set = false;
8188         int rc;
8189
8190         /* DSDT *always* updates status on resume */
8191         tp_features.fan_ctrl_status_undef = 0;
8192
8193         if (!fan_control_allowed ||
8194             !fan_control_resume_level ||
8195             (fan_get_status_safe(&current_level) < 0))
8196                 return;
8197
8198         switch (fan_control_access_mode) {
8199         case TPACPI_FAN_WR_ACPI_SFAN:
8200                 /* never decrease fan level */
8201                 do_set = (fan_control_resume_level > current_level);
8202                 break;
8203         case TPACPI_FAN_WR_ACPI_FANS:
8204         case TPACPI_FAN_WR_TPEC:
8205                 /* never decrease fan level, scale is:
8206                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
8207                  *
8208                  * We expect the firmware to set either 7 or AUTO, but we
8209                  * handle FULLSPEED out of paranoia.
8210                  *
8211                  * So, we can safely only restore FULLSPEED or 7, anything
8212                  * else could slow the fan.  Restoring AUTO is useless, at
8213                  * best that's exactly what the DSDT already set (it is the
8214                  * slower it uses).
8215                  *
8216                  * Always keep in mind that the DSDT *will* have set the
8217                  * fans to what the vendor supposes is the best level.  We
8218                  * muck with it only to speed the fan up.
8219                  */
8220                 if (fan_control_resume_level != 7 &&
8221                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
8222                         return;
8223                 else
8224                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
8225                                  (current_level != fan_control_resume_level);
8226                 break;
8227         default:
8228                 return;
8229         }
8230         if (do_set) {
8231                 printk(TPACPI_NOTICE
8232                         "restoring fan level to 0x%02x\n",
8233                         fan_control_resume_level);
8234                 rc = fan_set_level_safe(fan_control_resume_level);
8235                 if (rc < 0)
8236                         printk(TPACPI_NOTICE
8237                                 "failed to restore fan level: %d\n", rc);
8238         }
8239 }
8240
8241 static int fan_read(struct seq_file *m)
8242 {
8243         int rc;
8244         u8 status;
8245         unsigned int speed = 0;
8246
8247         switch (fan_status_access_mode) {
8248         case TPACPI_FAN_RD_ACPI_GFAN:
8249                 /* 570, 600e/x, 770e, 770x */
8250                 rc = fan_get_status_safe(&status);
8251                 if (rc < 0)
8252                         return rc;
8253
8254                 seq_printf(m, "status:\t\t%s\n"
8255                                "level:\t\t%d\n",
8256                                (status != 0) ? "enabled" : "disabled", status);
8257                 break;
8258
8259         case TPACPI_FAN_RD_TPEC:
8260                 /* all except 570, 600e/x, 770e, 770x */
8261                 rc = fan_get_status_safe(&status);
8262                 if (rc < 0)
8263                         return rc;
8264
8265                 seq_printf(m, "status:\t\t%s\n",
8266                                (status != 0) ? "enabled" : "disabled");
8267
8268                 rc = fan_get_speed(&speed);
8269                 if (rc < 0)
8270                         return rc;
8271
8272                 seq_printf(m, "speed:\t\t%d\n", speed);
8273
8274                 if (status & TP_EC_FAN_FULLSPEED)
8275                         /* Disengaged mode takes precedence */
8276                         seq_printf(m, "level:\t\tdisengaged\n");
8277                 else if (status & TP_EC_FAN_AUTO)
8278                         seq_printf(m, "level:\t\tauto\n");
8279                 else
8280                         seq_printf(m, "level:\t\t%d\n", status);
8281                 break;
8282
8283         case TPACPI_FAN_NONE:
8284         default:
8285                 seq_printf(m, "status:\t\tnot supported\n");
8286         }
8287
8288         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
8289                 seq_printf(m, "commands:\tlevel <level>");
8290
8291                 switch (fan_control_access_mode) {
8292                 case TPACPI_FAN_WR_ACPI_SFAN:
8293                         seq_printf(m, " (<level> is 0-7)\n");
8294                         break;
8295
8296                 default:
8297                         seq_printf(m, " (<level> is 0-7, "
8298                                        "auto, disengaged, full-speed)\n");
8299                         break;
8300                 }
8301         }
8302
8303         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
8304                 seq_printf(m, "commands:\tenable, disable\n"
8305                                "commands:\twatchdog <timeout> (<timeout> "
8306                                "is 0 (off), 1-120 (seconds))\n");
8307
8308         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
8309                 seq_printf(m, "commands:\tspeed <speed>"
8310                                " (<speed> is 0-65535)\n");
8311
8312         return 0;
8313 }
8314
8315 static int fan_write_cmd_level(const char *cmd, int *rc)
8316 {
8317         int level;
8318
8319         if (strlencmp(cmd, "level auto") == 0)
8320                 level = TP_EC_FAN_AUTO;
8321         else if ((strlencmp(cmd, "level disengaged") == 0) |
8322                         (strlencmp(cmd, "level full-speed") == 0))
8323                 level = TP_EC_FAN_FULLSPEED;
8324         else if (sscanf(cmd, "level %d", &level) != 1)
8325                 return 0;
8326
8327         *rc = fan_set_level_safe(level);
8328         if (*rc == -ENXIO)
8329                 printk(TPACPI_ERR "level command accepted for unsupported "
8330                        "access mode %d", fan_control_access_mode);
8331         else if (!*rc)
8332                 tpacpi_disclose_usertask("procfs fan",
8333                         "set level to %d\n", level);
8334
8335         return 1;
8336 }
8337
8338 static int fan_write_cmd_enable(const char *cmd, int *rc)
8339 {
8340         if (strlencmp(cmd, "enable") != 0)
8341                 return 0;
8342
8343         *rc = fan_set_enable();
8344         if (*rc == -ENXIO)
8345                 printk(TPACPI_ERR "enable command accepted for unsupported "
8346                        "access mode %d", fan_control_access_mode);
8347         else if (!*rc)
8348                 tpacpi_disclose_usertask("procfs fan", "enable\n");
8349
8350         return 1;
8351 }
8352
8353 static int fan_write_cmd_disable(const char *cmd, int *rc)
8354 {
8355         if (strlencmp(cmd, "disable") != 0)
8356                 return 0;
8357
8358         *rc = fan_set_disable();
8359         if (*rc == -ENXIO)
8360                 printk(TPACPI_ERR "disable command accepted for unsupported "
8361                        "access mode %d", fan_control_access_mode);
8362         else if (!*rc)
8363                 tpacpi_disclose_usertask("procfs fan", "disable\n");
8364
8365         return 1;
8366 }
8367
8368 static int fan_write_cmd_speed(const char *cmd, int *rc)
8369 {
8370         int speed;
8371
8372         /* TODO:
8373          * Support speed <low> <medium> <high> ? */
8374
8375         if (sscanf(cmd, "speed %d", &speed) != 1)
8376                 return 0;
8377
8378         *rc = fan_set_speed(speed);
8379         if (*rc == -ENXIO)
8380                 printk(TPACPI_ERR "speed command accepted for unsupported "
8381                        "access mode %d", fan_control_access_mode);
8382         else if (!*rc)
8383                 tpacpi_disclose_usertask("procfs fan",
8384                         "set speed to %d\n", speed);
8385
8386         return 1;
8387 }
8388
8389 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
8390 {
8391         int interval;
8392
8393         if (sscanf(cmd, "watchdog %d", &interval) != 1)
8394                 return 0;
8395
8396         if (interval < 0 || interval > 120)
8397                 *rc = -EINVAL;
8398         else {
8399                 fan_watchdog_maxinterval = interval;
8400                 tpacpi_disclose_usertask("procfs fan",
8401                         "set watchdog timer to %d\n",
8402                         interval);
8403         }
8404
8405         return 1;
8406 }
8407
8408 static int fan_write(char *buf)
8409 {
8410         char *cmd;
8411         int rc = 0;
8412
8413         while (!rc && (cmd = next_cmd(&buf))) {
8414                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
8415                       fan_write_cmd_level(cmd, &rc)) &&
8416                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
8417                       (fan_write_cmd_enable(cmd, &rc) ||
8418                        fan_write_cmd_disable(cmd, &rc) ||
8419                        fan_write_cmd_watchdog(cmd, &rc))) &&
8420                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
8421                       fan_write_cmd_speed(cmd, &rc))
8422                     )
8423                         rc = -EINVAL;
8424                 else if (!rc)
8425                         fan_watchdog_reset();
8426         }
8427
8428         return rc;
8429 }
8430
8431 static struct ibm_struct fan_driver_data = {
8432         .name = "fan",
8433         .read = fan_read,
8434         .write = fan_write,
8435         .exit = fan_exit,
8436         .suspend = fan_suspend,
8437         .resume = fan_resume,
8438 };
8439
8440 /****************************************************************************
8441  ****************************************************************************
8442  *
8443  * Infrastructure
8444  *
8445  ****************************************************************************
8446  ****************************************************************************/
8447
8448 /*
8449  * HKEY event callout for other subdrivers go here
8450  * (yes, it is ugly, but it is quick, safe, and gets the job done
8451  */
8452 static void tpacpi_driver_event(const unsigned int hkey_event)
8453 {
8454         if (ibm_backlight_device) {
8455                 switch (hkey_event) {
8456                 case TP_HKEY_EV_BRGHT_UP:
8457                 case TP_HKEY_EV_BRGHT_DOWN:
8458                         tpacpi_brightness_notify_change();
8459                 }
8460         }
8461         if (alsa_card) {
8462                 switch (hkey_event) {
8463                 case TP_HKEY_EV_VOL_UP:
8464                 case TP_HKEY_EV_VOL_DOWN:
8465                 case TP_HKEY_EV_VOL_MUTE:
8466                         volume_alsa_notify_change();
8467                 }
8468         }
8469 }
8470
8471 static void hotkey_driver_event(const unsigned int scancode)
8472 {
8473         tpacpi_driver_event(TP_HKEY_EV_HOTKEY_BASE + scancode);
8474 }
8475
8476 /* sysfs name ---------------------------------------------------------- */
8477 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
8478                            struct device_attribute *attr,
8479                            char *buf)
8480 {
8481         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
8482 }
8483
8484 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
8485         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
8486
8487 /* --------------------------------------------------------------------- */
8488
8489 /* /proc support */
8490 static struct proc_dir_entry *proc_dir;
8491
8492 /*
8493  * Module and infrastructure proble, init and exit handling
8494  */
8495
8496 static int force_load;
8497
8498 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
8499 static const char * __init str_supported(int is_supported)
8500 {
8501         static char text_unsupported[] __initdata = "not supported";
8502
8503         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
8504 }
8505 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
8506
8507 static void ibm_exit(struct ibm_struct *ibm)
8508 {
8509         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
8510
8511         list_del_init(&ibm->all_drivers);
8512
8513         if (ibm->flags.acpi_notify_installed) {
8514                 dbg_printk(TPACPI_DBG_EXIT,
8515                         "%s: acpi_remove_notify_handler\n", ibm->name);
8516                 BUG_ON(!ibm->acpi);
8517                 acpi_remove_notify_handler(*ibm->acpi->handle,
8518                                            ibm->acpi->type,
8519                                            dispatch_acpi_notify);
8520                 ibm->flags.acpi_notify_installed = 0;
8521                 ibm->flags.acpi_notify_installed = 0;
8522         }
8523
8524         if (ibm->flags.proc_created) {
8525                 dbg_printk(TPACPI_DBG_EXIT,
8526                         "%s: remove_proc_entry\n", ibm->name);
8527                 remove_proc_entry(ibm->name, proc_dir);
8528                 ibm->flags.proc_created = 0;
8529         }
8530
8531         if (ibm->flags.acpi_driver_registered) {
8532                 dbg_printk(TPACPI_DBG_EXIT,
8533                         "%s: acpi_bus_unregister_driver\n", ibm->name);
8534                 BUG_ON(!ibm->acpi);
8535                 acpi_bus_unregister_driver(ibm->acpi->driver);
8536                 kfree(ibm->acpi->driver);
8537                 ibm->acpi->driver = NULL;
8538                 ibm->flags.acpi_driver_registered = 0;
8539         }
8540
8541         if (ibm->flags.init_called && ibm->exit) {
8542                 ibm->exit();
8543                 ibm->flags.init_called = 0;
8544         }
8545
8546         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
8547 }
8548
8549 static int __init ibm_init(struct ibm_init_struct *iibm)
8550 {
8551         int ret;
8552         struct ibm_struct *ibm = iibm->data;
8553         struct proc_dir_entry *entry;
8554
8555         BUG_ON(ibm == NULL);
8556
8557         INIT_LIST_HEAD(&ibm->all_drivers);
8558
8559         if (ibm->flags.experimental && !experimental)
8560                 return 0;
8561
8562         dbg_printk(TPACPI_DBG_INIT,
8563                 "probing for %s\n", ibm->name);
8564
8565         if (iibm->init) {
8566                 ret = iibm->init(iibm);
8567                 if (ret > 0)
8568                         return 0;       /* probe failed */
8569                 if (ret)
8570                         return ret;
8571
8572                 ibm->flags.init_called = 1;
8573         }
8574
8575         if (ibm->acpi) {
8576                 if (ibm->acpi->hid) {
8577                         ret = register_tpacpi_subdriver(ibm);
8578                         if (ret)
8579                                 goto err_out;
8580                 }
8581
8582                 if (ibm->acpi->notify) {
8583                         ret = setup_acpi_notify(ibm);
8584                         if (ret == -ENODEV) {
8585                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
8586                                         ibm->name);
8587                                 ret = 0;
8588                                 goto err_out;
8589                         }
8590                         if (ret < 0)
8591                                 goto err_out;
8592                 }
8593         }
8594
8595         dbg_printk(TPACPI_DBG_INIT,
8596                 "%s installed\n", ibm->name);
8597
8598         if (ibm->read) {
8599                 mode_t mode = iibm->base_procfs_mode;
8600
8601                 if (!mode)
8602                         mode = S_IRUGO;
8603                 if (ibm->write)
8604                         mode |= S_IWUSR;
8605                 entry = proc_create_data(ibm->name, mode, proc_dir,
8606                                          &dispatch_proc_fops, ibm);
8607                 if (!entry) {
8608                         printk(TPACPI_ERR "unable to create proc entry %s\n",
8609                                ibm->name);
8610                         ret = -ENODEV;
8611                         goto err_out;
8612                 }
8613                 ibm->flags.proc_created = 1;
8614         }
8615
8616         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
8617
8618         return 0;
8619
8620 err_out:
8621         dbg_printk(TPACPI_DBG_INIT,
8622                 "%s: at error exit path with result %d\n",
8623                 ibm->name, ret);
8624
8625         ibm_exit(ibm);
8626         return (ret < 0)? ret : 0;
8627 }
8628
8629 /* Probing */
8630
8631 static bool __pure __init tpacpi_is_fw_digit(const char c)
8632 {
8633         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z');
8634 }
8635
8636 /* Most models: xxyTkkWW (#.##c); Ancient 570/600 and -SL lacks (#.##c) */
8637 static bool __pure __init tpacpi_is_valid_fw_id(const char* const s,
8638                                                 const char t)
8639 {
8640         return s && strlen(s) >= 8 &&
8641                 tpacpi_is_fw_digit(s[0]) &&
8642                 tpacpi_is_fw_digit(s[1]) &&
8643                 s[2] == t && s[3] == 'T' &&
8644                 tpacpi_is_fw_digit(s[4]) &&
8645                 tpacpi_is_fw_digit(s[5]) &&
8646                 s[6] == 'W' && s[7] == 'W';
8647 }
8648
8649 /* returns 0 - probe ok, or < 0 - probe error.
8650  * Probe ok doesn't mean thinkpad found.
8651  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
8652 static int __must_check __init get_thinkpad_model_data(
8653                                                 struct thinkpad_id_data *tp)
8654 {
8655         const struct dmi_device *dev = NULL;
8656         char ec_fw_string[18];
8657         char const *s;
8658
8659         if (!tp)
8660                 return -EINVAL;
8661
8662         memset(tp, 0, sizeof(*tp));
8663
8664         if (dmi_name_in_vendors("IBM"))
8665                 tp->vendor = PCI_VENDOR_ID_IBM;
8666         else if (dmi_name_in_vendors("LENOVO"))
8667                 tp->vendor = PCI_VENDOR_ID_LENOVO;
8668         else
8669                 return 0;
8670
8671         s = dmi_get_system_info(DMI_BIOS_VERSION);
8672         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
8673         if (s && !tp->bios_version_str)
8674                 return -ENOMEM;
8675
8676         /* Really ancient ThinkPad 240X will fail this, which is fine */
8677         if (!tpacpi_is_valid_fw_id(tp->bios_version_str, 'E'))
8678                 return 0;
8679
8680         tp->bios_model = tp->bios_version_str[0]
8681                          | (tp->bios_version_str[1] << 8);
8682         tp->bios_release = (tp->bios_version_str[4] << 8)
8683                          | tp->bios_version_str[5];
8684
8685         /*
8686          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
8687          * X32 or newer, all Z series;  Some models must have an
8688          * up-to-date BIOS or they will not be detected.
8689          *
8690          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
8691          */
8692         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
8693                 if (sscanf(dev->name,
8694                            "IBM ThinkPad Embedded Controller -[%17c",
8695                            ec_fw_string) == 1) {
8696                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
8697                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
8698
8699                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
8700                         if (!tp->ec_version_str)
8701                                 return -ENOMEM;
8702
8703                         if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) {
8704                                 tp->ec_model = ec_fw_string[0]
8705                                                 | (ec_fw_string[1] << 8);
8706                                 tp->ec_release = (ec_fw_string[4] << 8)
8707                                                 | ec_fw_string[5];
8708                         } else {
8709                                 printk(TPACPI_NOTICE
8710                                         "ThinkPad firmware release %s "
8711                                         "doesn't match the known patterns\n",
8712                                         ec_fw_string);
8713                                 printk(TPACPI_NOTICE
8714                                         "please report this to %s\n",
8715                                         TPACPI_MAIL);
8716                         }
8717                         break;
8718                 }
8719         }
8720
8721         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
8722         if (s && !strnicmp(s, "ThinkPad", 8)) {
8723                 tp->model_str = kstrdup(s, GFP_KERNEL);
8724                 if (!tp->model_str)
8725                         return -ENOMEM;
8726         }
8727
8728         s = dmi_get_system_info(DMI_PRODUCT_NAME);
8729         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
8730         if (s && !tp->nummodel_str)
8731                 return -ENOMEM;
8732
8733         return 0;
8734 }
8735
8736 static int __init probe_for_thinkpad(void)
8737 {
8738         int is_thinkpad;
8739
8740         if (acpi_disabled)
8741                 return -ENODEV;
8742
8743         /* It would be dangerous to run the driver in this case */
8744         if (!tpacpi_is_ibm() && !tpacpi_is_lenovo())
8745                 return -ENODEV;
8746
8747         /*
8748          * Non-ancient models have better DMI tagging, but very old models
8749          * don't.  tpacpi_is_fw_known() is a cheat to help in that case.
8750          */
8751         is_thinkpad = (thinkpad_id.model_str != NULL) ||
8752                       (thinkpad_id.ec_model != 0) ||
8753                       tpacpi_is_fw_known();
8754
8755         /* ec is required because many other handles are relative to it */
8756         TPACPI_ACPIHANDLE_INIT(ec);
8757         if (!ec_handle) {
8758                 if (is_thinkpad)
8759                         printk(TPACPI_ERR
8760                                 "Not yet supported ThinkPad detected!\n");
8761                 return -ENODEV;
8762         }
8763
8764         if (!is_thinkpad && !force_load)
8765                 return -ENODEV;
8766
8767         return 0;
8768 }
8769
8770 static void __init thinkpad_acpi_init_banner(void)
8771 {
8772         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
8773         printk(TPACPI_INFO "%s\n", TPACPI_URL);
8774
8775         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
8776                 (thinkpad_id.bios_version_str) ?
8777                         thinkpad_id.bios_version_str : "unknown",
8778                 (thinkpad_id.ec_version_str) ?
8779                         thinkpad_id.ec_version_str : "unknown");
8780
8781         BUG_ON(!thinkpad_id.vendor);
8782
8783         if (thinkpad_id.model_str)
8784                 printk(TPACPI_INFO "%s %s, model %s\n",
8785                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
8786                                 "IBM" : ((thinkpad_id.vendor ==
8787                                                 PCI_VENDOR_ID_LENOVO) ?
8788                                         "Lenovo" : "Unknown vendor"),
8789                         thinkpad_id.model_str,
8790                         (thinkpad_id.nummodel_str) ?
8791                                 thinkpad_id.nummodel_str : "unknown");
8792 }
8793
8794 /* Module init, exit, parameters */
8795
8796 static struct ibm_init_struct ibms_init[] __initdata = {
8797         {
8798                 .data = &thinkpad_acpi_driver_data,
8799         },
8800         {
8801                 .init = hotkey_init,
8802                 .data = &hotkey_driver_data,
8803         },
8804         {
8805                 .init = bluetooth_init,
8806                 .data = &bluetooth_driver_data,
8807         },
8808         {
8809                 .init = wan_init,
8810                 .data = &wan_driver_data,
8811         },
8812         {
8813                 .init = uwb_init,
8814                 .data = &uwb_driver_data,
8815         },
8816 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
8817         {
8818                 .init = video_init,
8819                 .base_procfs_mode = S_IRUSR,
8820                 .data = &video_driver_data,
8821         },
8822 #endif
8823         {
8824                 .init = light_init,
8825                 .data = &light_driver_data,
8826         },
8827         {
8828                 .init = cmos_init,
8829                 .data = &cmos_driver_data,
8830         },
8831         {
8832                 .init = led_init,
8833                 .data = &led_driver_data,
8834         },
8835         {
8836                 .init = beep_init,
8837                 .data = &beep_driver_data,
8838         },
8839         {
8840                 .init = thermal_init,
8841                 .data = &thermal_driver_data,
8842         },
8843         {
8844                 .data = &ecdump_driver_data,
8845         },
8846         {
8847                 .init = brightness_init,
8848                 .data = &brightness_driver_data,
8849         },
8850         {
8851                 .init = volume_init,
8852                 .data = &volume_driver_data,
8853         },
8854         {
8855                 .init = fan_init,
8856                 .data = &fan_driver_data,
8857         },
8858 };
8859
8860 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
8861 {
8862         unsigned int i;
8863         struct ibm_struct *ibm;
8864
8865         if (!kp || !kp->name || !val)
8866                 return -EINVAL;
8867
8868         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
8869                 ibm = ibms_init[i].data;
8870                 WARN_ON(ibm == NULL);
8871
8872                 if (!ibm || !ibm->name)
8873                         continue;
8874
8875                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
8876                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
8877                                 return -ENOSPC;
8878                         strcpy(ibms_init[i].param, val);
8879                         strcat(ibms_init[i].param, ",");
8880                         return 0;
8881                 }
8882         }
8883
8884         return -EINVAL;
8885 }
8886
8887 module_param(experimental, int, 0444);
8888 MODULE_PARM_DESC(experimental,
8889                  "Enables experimental features when non-zero");
8890
8891 module_param_named(debug, dbg_level, uint, 0);
8892 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
8893
8894 module_param(force_load, bool, 0444);
8895 MODULE_PARM_DESC(force_load,
8896                  "Attempts to load the driver even on a "
8897                  "mis-identified ThinkPad when true");
8898
8899 module_param_named(fan_control, fan_control_allowed, bool, 0444);
8900 MODULE_PARM_DESC(fan_control,
8901                  "Enables setting fan parameters features when true");
8902
8903 module_param_named(brightness_mode, brightness_mode, uint, 0444);
8904 MODULE_PARM_DESC(brightness_mode,
8905                  "Selects brightness control strategy: "
8906                  "0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM");
8907
8908 module_param(brightness_enable, uint, 0444);
8909 MODULE_PARM_DESC(brightness_enable,
8910                  "Enables backlight control when 1, disables when 0");
8911
8912 module_param(hotkey_report_mode, uint, 0444);
8913 MODULE_PARM_DESC(hotkey_report_mode,
8914                  "used for backwards compatibility with userspace, "
8915                  "see documentation");
8916
8917 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
8918 module_param_named(volume_mode, volume_mode, uint, 0444);
8919 MODULE_PARM_DESC(volume_mode,
8920                  "Selects volume control strategy: "
8921                  "0=auto, 1=EC, 2=N/A, 3=EC+NVRAM");
8922
8923 module_param_named(volume_capabilities, volume_capabilities, uint, 0444);
8924 MODULE_PARM_DESC(volume_capabilities,
8925                  "Selects the mixer capabilites: "
8926                  "0=auto, 1=volume and mute, 2=mute only");
8927
8928 module_param_named(volume_control, volume_control_allowed, bool, 0444);
8929 MODULE_PARM_DESC(volume_control,
8930                  "Enables software override for the console audio "
8931                  "control when true");
8932
8933 /* ALSA module API parameters */
8934 module_param_named(index, alsa_index, int, 0444);
8935 MODULE_PARM_DESC(index, "ALSA index for the ACPI EC Mixer");
8936 module_param_named(id, alsa_id, charp, 0444);
8937 MODULE_PARM_DESC(id, "ALSA id for the ACPI EC Mixer");
8938 module_param_named(enable, alsa_enable, bool, 0444);
8939 MODULE_PARM_DESC(enable, "Enable the ALSA interface for the ACPI EC Mixer");
8940 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
8941
8942 #define TPACPI_PARAM(feature) \
8943         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
8944         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
8945                          "at module load, see documentation")
8946
8947 TPACPI_PARAM(hotkey);
8948 TPACPI_PARAM(bluetooth);
8949 TPACPI_PARAM(video);
8950 TPACPI_PARAM(light);
8951 TPACPI_PARAM(cmos);
8952 TPACPI_PARAM(led);
8953 TPACPI_PARAM(beep);
8954 TPACPI_PARAM(ecdump);
8955 TPACPI_PARAM(brightness);
8956 TPACPI_PARAM(volume);
8957 TPACPI_PARAM(fan);
8958
8959 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
8960 module_param(dbg_wlswemul, uint, 0444);
8961 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
8962 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
8963 MODULE_PARM_DESC(wlsw_state,
8964                  "Initial state of the emulated WLSW switch");
8965
8966 module_param(dbg_bluetoothemul, uint, 0444);
8967 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
8968 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
8969 MODULE_PARM_DESC(bluetooth_state,
8970                  "Initial state of the emulated bluetooth switch");
8971
8972 module_param(dbg_wwanemul, uint, 0444);
8973 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
8974 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
8975 MODULE_PARM_DESC(wwan_state,
8976                  "Initial state of the emulated WWAN switch");
8977
8978 module_param(dbg_uwbemul, uint, 0444);
8979 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
8980 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
8981 MODULE_PARM_DESC(uwb_state,
8982                  "Initial state of the emulated UWB switch");
8983 #endif
8984
8985 static void thinkpad_acpi_module_exit(void)
8986 {
8987         struct ibm_struct *ibm, *itmp;
8988
8989         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
8990
8991         list_for_each_entry_safe_reverse(ibm, itmp,
8992                                          &tpacpi_all_drivers,
8993                                          all_drivers) {
8994                 ibm_exit(ibm);
8995         }
8996
8997         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
8998
8999         if (tpacpi_inputdev) {
9000                 if (tp_features.input_device_registered)
9001                         input_unregister_device(tpacpi_inputdev);
9002                 else
9003                         input_free_device(tpacpi_inputdev);
9004         }
9005
9006         if (tpacpi_hwmon)
9007                 hwmon_device_unregister(tpacpi_hwmon);
9008
9009         if (tp_features.sensors_pdev_attrs_registered)
9010                 device_remove_file(&tpacpi_sensors_pdev->dev,
9011                                    &dev_attr_thinkpad_acpi_pdev_name);
9012         if (tpacpi_sensors_pdev)
9013                 platform_device_unregister(tpacpi_sensors_pdev);
9014         if (tpacpi_pdev)
9015                 platform_device_unregister(tpacpi_pdev);
9016
9017         if (tp_features.sensors_pdrv_attrs_registered)
9018                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
9019         if (tp_features.platform_drv_attrs_registered)
9020                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
9021
9022         if (tp_features.sensors_pdrv_registered)
9023                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
9024
9025         if (tp_features.platform_drv_registered)
9026                 platform_driver_unregister(&tpacpi_pdriver);
9027
9028         if (proc_dir)
9029                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
9030
9031         if (tpacpi_wq)
9032                 destroy_workqueue(tpacpi_wq);
9033
9034         kfree(thinkpad_id.bios_version_str);
9035         kfree(thinkpad_id.ec_version_str);
9036         kfree(thinkpad_id.model_str);
9037 }
9038
9039
9040 static int __init thinkpad_acpi_module_init(void)
9041 {
9042         int ret, i;
9043
9044         tpacpi_lifecycle = TPACPI_LIFE_INIT;
9045
9046         /* Parameter checking */
9047         if (hotkey_report_mode > 2)
9048                 return -EINVAL;
9049
9050         /* Driver-level probe */
9051
9052         ret = get_thinkpad_model_data(&thinkpad_id);
9053         if (ret) {
9054                 printk(TPACPI_ERR
9055                         "unable to get DMI data: %d\n", ret);
9056                 thinkpad_acpi_module_exit();
9057                 return ret;
9058         }
9059         ret = probe_for_thinkpad();
9060         if (ret) {
9061                 thinkpad_acpi_module_exit();
9062                 return ret;
9063         }
9064
9065         /* Driver initialization */
9066
9067         thinkpad_acpi_init_banner();
9068         tpacpi_check_outdated_fw();
9069
9070         TPACPI_ACPIHANDLE_INIT(ecrd);
9071         TPACPI_ACPIHANDLE_INIT(ecwr);
9072
9073         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
9074         if (!tpacpi_wq) {
9075                 thinkpad_acpi_module_exit();
9076                 return -ENOMEM;
9077         }
9078
9079         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
9080         if (!proc_dir) {
9081                 printk(TPACPI_ERR
9082                        "unable to create proc dir " TPACPI_PROC_DIR);
9083                 thinkpad_acpi_module_exit();
9084                 return -ENODEV;
9085         }
9086
9087         ret = platform_driver_register(&tpacpi_pdriver);
9088         if (ret) {
9089                 printk(TPACPI_ERR
9090                        "unable to register main platform driver\n");
9091                 thinkpad_acpi_module_exit();
9092                 return ret;
9093         }
9094         tp_features.platform_drv_registered = 1;
9095
9096         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
9097         if (ret) {
9098                 printk(TPACPI_ERR
9099                        "unable to register hwmon platform driver\n");
9100                 thinkpad_acpi_module_exit();
9101                 return ret;
9102         }
9103         tp_features.sensors_pdrv_registered = 1;
9104
9105         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
9106         if (!ret) {
9107                 tp_features.platform_drv_attrs_registered = 1;
9108                 ret = tpacpi_create_driver_attributes(
9109                                         &tpacpi_hwmon_pdriver.driver);
9110         }
9111         if (ret) {
9112                 printk(TPACPI_ERR
9113                        "unable to create sysfs driver attributes\n");
9114                 thinkpad_acpi_module_exit();
9115                 return ret;
9116         }
9117         tp_features.sensors_pdrv_attrs_registered = 1;
9118
9119
9120         /* Device initialization */
9121         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
9122                                                         NULL, 0);
9123         if (IS_ERR(tpacpi_pdev)) {
9124                 ret = PTR_ERR(tpacpi_pdev);
9125                 tpacpi_pdev = NULL;
9126                 printk(TPACPI_ERR "unable to register platform device\n");
9127                 thinkpad_acpi_module_exit();
9128                 return ret;
9129         }
9130         tpacpi_sensors_pdev = platform_device_register_simple(
9131                                                 TPACPI_HWMON_DRVR_NAME,
9132                                                 -1, NULL, 0);
9133         if (IS_ERR(tpacpi_sensors_pdev)) {
9134                 ret = PTR_ERR(tpacpi_sensors_pdev);
9135                 tpacpi_sensors_pdev = NULL;
9136                 printk(TPACPI_ERR
9137                        "unable to register hwmon platform device\n");
9138                 thinkpad_acpi_module_exit();
9139                 return ret;
9140         }
9141         ret = device_create_file(&tpacpi_sensors_pdev->dev,
9142                                  &dev_attr_thinkpad_acpi_pdev_name);
9143         if (ret) {
9144                 printk(TPACPI_ERR
9145                        "unable to create sysfs hwmon device attributes\n");
9146                 thinkpad_acpi_module_exit();
9147                 return ret;
9148         }
9149         tp_features.sensors_pdev_attrs_registered = 1;
9150         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
9151         if (IS_ERR(tpacpi_hwmon)) {
9152                 ret = PTR_ERR(tpacpi_hwmon);
9153                 tpacpi_hwmon = NULL;
9154                 printk(TPACPI_ERR "unable to register hwmon device\n");
9155                 thinkpad_acpi_module_exit();
9156                 return ret;
9157         }
9158         mutex_init(&tpacpi_inputdev_send_mutex);
9159         tpacpi_inputdev = input_allocate_device();
9160         if (!tpacpi_inputdev) {
9161                 printk(TPACPI_ERR "unable to allocate input device\n");
9162                 thinkpad_acpi_module_exit();
9163                 return -ENOMEM;
9164         } else {
9165                 /* Prepare input device, but don't register */
9166                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
9167                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
9168                 tpacpi_inputdev->id.bustype = BUS_HOST;
9169                 tpacpi_inputdev->id.vendor = thinkpad_id.vendor;
9170                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
9171                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
9172                 tpacpi_inputdev->dev.parent = &tpacpi_pdev->dev;
9173         }
9174
9175         /* Init subdriver dependencies */
9176         tpacpi_detect_brightness_capabilities();
9177
9178         /* Init subdrivers */
9179         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
9180                 ret = ibm_init(&ibms_init[i]);
9181                 if (ret >= 0 && *ibms_init[i].param)
9182                         ret = ibms_init[i].data->write(ibms_init[i].param);
9183                 if (ret < 0) {
9184                         thinkpad_acpi_module_exit();
9185                         return ret;
9186                 }
9187         }
9188
9189         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
9190
9191         ret = input_register_device(tpacpi_inputdev);
9192         if (ret < 0) {
9193                 printk(TPACPI_ERR "unable to register input device\n");
9194                 thinkpad_acpi_module_exit();
9195                 return ret;
9196         } else {
9197                 tp_features.input_device_registered = 1;
9198         }
9199
9200         return 0;
9201 }
9202
9203 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
9204
9205 /*
9206  * This will autoload the driver in almost every ThinkPad
9207  * in widespread use.
9208  *
9209  * Only _VERY_ old models, like the 240, 240x and 570 lack
9210  * the HKEY event interface.
9211  */
9212 MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids);
9213
9214 /*
9215  * DMI matching for module autoloading
9216  *
9217  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
9218  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
9219  *
9220  * Only models listed in thinkwiki will be supported, so add yours
9221  * if it is not there yet.
9222  */
9223 #define IBM_BIOS_MODULE_ALIAS(__type) \
9224         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*")
9225
9226 /* Ancient thinkpad BIOSes have to be identified by
9227  * BIOS type or model number, and there are far less
9228  * BIOS types than model numbers... */
9229 IBM_BIOS_MODULE_ALIAS("I[MU]");         /* 570, 570e */
9230
9231 MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>");
9232 MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>");
9233 MODULE_DESCRIPTION(TPACPI_DESC);
9234 MODULE_VERSION(TPACPI_VERSION);
9235 MODULE_LICENSE("GPL");
9236
9237 module_init(thinkpad_acpi_module_init);
9238 module_exit(thinkpad_acpi_module_exit);