Merge branch 'next' of git://git.kernel.org/pub/scm/linux/kernel/git/djbw/async_tx
[sfrench/cifs-2.6.git] / drivers / platform / x86 / thinkpad_acpi.c
1 /*
2  *  thinkpad_acpi.c - ThinkPad ACPI Extras
3  *
4  *
5  *  Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net>
6  *  Copyright (C) 2006-2009 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  *  02110-1301, USA.
22  */
23
24 #define TPACPI_VERSION "0.24"
25 #define TPACPI_SYSFS_VERSION 0x020700
26
27 /*
28  *  Changelog:
29  *  2007-10-20          changelog trimmed down
30  *
31  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
32  *                      drivers/misc.
33  *
34  *  2006-11-22  0.13    new maintainer
35  *                      changelog now lives in git commit history, and will
36  *                      not be updated further in-file.
37  *
38  *  2005-03-17  0.11    support for 600e, 770x
39  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
40  *
41  *  2005-01-16  0.9     use MODULE_VERSION
42  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
43  *                      fix parameter passing on module loading
44  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
45  *                          thanks to Jim Radford <radford@blackbean.org>
46  *  2004-11-08  0.8     fix init error case, don't return from a macro
47  *                          thanks to Chris Wright <chrisw@osdl.org>
48  */
49
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/init.h>
53 #include <linux/types.h>
54 #include <linux/string.h>
55 #include <linux/list.h>
56 #include <linux/mutex.h>
57 #include <linux/sched.h>
58 #include <linux/kthread.h>
59 #include <linux/freezer.h>
60 #include <linux/delay.h>
61 #include <linux/slab.h>
62
63 #include <linux/nvram.h>
64 #include <linux/proc_fs.h>
65 #include <linux/seq_file.h>
66 #include <linux/sysfs.h>
67 #include <linux/backlight.h>
68 #include <linux/fb.h>
69 #include <linux/platform_device.h>
70 #include <linux/hwmon.h>
71 #include <linux/hwmon-sysfs.h>
72 #include <linux/input.h>
73 #include <linux/leds.h>
74 #include <linux/rfkill.h>
75 #include <asm/uaccess.h>
76
77 #include <linux/dmi.h>
78 #include <linux/jiffies.h>
79 #include <linux/workqueue.h>
80
81 #include <sound/core.h>
82 #include <sound/control.h>
83 #include <sound/initval.h>
84
85 #include <acpi/acpi_drivers.h>
86
87 #include <linux/pci_ids.h>
88
89
90 /* ThinkPad CMOS commands */
91 #define TP_CMOS_VOLUME_DOWN     0
92 #define TP_CMOS_VOLUME_UP       1
93 #define TP_CMOS_VOLUME_MUTE     2
94 #define TP_CMOS_BRIGHTNESS_UP   4
95 #define TP_CMOS_BRIGHTNESS_DOWN 5
96 #define TP_CMOS_THINKLIGHT_ON   12
97 #define TP_CMOS_THINKLIGHT_OFF  13
98
99 /* NVRAM Addresses */
100 enum tp_nvram_addr {
101         TP_NVRAM_ADDR_HK2               = 0x57,
102         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
103         TP_NVRAM_ADDR_VIDEO             = 0x59,
104         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
105         TP_NVRAM_ADDR_MIXER             = 0x60,
106 };
107
108 /* NVRAM bit masks */
109 enum {
110         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
111         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
112         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
113         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
114         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
115         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
116         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
117         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
118         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
119         TP_NVRAM_MASK_MUTE              = 0x40,
120         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
121         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
122         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
123 };
124
125 /* ACPI HIDs */
126 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
127
128 /* Input IDs */
129 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
130 #define TPACPI_HKEY_INPUT_VERSION       0x4101
131
132 /* ACPI \WGSV commands */
133 enum {
134         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
135         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
136         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
137         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
138 };
139
140 /* TP_ACPI_WGSV_GET_STATE bits */
141 enum {
142         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
143         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
144         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
145         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
146         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
147         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
148         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
149         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
150         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
151         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
152 };
153
154 /* HKEY events */
155 enum tpacpi_hkey_event_t {
156         /* Hotkey-related */
157         TP_HKEY_EV_HOTKEY_BASE          = 0x1001, /* first hotkey (FN+F1) */
158         TP_HKEY_EV_BRGHT_UP             = 0x1010, /* Brightness up */
159         TP_HKEY_EV_BRGHT_DOWN           = 0x1011, /* Brightness down */
160         TP_HKEY_EV_VOL_UP               = 0x1015, /* Volume up or unmute */
161         TP_HKEY_EV_VOL_DOWN             = 0x1016, /* Volume down or unmute */
162         TP_HKEY_EV_VOL_MUTE             = 0x1017, /* Mixer output mute */
163
164         /* Reasons for waking up from S3/S4 */
165         TP_HKEY_EV_WKUP_S3_UNDOCK       = 0x2304, /* undock requested, S3 */
166         TP_HKEY_EV_WKUP_S4_UNDOCK       = 0x2404, /* undock requested, S4 */
167         TP_HKEY_EV_WKUP_S3_BAYEJ        = 0x2305, /* bay ejection req, S3 */
168         TP_HKEY_EV_WKUP_S4_BAYEJ        = 0x2405, /* bay ejection req, S4 */
169         TP_HKEY_EV_WKUP_S3_BATLOW       = 0x2313, /* battery empty, S3 */
170         TP_HKEY_EV_WKUP_S4_BATLOW       = 0x2413, /* battery empty, S4 */
171
172         /* Auto-sleep after eject request */
173         TP_HKEY_EV_BAYEJ_ACK            = 0x3003, /* bay ejection complete */
174         TP_HKEY_EV_UNDOCK_ACK           = 0x4003, /* undock complete */
175
176         /* Misc bay events */
177         TP_HKEY_EV_OPTDRV_EJ            = 0x3006, /* opt. drive tray ejected */
178
179         /* User-interface events */
180         TP_HKEY_EV_LID_CLOSE            = 0x5001, /* laptop lid closed */
181         TP_HKEY_EV_LID_OPEN             = 0x5002, /* laptop lid opened */
182         TP_HKEY_EV_TABLET_TABLET        = 0x5009, /* tablet swivel up */
183         TP_HKEY_EV_TABLET_NOTEBOOK      = 0x500a, /* tablet swivel down */
184         TP_HKEY_EV_PEN_INSERTED         = 0x500b, /* tablet pen inserted */
185         TP_HKEY_EV_PEN_REMOVED          = 0x500c, /* tablet pen removed */
186         TP_HKEY_EV_BRGHT_CHANGED        = 0x5010, /* backlight control event */
187
188         /* Thermal events */
189         TP_HKEY_EV_ALARM_BAT_HOT        = 0x6011, /* battery too hot */
190         TP_HKEY_EV_ALARM_BAT_XHOT       = 0x6012, /* battery critically hot */
191         TP_HKEY_EV_ALARM_SENSOR_HOT     = 0x6021, /* sensor too hot */
192         TP_HKEY_EV_ALARM_SENSOR_XHOT    = 0x6022, /* sensor critically hot */
193         TP_HKEY_EV_THM_TABLE_CHANGED    = 0x6030, /* thermal table changed */
194
195         /* Misc */
196         TP_HKEY_EV_RFKILL_CHANGED       = 0x7000, /* rfkill switch changed */
197 };
198
199 /****************************************************************************
200  * Main driver
201  */
202
203 #define TPACPI_NAME "thinkpad"
204 #define TPACPI_DESC "ThinkPad ACPI Extras"
205 #define TPACPI_FILE TPACPI_NAME "_acpi"
206 #define TPACPI_URL "http://ibm-acpi.sf.net/"
207 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
208
209 #define TPACPI_PROC_DIR "ibm"
210 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
211 #define TPACPI_DRVR_NAME TPACPI_FILE
212 #define TPACPI_DRVR_SHORTNAME "tpacpi"
213 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
214
215 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
216 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
217
218 #define TPACPI_MAX_ACPI_ARGS 3
219
220 /* printk headers */
221 #define TPACPI_LOG TPACPI_FILE ": "
222 #define TPACPI_EMERG    KERN_EMERG      TPACPI_LOG
223 #define TPACPI_ALERT    KERN_ALERT      TPACPI_LOG
224 #define TPACPI_CRIT     KERN_CRIT       TPACPI_LOG
225 #define TPACPI_ERR      KERN_ERR        TPACPI_LOG
226 #define TPACPI_WARN     KERN_WARNING    TPACPI_LOG
227 #define TPACPI_NOTICE   KERN_NOTICE     TPACPI_LOG
228 #define TPACPI_INFO     KERN_INFO       TPACPI_LOG
229 #define TPACPI_DEBUG    KERN_DEBUG      TPACPI_LOG
230
231 /* Debugging printk groups */
232 #define TPACPI_DBG_ALL          0xffff
233 #define TPACPI_DBG_DISCLOSETASK 0x8000
234 #define TPACPI_DBG_INIT         0x0001
235 #define TPACPI_DBG_EXIT         0x0002
236 #define TPACPI_DBG_RFKILL       0x0004
237 #define TPACPI_DBG_HKEY         0x0008
238 #define TPACPI_DBG_FAN          0x0010
239 #define TPACPI_DBG_BRGHT        0x0020
240 #define TPACPI_DBG_MIXER        0x0040
241
242 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off")
243 #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled")
244 #define strlencmp(a, b) (strncmp((a), (b), strlen(b)))
245
246
247 /****************************************************************************
248  * Driver-wide structs and misc. variables
249  */
250
251 struct ibm_struct;
252
253 struct tp_acpi_drv_struct {
254         const struct acpi_device_id *hid;
255         struct acpi_driver *driver;
256
257         void (*notify) (struct ibm_struct *, u32);
258         acpi_handle *handle;
259         u32 type;
260         struct acpi_device *device;
261 };
262
263 struct ibm_struct {
264         char *name;
265
266         int (*read) (struct seq_file *);
267         int (*write) (char *);
268         void (*exit) (void);
269         void (*resume) (void);
270         void (*suspend) (pm_message_t state);
271         void (*shutdown) (void);
272
273         struct list_head all_drivers;
274
275         struct tp_acpi_drv_struct *acpi;
276
277         struct {
278                 u8 acpi_driver_registered:1;
279                 u8 acpi_notify_installed:1;
280                 u8 proc_created:1;
281                 u8 init_called:1;
282                 u8 experimental:1;
283         } flags;
284 };
285
286 struct ibm_init_struct {
287         char param[32];
288
289         int (*init) (struct ibm_init_struct *);
290         mode_t base_procfs_mode;
291         struct ibm_struct *data;
292 };
293
294 static struct {
295         u32 bluetooth:1;
296         u32 hotkey:1;
297         u32 hotkey_mask:1;
298         u32 hotkey_wlsw:1;
299         u32 hotkey_tablet:1;
300         u32 light:1;
301         u32 light_status:1;
302         u32 bright_16levels:1;
303         u32 bright_acpimode:1;
304         u32 wan:1;
305         u32 uwb:1;
306         u32 fan_ctrl_status_undef:1;
307         u32 second_fan:1;
308         u32 beep_needs_two_args:1;
309         u32 mixer_no_level_control:1;
310         u32 input_device_registered:1;
311         u32 platform_drv_registered:1;
312         u32 platform_drv_attrs_registered:1;
313         u32 sensors_pdrv_registered:1;
314         u32 sensors_pdrv_attrs_registered:1;
315         u32 sensors_pdev_attrs_registered:1;
316         u32 hotkey_poll_active:1;
317 } tp_features;
318
319 static struct {
320         u16 hotkey_mask_ff:1;
321         u16 volume_ctrl_forbidden:1;
322 } tp_warned;
323
324 struct thinkpad_id_data {
325         unsigned int vendor;    /* ThinkPad vendor:
326                                  * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */
327
328         char *bios_version_str; /* Something like 1ZET51WW (1.03z) */
329         char *ec_version_str;   /* Something like 1ZHT51WW-1.04a */
330
331         u16 bios_model;         /* 1Y = 0x5931, 0 = unknown */
332         u16 ec_model;
333         u16 bios_release;       /* 1ZETK1WW = 0x314b, 0 = unknown */
334         u16 ec_release;
335
336         char *model_str;        /* ThinkPad T43 */
337         char *nummodel_str;     /* 9384A9C for a 9384-A9C model */
338 };
339 static struct thinkpad_id_data thinkpad_id;
340
341 static enum {
342         TPACPI_LIFE_INIT = 0,
343         TPACPI_LIFE_RUNNING,
344         TPACPI_LIFE_EXITING,
345 } tpacpi_lifecycle;
346
347 static int experimental;
348 static u32 dbg_level;
349
350 static struct workqueue_struct *tpacpi_wq;
351
352 enum led_status_t {
353         TPACPI_LED_OFF = 0,
354         TPACPI_LED_ON,
355         TPACPI_LED_BLINK,
356 };
357
358 /* Special LED class that can defer work */
359 struct tpacpi_led_classdev {
360         struct led_classdev led_classdev;
361         struct work_struct work;
362         enum led_status_t new_state;
363         unsigned int led;
364 };
365
366 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
367 static int dbg_wlswemul;
368 static int tpacpi_wlsw_emulstate;
369 static int dbg_bluetoothemul;
370 static int tpacpi_bluetooth_emulstate;
371 static int dbg_wwanemul;
372 static int tpacpi_wwan_emulstate;
373 static int dbg_uwbemul;
374 static int tpacpi_uwb_emulstate;
375 #endif
376
377
378 /*************************************************************************
379  *  Debugging helpers
380  */
381
382 #define dbg_printk(a_dbg_level, format, arg...) \
383         do { if (dbg_level & (a_dbg_level)) \
384                 printk(TPACPI_DEBUG "%s: " format, __func__ , ## arg); \
385         } while (0)
386
387 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
388 #define vdbg_printk dbg_printk
389 static const char *str_supported(int is_supported);
390 #else
391 #define vdbg_printk(a_dbg_level, format, arg...) \
392         do { } while (0)
393 #endif
394
395 static void tpacpi_log_usertask(const char * const what)
396 {
397         printk(TPACPI_DEBUG "%s: access by process with PID %d\n",
398                 what, task_tgid_vnr(current));
399 }
400
401 #define tpacpi_disclose_usertask(what, format, arg...) \
402         do { \
403                 if (unlikely( \
404                     (dbg_level & TPACPI_DBG_DISCLOSETASK) && \
405                     (tpacpi_lifecycle == TPACPI_LIFE_RUNNING))) { \
406                         printk(TPACPI_DEBUG "%s: PID %d: " format, \
407                                 what, task_tgid_vnr(current), ## arg); \
408                 } \
409         } while (0)
410
411 /*
412  * Quirk handling helpers
413  *
414  * ThinkPad IDs and versions seen in the field so far
415  * are two-characters from the set [0-9A-Z], i.e. base 36.
416  *
417  * We use values well outside that range as specials.
418  */
419
420 #define TPACPI_MATCH_ANY                0xffffU
421 #define TPACPI_MATCH_UNKNOWN            0U
422
423 /* TPID('1', 'Y') == 0x5931 */
424 #define TPID(__c1, __c2) (((__c2) << 8) | (__c1))
425
426 #define TPACPI_Q_IBM(__id1, __id2, __quirk)     \
427         { .vendor = PCI_VENDOR_ID_IBM,          \
428           .bios = TPID(__id1, __id2),           \
429           .ec = TPACPI_MATCH_ANY,               \
430           .quirks = (__quirk) }
431
432 #define TPACPI_Q_LNV(__id1, __id2, __quirk)     \
433         { .vendor = PCI_VENDOR_ID_LENOVO,       \
434           .bios = TPID(__id1, __id2),           \
435           .ec = TPACPI_MATCH_ANY,               \
436           .quirks = (__quirk) }
437
438 #define TPACPI_QEC_LNV(__id1, __id2, __quirk)   \
439         { .vendor = PCI_VENDOR_ID_LENOVO,       \
440           .bios = TPACPI_MATCH_ANY,             \
441           .ec = TPID(__id1, __id2),             \
442           .quirks = (__quirk) }
443
444 struct tpacpi_quirk {
445         unsigned int vendor;
446         u16 bios;
447         u16 ec;
448         unsigned long quirks;
449 };
450
451 /**
452  * tpacpi_check_quirks() - search BIOS/EC version on a list
453  * @qlist:              array of &struct tpacpi_quirk
454  * @qlist_size:         number of elements in @qlist
455  *
456  * Iterates over a quirks list until one is found that matches the
457  * ThinkPad's vendor, BIOS and EC model.
458  *
459  * Returns 0 if nothing matches, otherwise returns the quirks field of
460  * the matching &struct tpacpi_quirk entry.
461  *
462  * The match criteria is: vendor, ec and bios much match.
463  */
464 static unsigned long __init tpacpi_check_quirks(
465                         const struct tpacpi_quirk *qlist,
466                         unsigned int qlist_size)
467 {
468         while (qlist_size) {
469                 if ((qlist->vendor == thinkpad_id.vendor ||
470                                 qlist->vendor == TPACPI_MATCH_ANY) &&
471                     (qlist->bios == thinkpad_id.bios_model ||
472                                 qlist->bios == TPACPI_MATCH_ANY) &&
473                     (qlist->ec == thinkpad_id.ec_model ||
474                                 qlist->ec == TPACPI_MATCH_ANY))
475                         return qlist->quirks;
476
477                 qlist_size--;
478                 qlist++;
479         }
480         return 0;
481 }
482
483
484 /****************************************************************************
485  ****************************************************************************
486  *
487  * ACPI Helpers and device model
488  *
489  ****************************************************************************
490  ****************************************************************************/
491
492 /*************************************************************************
493  * ACPI basic handles
494  */
495
496 static acpi_handle root_handle;
497
498 #define TPACPI_HANDLE(object, parent, paths...)                 \
499         static acpi_handle  object##_handle;                    \
500         static acpi_handle *object##_parent = &parent##_handle; \
501         static char        *object##_path;                      \
502         static char        *object##_paths[] = { paths }
503
504 TPACPI_HANDLE(ec, root, "\\_SB.PCI0.ISA.EC0",   /* 240, 240x */
505            "\\_SB.PCI.ISA.EC",  /* 570 */
506            "\\_SB.PCI0.ISA0.EC0",       /* 600e/x, 770e, 770x */
507            "\\_SB.PCI0.ISA.EC", /* A21e, A2xm/p, T20-22, X20-21 */
508            "\\_SB.PCI0.AD4S.EC0",       /* i1400, R30 */
509            "\\_SB.PCI0.ICH3.EC0",       /* R31 */
510            "\\_SB.PCI0.LPC.EC", /* all others */
511            );
512
513 TPACPI_HANDLE(ecrd, ec, "ECRD");        /* 570 */
514 TPACPI_HANDLE(ecwr, ec, "ECWR");        /* 570 */
515
516 TPACPI_HANDLE(cmos, root, "\\UCMS",     /* R50, R50e, R50p, R51, */
517                                         /* T4x, X31, X40 */
518            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
519            "\\CMS",             /* R40, R40e */
520            );                   /* all others */
521
522 TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY",   /* 600e/x, 770e, 770x */
523            "^HKEY",             /* R30, R31 */
524            "HKEY",              /* all others */
525            );                   /* 570 */
526
527 TPACPI_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA",   /* 570 */
528            "\\_SB.PCI0.AGP0.VID0",      /* 600e/x, 770x */
529            "\\_SB.PCI0.VID0",   /* 770e */
530            "\\_SB.PCI0.VID",    /* A21e, G4x, R50e, X30, X40 */
531            "\\_SB.PCI0.AGP.VID",        /* all others */
532            );                           /* R30, R31 */
533
534
535 /*************************************************************************
536  * ACPI helpers
537  */
538
539 static int acpi_evalf(acpi_handle handle,
540                       void *res, char *method, char *fmt, ...)
541 {
542         char *fmt0 = fmt;
543         struct acpi_object_list params;
544         union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS];
545         struct acpi_buffer result, *resultp;
546         union acpi_object out_obj;
547         acpi_status status;
548         va_list ap;
549         char res_type;
550         int success;
551         int quiet;
552
553         if (!*fmt) {
554                 printk(TPACPI_ERR "acpi_evalf() called with empty format\n");
555                 return 0;
556         }
557
558         if (*fmt == 'q') {
559                 quiet = 1;
560                 fmt++;
561         } else
562                 quiet = 0;
563
564         res_type = *(fmt++);
565
566         params.count = 0;
567         params.pointer = &in_objs[0];
568
569         va_start(ap, fmt);
570         while (*fmt) {
571                 char c = *(fmt++);
572                 switch (c) {
573                 case 'd':       /* int */
574                         in_objs[params.count].integer.value = va_arg(ap, int);
575                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
576                         break;
577                         /* add more types as needed */
578                 default:
579                         printk(TPACPI_ERR "acpi_evalf() called "
580                                "with invalid format character '%c'\n", c);
581                         return 0;
582                 }
583         }
584         va_end(ap);
585
586         if (res_type != 'v') {
587                 result.length = sizeof(out_obj);
588                 result.pointer = &out_obj;
589                 resultp = &result;
590         } else
591                 resultp = NULL;
592
593         status = acpi_evaluate_object(handle, method, &params, resultp);
594
595         switch (res_type) {
596         case 'd':               /* int */
597                 if (res)
598                         *(int *)res = out_obj.integer.value;
599                 success = status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER;
600                 break;
601         case 'v':               /* void */
602                 success = status == AE_OK;
603                 break;
604                 /* add more types as needed */
605         default:
606                 printk(TPACPI_ERR "acpi_evalf() called "
607                        "with invalid format character '%c'\n", res_type);
608                 return 0;
609         }
610
611         if (!success && !quiet)
612                 printk(TPACPI_ERR "acpi_evalf(%s, %s, ...) failed: %d\n",
613                        method, fmt0, status);
614
615         return success;
616 }
617
618 static int acpi_ec_read(int i, u8 *p)
619 {
620         int v;
621
622         if (ecrd_handle) {
623                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
624                         return 0;
625                 *p = v;
626         } else {
627                 if (ec_read(i, p) < 0)
628                         return 0;
629         }
630
631         return 1;
632 }
633
634 static int acpi_ec_write(int i, u8 v)
635 {
636         if (ecwr_handle) {
637                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
638                         return 0;
639         } else {
640                 if (ec_write(i, v) < 0)
641                         return 0;
642         }
643
644         return 1;
645 }
646
647 static int issue_thinkpad_cmos_command(int cmos_cmd)
648 {
649         if (!cmos_handle)
650                 return -ENXIO;
651
652         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
653                 return -EIO;
654
655         return 0;
656 }
657
658 /*************************************************************************
659  * ACPI device model
660  */
661
662 #define TPACPI_ACPIHANDLE_INIT(object) \
663         drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \
664                 object##_paths, ARRAY_SIZE(object##_paths), &object##_path)
665
666 static void drv_acpi_handle_init(char *name,
667                            acpi_handle *handle, acpi_handle parent,
668                            char **paths, int num_paths, char **path)
669 {
670         int i;
671         acpi_status status;
672
673         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
674                 name);
675
676         for (i = 0; i < num_paths; i++) {
677                 status = acpi_get_handle(parent, paths[i], handle);
678                 if (ACPI_SUCCESS(status)) {
679                         *path = paths[i];
680                         dbg_printk(TPACPI_DBG_INIT,
681                                    "Found ACPI handle %s for %s\n",
682                                    *path, name);
683                         return;
684                 }
685         }
686
687         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
688                     name);
689         *handle = NULL;
690 }
691
692 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
693 {
694         struct ibm_struct *ibm = data;
695
696         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
697                 return;
698
699         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
700                 return;
701
702         ibm->acpi->notify(ibm, event);
703 }
704
705 static int __init setup_acpi_notify(struct ibm_struct *ibm)
706 {
707         acpi_status status;
708         int rc;
709
710         BUG_ON(!ibm->acpi);
711
712         if (!*ibm->acpi->handle)
713                 return 0;
714
715         vdbg_printk(TPACPI_DBG_INIT,
716                 "setting up ACPI notify for %s\n", ibm->name);
717
718         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
719         if (rc < 0) {
720                 printk(TPACPI_ERR "acpi_bus_get_device(%s) failed: %d\n",
721                         ibm->name, rc);
722                 return -ENODEV;
723         }
724
725         ibm->acpi->device->driver_data = ibm;
726         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
727                 TPACPI_ACPI_EVENT_PREFIX,
728                 ibm->name);
729
730         status = acpi_install_notify_handler(*ibm->acpi->handle,
731                         ibm->acpi->type, dispatch_acpi_notify, ibm);
732         if (ACPI_FAILURE(status)) {
733                 if (status == AE_ALREADY_EXISTS) {
734                         printk(TPACPI_NOTICE
735                                "another device driver is already "
736                                "handling %s events\n", ibm->name);
737                 } else {
738                         printk(TPACPI_ERR
739                                "acpi_install_notify_handler(%s) failed: %d\n",
740                                ibm->name, status);
741                 }
742                 return -ENODEV;
743         }
744         ibm->flags.acpi_notify_installed = 1;
745         return 0;
746 }
747
748 static int __init tpacpi_device_add(struct acpi_device *device)
749 {
750         return 0;
751 }
752
753 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
754 {
755         int rc;
756
757         dbg_printk(TPACPI_DBG_INIT,
758                 "registering %s as an ACPI driver\n", ibm->name);
759
760         BUG_ON(!ibm->acpi);
761
762         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
763         if (!ibm->acpi->driver) {
764                 printk(TPACPI_ERR
765                        "failed to allocate memory for ibm->acpi->driver\n");
766                 return -ENOMEM;
767         }
768
769         sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name);
770         ibm->acpi->driver->ids = ibm->acpi->hid;
771
772         ibm->acpi->driver->ops.add = &tpacpi_device_add;
773
774         rc = acpi_bus_register_driver(ibm->acpi->driver);
775         if (rc < 0) {
776                 printk(TPACPI_ERR "acpi_bus_register_driver(%s) failed: %d\n",
777                        ibm->name, rc);
778                 kfree(ibm->acpi->driver);
779                 ibm->acpi->driver = NULL;
780         } else if (!rc)
781                 ibm->flags.acpi_driver_registered = 1;
782
783         return rc;
784 }
785
786
787 /****************************************************************************
788  ****************************************************************************
789  *
790  * Procfs Helpers
791  *
792  ****************************************************************************
793  ****************************************************************************/
794
795 static int dispatch_proc_show(struct seq_file *m, void *v)
796 {
797         struct ibm_struct *ibm = m->private;
798
799         if (!ibm || !ibm->read)
800                 return -EINVAL;
801         return ibm->read(m);
802 }
803
804 static int dispatch_proc_open(struct inode *inode, struct file *file)
805 {
806         return single_open(file, dispatch_proc_show, PDE(inode)->data);
807 }
808
809 static ssize_t dispatch_proc_write(struct file *file,
810                         const char __user *userbuf,
811                         size_t count, loff_t *pos)
812 {
813         struct ibm_struct *ibm = PDE(file->f_path.dentry->d_inode)->data;
814         char *kernbuf;
815         int ret;
816
817         if (!ibm || !ibm->write)
818                 return -EINVAL;
819         if (count > PAGE_SIZE - 2)
820                 return -EINVAL;
821
822         kernbuf = kmalloc(count + 2, GFP_KERNEL);
823         if (!kernbuf)
824                 return -ENOMEM;
825
826         if (copy_from_user(kernbuf, userbuf, count)) {
827                 kfree(kernbuf);
828                 return -EFAULT;
829         }
830
831         kernbuf[count] = 0;
832         strcat(kernbuf, ",");
833         ret = ibm->write(kernbuf);
834         if (ret == 0)
835                 ret = count;
836
837         kfree(kernbuf);
838
839         return ret;
840 }
841
842 static const struct file_operations dispatch_proc_fops = {
843         .owner          = THIS_MODULE,
844         .open           = dispatch_proc_open,
845         .read           = seq_read,
846         .llseek         = seq_lseek,
847         .release        = single_release,
848         .write          = dispatch_proc_write,
849 };
850
851 static char *next_cmd(char **cmds)
852 {
853         char *start = *cmds;
854         char *end;
855
856         while ((end = strchr(start, ',')) && end == start)
857                 start = end + 1;
858
859         if (!end)
860                 return NULL;
861
862         *end = 0;
863         *cmds = end + 1;
864         return start;
865 }
866
867
868 /****************************************************************************
869  ****************************************************************************
870  *
871  * Device model: input, hwmon and platform
872  *
873  ****************************************************************************
874  ****************************************************************************/
875
876 static struct platform_device *tpacpi_pdev;
877 static struct platform_device *tpacpi_sensors_pdev;
878 static struct device *tpacpi_hwmon;
879 static struct input_dev *tpacpi_inputdev;
880 static struct mutex tpacpi_inputdev_send_mutex;
881 static LIST_HEAD(tpacpi_all_drivers);
882
883 static int tpacpi_suspend_handler(struct platform_device *pdev,
884                                   pm_message_t state)
885 {
886         struct ibm_struct *ibm, *itmp;
887
888         list_for_each_entry_safe(ibm, itmp,
889                                  &tpacpi_all_drivers,
890                                  all_drivers) {
891                 if (ibm->suspend)
892                         (ibm->suspend)(state);
893         }
894
895         return 0;
896 }
897
898 static int tpacpi_resume_handler(struct platform_device *pdev)
899 {
900         struct ibm_struct *ibm, *itmp;
901
902         list_for_each_entry_safe(ibm, itmp,
903                                  &tpacpi_all_drivers,
904                                  all_drivers) {
905                 if (ibm->resume)
906                         (ibm->resume)();
907         }
908
909         return 0;
910 }
911
912 static void tpacpi_shutdown_handler(struct platform_device *pdev)
913 {
914         struct ibm_struct *ibm, *itmp;
915
916         list_for_each_entry_safe(ibm, itmp,
917                                  &tpacpi_all_drivers,
918                                  all_drivers) {
919                 if (ibm->shutdown)
920                         (ibm->shutdown)();
921         }
922 }
923
924 static struct platform_driver tpacpi_pdriver = {
925         .driver = {
926                 .name = TPACPI_DRVR_NAME,
927                 .owner = THIS_MODULE,
928         },
929         .suspend = tpacpi_suspend_handler,
930         .resume = tpacpi_resume_handler,
931         .shutdown = tpacpi_shutdown_handler,
932 };
933
934 static struct platform_driver tpacpi_hwmon_pdriver = {
935         .driver = {
936                 .name = TPACPI_HWMON_DRVR_NAME,
937                 .owner = THIS_MODULE,
938         },
939 };
940
941 /*************************************************************************
942  * sysfs support helpers
943  */
944
945 struct attribute_set {
946         unsigned int members, max_members;
947         struct attribute_group group;
948 };
949
950 struct attribute_set_obj {
951         struct attribute_set s;
952         struct attribute *a;
953 } __attribute__((packed));
954
955 static struct attribute_set *create_attr_set(unsigned int max_members,
956                                                 const char *name)
957 {
958         struct attribute_set_obj *sobj;
959
960         if (max_members == 0)
961                 return NULL;
962
963         /* Allocates space for implicit NULL at the end too */
964         sobj = kzalloc(sizeof(struct attribute_set_obj) +
965                     max_members * sizeof(struct attribute *),
966                     GFP_KERNEL);
967         if (!sobj)
968                 return NULL;
969         sobj->s.max_members = max_members;
970         sobj->s.group.attrs = &sobj->a;
971         sobj->s.group.name = name;
972
973         return &sobj->s;
974 }
975
976 #define destroy_attr_set(_set) \
977         kfree(_set);
978
979 /* not multi-threaded safe, use it in a single thread per set */
980 static int add_to_attr_set(struct attribute_set *s, struct attribute *attr)
981 {
982         if (!s || !attr)
983                 return -EINVAL;
984
985         if (s->members >= s->max_members)
986                 return -ENOMEM;
987
988         s->group.attrs[s->members] = attr;
989         s->members++;
990
991         return 0;
992 }
993
994 static int add_many_to_attr_set(struct attribute_set *s,
995                         struct attribute **attr,
996                         unsigned int count)
997 {
998         int i, res;
999
1000         for (i = 0; i < count; i++) {
1001                 res = add_to_attr_set(s, attr[i]);
1002                 if (res)
1003                         return res;
1004         }
1005
1006         return 0;
1007 }
1008
1009 static void delete_attr_set(struct attribute_set *s, struct kobject *kobj)
1010 {
1011         sysfs_remove_group(kobj, &s->group);
1012         destroy_attr_set(s);
1013 }
1014
1015 #define register_attr_set_with_sysfs(_attr_set, _kobj) \
1016         sysfs_create_group(_kobj, &_attr_set->group)
1017
1018 static int parse_strtoul(const char *buf,
1019                 unsigned long max, unsigned long *value)
1020 {
1021         char *endp;
1022
1023         *value = simple_strtoul(skip_spaces(buf), &endp, 0);
1024         endp = skip_spaces(endp);
1025         if (*endp || *value > max)
1026                 return -EINVAL;
1027
1028         return 0;
1029 }
1030
1031 static void tpacpi_disable_brightness_delay(void)
1032 {
1033         if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0))
1034                 printk(TPACPI_NOTICE
1035                         "ACPI backlight control delay disabled\n");
1036 }
1037
1038 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
1039 {
1040         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
1041         union acpi_object *obj;
1042         int rc;
1043
1044         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
1045                 obj = (union acpi_object *)buffer.pointer;
1046                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
1047                         printk(TPACPI_ERR "Unknown _BCL data, "
1048                                "please report this to %s\n", TPACPI_MAIL);
1049                         rc = 0;
1050                 } else {
1051                         rc = obj->package.count;
1052                 }
1053         } else {
1054                 return 0;
1055         }
1056
1057         kfree(buffer.pointer);
1058         return rc;
1059 }
1060
1061 static acpi_status __init tpacpi_acpi_walk_find_bcl(acpi_handle handle,
1062                                         u32 lvl, void *context, void **rv)
1063 {
1064         char name[ACPI_PATH_SEGMENT_LENGTH];
1065         struct acpi_buffer buffer = { sizeof(name), &name };
1066
1067         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
1068             !strncmp("_BCL", name, sizeof(name) - 1)) {
1069                 BUG_ON(!rv || !*rv);
1070                 **(int **)rv = tpacpi_query_bcl_levels(handle);
1071                 return AE_CTRL_TERMINATE;
1072         } else {
1073                 return AE_OK;
1074         }
1075 }
1076
1077 /*
1078  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
1079  */
1080 static int __init tpacpi_check_std_acpi_brightness_support(void)
1081 {
1082         int status;
1083         int bcl_levels = 0;
1084         void *bcl_ptr = &bcl_levels;
1085
1086         if (!vid_handle) {
1087                 TPACPI_ACPIHANDLE_INIT(vid);
1088         }
1089         if (!vid_handle)
1090                 return 0;
1091
1092         /*
1093          * Search for a _BCL method, and execute it.  This is safe on all
1094          * ThinkPads, and as a side-effect, _BCL will place a Lenovo Vista
1095          * BIOS in ACPI backlight control mode.  We do NOT have to care
1096          * about calling the _BCL method in an enabled video device, any
1097          * will do for our purposes.
1098          */
1099
1100         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
1101                                      tpacpi_acpi_walk_find_bcl, NULL, NULL,
1102                                      &bcl_ptr);
1103
1104         if (ACPI_SUCCESS(status) && bcl_levels > 2) {
1105                 tp_features.bright_acpimode = 1;
1106                 return (bcl_levels - 2);
1107         }
1108
1109         return 0;
1110 }
1111
1112 static void printk_deprecated_attribute(const char * const what,
1113                                         const char * const details)
1114 {
1115         tpacpi_log_usertask("deprecated sysfs attribute");
1116         printk(TPACPI_WARN "WARNING: sysfs attribute %s is deprecated and "
1117                 "will be removed. %s\n",
1118                 what, details);
1119 }
1120
1121 /*************************************************************************
1122  * rfkill and radio control support helpers
1123  */
1124
1125 /*
1126  * ThinkPad-ACPI firmware handling model:
1127  *
1128  * WLSW (master wireless switch) is event-driven, and is common to all
1129  * firmware-controlled radios.  It cannot be controlled, just monitored,
1130  * as expected.  It overrides all radio state in firmware
1131  *
1132  * The kernel, a masked-off hotkey, and WLSW can change the radio state
1133  * (TODO: verify how WLSW interacts with the returned radio state).
1134  *
1135  * The only time there are shadow radio state changes, is when
1136  * masked-off hotkeys are used.
1137  */
1138
1139 /*
1140  * Internal driver API for radio state:
1141  *
1142  * int: < 0 = error, otherwise enum tpacpi_rfkill_state
1143  * bool: true means radio blocked (off)
1144  */
1145 enum tpacpi_rfkill_state {
1146         TPACPI_RFK_RADIO_OFF = 0,
1147         TPACPI_RFK_RADIO_ON
1148 };
1149
1150 /* rfkill switches */
1151 enum tpacpi_rfk_id {
1152         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
1153         TPACPI_RFK_WWAN_SW_ID,
1154         TPACPI_RFK_UWB_SW_ID,
1155         TPACPI_RFK_SW_MAX
1156 };
1157
1158 static const char *tpacpi_rfkill_names[] = {
1159         [TPACPI_RFK_BLUETOOTH_SW_ID] = "bluetooth",
1160         [TPACPI_RFK_WWAN_SW_ID] = "wwan",
1161         [TPACPI_RFK_UWB_SW_ID] = "uwb",
1162         [TPACPI_RFK_SW_MAX] = NULL
1163 };
1164
1165 /* ThinkPad-ACPI rfkill subdriver */
1166 struct tpacpi_rfk {
1167         struct rfkill *rfkill;
1168         enum tpacpi_rfk_id id;
1169         const struct tpacpi_rfk_ops *ops;
1170 };
1171
1172 struct tpacpi_rfk_ops {
1173         /* firmware interface */
1174         int (*get_status)(void);
1175         int (*set_status)(const enum tpacpi_rfkill_state);
1176 };
1177
1178 static struct tpacpi_rfk *tpacpi_rfkill_switches[TPACPI_RFK_SW_MAX];
1179
1180 /* Query FW and update rfkill sw state for a given rfkill switch */
1181 static int tpacpi_rfk_update_swstate(const struct tpacpi_rfk *tp_rfk)
1182 {
1183         int status;
1184
1185         if (!tp_rfk)
1186                 return -ENODEV;
1187
1188         status = (tp_rfk->ops->get_status)();
1189         if (status < 0)
1190                 return status;
1191
1192         rfkill_set_sw_state(tp_rfk->rfkill,
1193                             (status == TPACPI_RFK_RADIO_OFF));
1194
1195         return status;
1196 }
1197
1198 /* Query FW and update rfkill sw state for all rfkill switches */
1199 static void tpacpi_rfk_update_swstate_all(void)
1200 {
1201         unsigned int i;
1202
1203         for (i = 0; i < TPACPI_RFK_SW_MAX; i++)
1204                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[i]);
1205 }
1206
1207 /*
1208  * Sync the HW-blocking state of all rfkill switches,
1209  * do notice it causes the rfkill core to schedule uevents
1210  */
1211 static void tpacpi_rfk_update_hwblock_state(bool blocked)
1212 {
1213         unsigned int i;
1214         struct tpacpi_rfk *tp_rfk;
1215
1216         for (i = 0; i < TPACPI_RFK_SW_MAX; i++) {
1217                 tp_rfk = tpacpi_rfkill_switches[i];
1218                 if (tp_rfk) {
1219                         if (rfkill_set_hw_state(tp_rfk->rfkill,
1220                                                 blocked)) {
1221                                 /* ignore -- we track sw block */
1222                         }
1223                 }
1224         }
1225 }
1226
1227 /* Call to get the WLSW state from the firmware */
1228 static int hotkey_get_wlsw(void);
1229
1230 /* Call to query WLSW state and update all rfkill switches */
1231 static bool tpacpi_rfk_check_hwblock_state(void)
1232 {
1233         int res = hotkey_get_wlsw();
1234         int hw_blocked;
1235
1236         /* When unknown or unsupported, we have to assume it is unblocked */
1237         if (res < 0)
1238                 return false;
1239
1240         hw_blocked = (res == TPACPI_RFK_RADIO_OFF);
1241         tpacpi_rfk_update_hwblock_state(hw_blocked);
1242
1243         return hw_blocked;
1244 }
1245
1246 static int tpacpi_rfk_hook_set_block(void *data, bool blocked)
1247 {
1248         struct tpacpi_rfk *tp_rfk = data;
1249         int res;
1250
1251         dbg_printk(TPACPI_DBG_RFKILL,
1252                    "request to change radio state to %s\n",
1253                    blocked ? "blocked" : "unblocked");
1254
1255         /* try to set radio state */
1256         res = (tp_rfk->ops->set_status)(blocked ?
1257                                 TPACPI_RFK_RADIO_OFF : TPACPI_RFK_RADIO_ON);
1258
1259         /* and update the rfkill core with whatever the FW really did */
1260         tpacpi_rfk_update_swstate(tp_rfk);
1261
1262         return (res < 0) ? res : 0;
1263 }
1264
1265 static const struct rfkill_ops tpacpi_rfk_rfkill_ops = {
1266         .set_block = tpacpi_rfk_hook_set_block,
1267 };
1268
1269 static int __init tpacpi_new_rfkill(const enum tpacpi_rfk_id id,
1270                         const struct tpacpi_rfk_ops *tp_rfkops,
1271                         const enum rfkill_type rfktype,
1272                         const char *name,
1273                         const bool set_default)
1274 {
1275         struct tpacpi_rfk *atp_rfk;
1276         int res;
1277         bool sw_state = false;
1278         bool hw_state;
1279         int sw_status;
1280
1281         BUG_ON(id >= TPACPI_RFK_SW_MAX || tpacpi_rfkill_switches[id]);
1282
1283         atp_rfk = kzalloc(sizeof(struct tpacpi_rfk), GFP_KERNEL);
1284         if (atp_rfk)
1285                 atp_rfk->rfkill = rfkill_alloc(name,
1286                                                 &tpacpi_pdev->dev,
1287                                                 rfktype,
1288                                                 &tpacpi_rfk_rfkill_ops,
1289                                                 atp_rfk);
1290         if (!atp_rfk || !atp_rfk->rfkill) {
1291                 printk(TPACPI_ERR
1292                         "failed to allocate memory for rfkill class\n");
1293                 kfree(atp_rfk);
1294                 return -ENOMEM;
1295         }
1296
1297         atp_rfk->id = id;
1298         atp_rfk->ops = tp_rfkops;
1299
1300         sw_status = (tp_rfkops->get_status)();
1301         if (sw_status < 0) {
1302                 printk(TPACPI_ERR
1303                         "failed to read initial state for %s, error %d\n",
1304                         name, sw_status);
1305         } else {
1306                 sw_state = (sw_status == TPACPI_RFK_RADIO_OFF);
1307                 if (set_default) {
1308                         /* try to keep the initial state, since we ask the
1309                          * firmware to preserve it across S5 in NVRAM */
1310                         rfkill_init_sw_state(atp_rfk->rfkill, sw_state);
1311                 }
1312         }
1313         hw_state = tpacpi_rfk_check_hwblock_state();
1314         rfkill_set_hw_state(atp_rfk->rfkill, hw_state);
1315
1316         res = rfkill_register(atp_rfk->rfkill);
1317         if (res < 0) {
1318                 printk(TPACPI_ERR
1319                         "failed to register %s rfkill switch: %d\n",
1320                         name, res);
1321                 rfkill_destroy(atp_rfk->rfkill);
1322                 kfree(atp_rfk);
1323                 return res;
1324         }
1325
1326         tpacpi_rfkill_switches[id] = atp_rfk;
1327
1328         printk(TPACPI_INFO "rfkill switch %s: radio is %sblocked\n",
1329                 name, (sw_state || hw_state) ? "" : "un");
1330         return 0;
1331 }
1332
1333 static void tpacpi_destroy_rfkill(const enum tpacpi_rfk_id id)
1334 {
1335         struct tpacpi_rfk *tp_rfk;
1336
1337         BUG_ON(id >= TPACPI_RFK_SW_MAX);
1338
1339         tp_rfk = tpacpi_rfkill_switches[id];
1340         if (tp_rfk) {
1341                 rfkill_unregister(tp_rfk->rfkill);
1342                 rfkill_destroy(tp_rfk->rfkill);
1343                 tpacpi_rfkill_switches[id] = NULL;
1344                 kfree(tp_rfk);
1345         }
1346 }
1347
1348 static void printk_deprecated_rfkill_attribute(const char * const what)
1349 {
1350         printk_deprecated_attribute(what,
1351                         "Please switch to generic rfkill before year 2010");
1352 }
1353
1354 /* sysfs <radio> enable ------------------------------------------------ */
1355 static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id,
1356                                             struct device_attribute *attr,
1357                                             char *buf)
1358 {
1359         int status;
1360
1361         printk_deprecated_rfkill_attribute(attr->attr.name);
1362
1363         /* This is in the ABI... */
1364         if (tpacpi_rfk_check_hwblock_state()) {
1365                 status = TPACPI_RFK_RADIO_OFF;
1366         } else {
1367                 status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1368                 if (status < 0)
1369                         return status;
1370         }
1371
1372         return snprintf(buf, PAGE_SIZE, "%d\n",
1373                         (status == TPACPI_RFK_RADIO_ON) ? 1 : 0);
1374 }
1375
1376 static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id,
1377                             struct device_attribute *attr,
1378                             const char *buf, size_t count)
1379 {
1380         unsigned long t;
1381         int res;
1382
1383         printk_deprecated_rfkill_attribute(attr->attr.name);
1384
1385         if (parse_strtoul(buf, 1, &t))
1386                 return -EINVAL;
1387
1388         tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t);
1389
1390         /* This is in the ABI... */
1391         if (tpacpi_rfk_check_hwblock_state() && !!t)
1392                 return -EPERM;
1393
1394         res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ?
1395                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF);
1396         tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1397
1398         return (res < 0) ? res : count;
1399 }
1400
1401 /* procfs -------------------------------------------------------------- */
1402 static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, struct seq_file *m)
1403 {
1404         if (id >= TPACPI_RFK_SW_MAX)
1405                 seq_printf(m, "status:\t\tnot supported\n");
1406         else {
1407                 int status;
1408
1409                 /* This is in the ABI... */
1410                 if (tpacpi_rfk_check_hwblock_state()) {
1411                         status = TPACPI_RFK_RADIO_OFF;
1412                 } else {
1413                         status = tpacpi_rfk_update_swstate(
1414                                                 tpacpi_rfkill_switches[id]);
1415                         if (status < 0)
1416                                 return status;
1417                 }
1418
1419                 seq_printf(m, "status:\t\t%s\n",
1420                                 (status == TPACPI_RFK_RADIO_ON) ?
1421                                         "enabled" : "disabled");
1422                 seq_printf(m, "commands:\tenable, disable\n");
1423         }
1424
1425         return 0;
1426 }
1427
1428 static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf)
1429 {
1430         char *cmd;
1431         int status = -1;
1432         int res = 0;
1433
1434         if (id >= TPACPI_RFK_SW_MAX)
1435                 return -ENODEV;
1436
1437         while ((cmd = next_cmd(&buf))) {
1438                 if (strlencmp(cmd, "enable") == 0)
1439                         status = TPACPI_RFK_RADIO_ON;
1440                 else if (strlencmp(cmd, "disable") == 0)
1441                         status = TPACPI_RFK_RADIO_OFF;
1442                 else
1443                         return -EINVAL;
1444         }
1445
1446         if (status != -1) {
1447                 tpacpi_disclose_usertask("procfs", "attempt to %s %s\n",
1448                                 (status == TPACPI_RFK_RADIO_ON) ?
1449                                                 "enable" : "disable",
1450                                 tpacpi_rfkill_names[id]);
1451                 res = (tpacpi_rfkill_switches[id]->ops->set_status)(status);
1452                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1453         }
1454
1455         return res;
1456 }
1457
1458 /*************************************************************************
1459  * thinkpad-acpi driver attributes
1460  */
1461
1462 /* interface_version --------------------------------------------------- */
1463 static ssize_t tpacpi_driver_interface_version_show(
1464                                 struct device_driver *drv,
1465                                 char *buf)
1466 {
1467         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
1468 }
1469
1470 static DRIVER_ATTR(interface_version, S_IRUGO,
1471                 tpacpi_driver_interface_version_show, NULL);
1472
1473 /* debug_level --------------------------------------------------------- */
1474 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
1475                                                 char *buf)
1476 {
1477         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
1478 }
1479
1480 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
1481                                                 const char *buf, size_t count)
1482 {
1483         unsigned long t;
1484
1485         if (parse_strtoul(buf, 0xffff, &t))
1486                 return -EINVAL;
1487
1488         dbg_level = t;
1489
1490         return count;
1491 }
1492
1493 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1494                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
1495
1496 /* version ------------------------------------------------------------- */
1497 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
1498                                                 char *buf)
1499 {
1500         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1501                         TPACPI_DESC, TPACPI_VERSION);
1502 }
1503
1504 static DRIVER_ATTR(version, S_IRUGO,
1505                 tpacpi_driver_version_show, NULL);
1506
1507 /* --------------------------------------------------------------------- */
1508
1509 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1510
1511 /* wlsw_emulstate ------------------------------------------------------ */
1512 static ssize_t tpacpi_driver_wlsw_emulstate_show(struct device_driver *drv,
1513                                                 char *buf)
1514 {
1515         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate);
1516 }
1517
1518 static ssize_t tpacpi_driver_wlsw_emulstate_store(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         if (tpacpi_wlsw_emulstate != !!t) {
1527                 tpacpi_wlsw_emulstate = !!t;
1528                 tpacpi_rfk_update_hwblock_state(!t);    /* negative logic */
1529         }
1530
1531         return count;
1532 }
1533
1534 static DRIVER_ATTR(wlsw_emulstate, S_IWUSR | S_IRUGO,
1535                 tpacpi_driver_wlsw_emulstate_show,
1536                 tpacpi_driver_wlsw_emulstate_store);
1537
1538 /* bluetooth_emulstate ------------------------------------------------- */
1539 static ssize_t tpacpi_driver_bluetooth_emulstate_show(
1540                                         struct device_driver *drv,
1541                                         char *buf)
1542 {
1543         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate);
1544 }
1545
1546 static ssize_t tpacpi_driver_bluetooth_emulstate_store(
1547                                         struct device_driver *drv,
1548                                         const char *buf, size_t count)
1549 {
1550         unsigned long t;
1551
1552         if (parse_strtoul(buf, 1, &t))
1553                 return -EINVAL;
1554
1555         tpacpi_bluetooth_emulstate = !!t;
1556
1557         return count;
1558 }
1559
1560 static DRIVER_ATTR(bluetooth_emulstate, S_IWUSR | S_IRUGO,
1561                 tpacpi_driver_bluetooth_emulstate_show,
1562                 tpacpi_driver_bluetooth_emulstate_store);
1563
1564 /* wwan_emulstate ------------------------------------------------- */
1565 static ssize_t tpacpi_driver_wwan_emulstate_show(
1566                                         struct device_driver *drv,
1567                                         char *buf)
1568 {
1569         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate);
1570 }
1571
1572 static ssize_t tpacpi_driver_wwan_emulstate_store(
1573                                         struct device_driver *drv,
1574                                         const char *buf, size_t count)
1575 {
1576         unsigned long t;
1577
1578         if (parse_strtoul(buf, 1, &t))
1579                 return -EINVAL;
1580
1581         tpacpi_wwan_emulstate = !!t;
1582
1583         return count;
1584 }
1585
1586 static DRIVER_ATTR(wwan_emulstate, S_IWUSR | S_IRUGO,
1587                 tpacpi_driver_wwan_emulstate_show,
1588                 tpacpi_driver_wwan_emulstate_store);
1589
1590 /* uwb_emulstate ------------------------------------------------- */
1591 static ssize_t tpacpi_driver_uwb_emulstate_show(
1592                                         struct device_driver *drv,
1593                                         char *buf)
1594 {
1595         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate);
1596 }
1597
1598 static ssize_t tpacpi_driver_uwb_emulstate_store(
1599                                         struct device_driver *drv,
1600                                         const char *buf, size_t count)
1601 {
1602         unsigned long t;
1603
1604         if (parse_strtoul(buf, 1, &t))
1605                 return -EINVAL;
1606
1607         tpacpi_uwb_emulstate = !!t;
1608
1609         return count;
1610 }
1611
1612 static DRIVER_ATTR(uwb_emulstate, S_IWUSR | S_IRUGO,
1613                 tpacpi_driver_uwb_emulstate_show,
1614                 tpacpi_driver_uwb_emulstate_store);
1615 #endif
1616
1617 /* --------------------------------------------------------------------- */
1618
1619 static struct driver_attribute *tpacpi_driver_attributes[] = {
1620         &driver_attr_debug_level, &driver_attr_version,
1621         &driver_attr_interface_version,
1622 };
1623
1624 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1625 {
1626         int i, res;
1627
1628         i = 0;
1629         res = 0;
1630         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1631                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1632                 i++;
1633         }
1634
1635 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1636         if (!res && dbg_wlswemul)
1637                 res = driver_create_file(drv, &driver_attr_wlsw_emulstate);
1638         if (!res && dbg_bluetoothemul)
1639                 res = driver_create_file(drv, &driver_attr_bluetooth_emulstate);
1640         if (!res && dbg_wwanemul)
1641                 res = driver_create_file(drv, &driver_attr_wwan_emulstate);
1642         if (!res && dbg_uwbemul)
1643                 res = driver_create_file(drv, &driver_attr_uwb_emulstate);
1644 #endif
1645
1646         return res;
1647 }
1648
1649 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1650 {
1651         int i;
1652
1653         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1654                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1655
1656 #ifdef THINKPAD_ACPI_DEBUGFACILITIES
1657         driver_remove_file(drv, &driver_attr_wlsw_emulstate);
1658         driver_remove_file(drv, &driver_attr_bluetooth_emulstate);
1659         driver_remove_file(drv, &driver_attr_wwan_emulstate);
1660         driver_remove_file(drv, &driver_attr_uwb_emulstate);
1661 #endif
1662 }
1663
1664 /*************************************************************************
1665  * Firmware Data
1666  */
1667
1668 /*
1669  * Table of recommended minimum BIOS versions
1670  *
1671  * Reasons for listing:
1672  *    1. Stable BIOS, listed because the unknown amount of
1673  *       bugs and bad ACPI behaviour on older versions
1674  *
1675  *    2. BIOS or EC fw with known bugs that trigger on Linux
1676  *
1677  *    3. BIOS with known reduced functionality in older versions
1678  *
1679  *  We recommend the latest BIOS and EC version.
1680  *  We only support the latest BIOS and EC fw version as a rule.
1681  *
1682  *  Sources: IBM ThinkPad Public Web Documents (update changelogs),
1683  *  Information from users in ThinkWiki
1684  *
1685  *  WARNING: we use this table also to detect that the machine is
1686  *  a ThinkPad in some cases, so don't remove entries lightly.
1687  */
1688
1689 #define TPV_Q(__v, __id1, __id2, __bv1, __bv2)          \
1690         { .vendor       = (__v),                        \
1691           .bios         = TPID(__id1, __id2),           \
1692           .ec           = TPACPI_MATCH_ANY,             \
1693           .quirks       = TPACPI_MATCH_ANY << 16        \
1694                           | (__bv1) << 8 | (__bv2) }
1695
1696 #define TPV_Q_X(__v, __bid1, __bid2, __bv1, __bv2,      \
1697                 __eid, __ev1, __ev2)                    \
1698         { .vendor       = (__v),                        \
1699           .bios         = TPID(__bid1, __bid2),         \
1700           .ec           = __eid,                        \
1701           .quirks       = (__ev1) << 24 | (__ev2) << 16 \
1702                           | (__bv1) << 8 | (__bv2) }
1703
1704 #define TPV_QI0(__id1, __id2, __bv1, __bv2) \
1705         TPV_Q(PCI_VENDOR_ID_IBM, __id1, __id2, __bv1, __bv2)
1706
1707 /* Outdated IBM BIOSes often lack the EC id string */
1708 #define TPV_QI1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1709         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1710                 __bv1, __bv2, TPID(__id1, __id2),       \
1711                 __ev1, __ev2),                          \
1712         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1713                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1714                 __ev1, __ev2)
1715
1716 /* Outdated IBM BIOSes often lack the EC id string */
1717 #define TPV_QI2(__bid1, __bid2, __bv1, __bv2,           \
1718                 __eid1, __eid2, __ev1, __ev2)           \
1719         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1720                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1721                 __ev1, __ev2),                          \
1722         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1723                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1724                 __ev1, __ev2)
1725
1726 #define TPV_QL0(__id1, __id2, __bv1, __bv2) \
1727         TPV_Q(PCI_VENDOR_ID_LENOVO, __id1, __id2, __bv1, __bv2)
1728
1729 #define TPV_QL1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1730         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __id1, __id2,     \
1731                 __bv1, __bv2, TPID(__id1, __id2),       \
1732                 __ev1, __ev2)
1733
1734 #define TPV_QL2(__bid1, __bid2, __bv1, __bv2,           \
1735                 __eid1, __eid2, __ev1, __ev2)           \
1736         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __bid1, __bid2,   \
1737                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1738                 __ev1, __ev2)
1739
1740 static const struct tpacpi_quirk tpacpi_bios_version_qtable[] __initconst = {
1741         /*  Numeric models ------------------ */
1742         /*      FW MODEL   BIOS VERS          */
1743         TPV_QI0('I', 'M',  '6', '5'),            /* 570 */
1744         TPV_QI0('I', 'U',  '2', '6'),            /* 570E */
1745         TPV_QI0('I', 'B',  '5', '4'),            /* 600 */
1746         TPV_QI0('I', 'H',  '4', '7'),            /* 600E */
1747         TPV_QI0('I', 'N',  '3', '6'),            /* 600E */
1748         TPV_QI0('I', 'T',  '5', '5'),            /* 600X */
1749         TPV_QI0('I', 'D',  '4', '8'),            /* 770, 770E, 770ED */
1750         TPV_QI0('I', 'I',  '4', '2'),            /* 770X */
1751         TPV_QI0('I', 'O',  '2', '3'),            /* 770Z */
1752
1753         /* A-series ------------------------- */
1754         /*      FW MODEL   BIOS VERS  EC VERS */
1755         TPV_QI0('I', 'W',  '5', '9'),            /* A20m */
1756         TPV_QI0('I', 'V',  '6', '9'),            /* A20p */
1757         TPV_QI0('1', '0',  '2', '6'),            /* A21e, A22e */
1758         TPV_QI0('K', 'U',  '3', '6'),            /* A21e */
1759         TPV_QI0('K', 'X',  '3', '6'),            /* A21m, A22m */
1760         TPV_QI0('K', 'Y',  '3', '8'),            /* A21p, A22p */
1761         TPV_QI0('1', 'B',  '1', '7'),            /* A22e */
1762         TPV_QI0('1', '3',  '2', '0'),            /* A22m */
1763         TPV_QI0('1', 'E',  '7', '3'),            /* A30/p (0) */
1764         TPV_QI1('1', 'G',  '4', '1',  '1', '7'), /* A31/p (0) */
1765         TPV_QI1('1', 'N',  '1', '6',  '0', '7'), /* A31/p (0) */
1766
1767         /* G-series ------------------------- */
1768         /*      FW MODEL   BIOS VERS          */
1769         TPV_QI0('1', 'T',  'A', '6'),            /* G40 */
1770         TPV_QI0('1', 'X',  '5', '7'),            /* G41 */
1771
1772         /* R-series, T-series --------------- */
1773         /*      FW MODEL   BIOS VERS  EC VERS */
1774         TPV_QI0('1', 'C',  'F', '0'),            /* R30 */
1775         TPV_QI0('1', 'F',  'F', '1'),            /* R31 */
1776         TPV_QI0('1', 'M',  '9', '7'),            /* R32 */
1777         TPV_QI0('1', 'O',  '6', '1'),            /* R40 */
1778         TPV_QI0('1', 'P',  '6', '5'),            /* R40 */
1779         TPV_QI0('1', 'S',  '7', '0'),            /* R40e */
1780         TPV_QI1('1', 'R',  'D', 'R',  '7', '1'), /* R50/p, R51,
1781                                                     T40/p, T41/p, T42/p (1) */
1782         TPV_QI1('1', 'V',  '7', '1',  '2', '8'), /* R50e, R51 (1) */
1783         TPV_QI1('7', '8',  '7', '1',  '0', '6'), /* R51e (1) */
1784         TPV_QI1('7', '6',  '6', '9',  '1', '6'), /* R52 (1) */
1785         TPV_QI1('7', '0',  '6', '9',  '2', '8'), /* R52, T43 (1) */
1786
1787         TPV_QI0('I', 'Y',  '6', '1'),            /* T20 */
1788         TPV_QI0('K', 'Z',  '3', '4'),            /* T21 */
1789         TPV_QI0('1', '6',  '3', '2'),            /* T22 */
1790         TPV_QI1('1', 'A',  '6', '4',  '2', '3'), /* T23 (0) */
1791         TPV_QI1('1', 'I',  '7', '1',  '2', '0'), /* T30 (0) */
1792         TPV_QI1('1', 'Y',  '6', '5',  '2', '9'), /* T43/p (1) */
1793
1794         TPV_QL1('7', '9',  'E', '3',  '5', '0'), /* T60/p */
1795         TPV_QL1('7', 'C',  'D', '2',  '2', '2'), /* R60, R60i */
1796         TPV_QL1('7', 'E',  'D', '0',  '1', '5'), /* R60e, R60i */
1797
1798         /*      BIOS FW    BIOS VERS  EC FW     EC VERS */
1799         TPV_QI2('1', 'W',  '9', '0',  '1', 'V', '2', '8'), /* R50e (1) */
1800         TPV_QL2('7', 'I',  '3', '4',  '7', '9', '5', '0'), /* T60/p wide */
1801
1802         /* X-series ------------------------- */
1803         /*      FW MODEL   BIOS VERS  EC VERS */
1804         TPV_QI0('I', 'Z',  '9', 'D'),            /* X20, X21 */
1805         TPV_QI0('1', 'D',  '7', '0'),            /* X22, X23, X24 */
1806         TPV_QI1('1', 'K',  '4', '8',  '1', '8'), /* X30 (0) */
1807         TPV_QI1('1', 'Q',  '9', '7',  '2', '3'), /* X31, X32 (0) */
1808         TPV_QI1('1', 'U',  'D', '3',  'B', '2'), /* X40 (0) */
1809         TPV_QI1('7', '4',  '6', '4',  '2', '7'), /* X41 (0) */
1810         TPV_QI1('7', '5',  '6', '0',  '2', '0'), /* X41t (0) */
1811
1812         TPV_QL1('7', 'B',  'D', '7',  '4', '0'), /* X60/s */
1813         TPV_QL1('7', 'J',  '3', '0',  '1', '3'), /* X60t */
1814
1815         /* (0) - older versions lack DMI EC fw string and functionality */
1816         /* (1) - older versions known to lack functionality */
1817 };
1818
1819 #undef TPV_QL1
1820 #undef TPV_QL0
1821 #undef TPV_QI2
1822 #undef TPV_QI1
1823 #undef TPV_QI0
1824 #undef TPV_Q_X
1825 #undef TPV_Q
1826
1827 static void __init tpacpi_check_outdated_fw(void)
1828 {
1829         unsigned long fwvers;
1830         u16 ec_version, bios_version;
1831
1832         fwvers = tpacpi_check_quirks(tpacpi_bios_version_qtable,
1833                                 ARRAY_SIZE(tpacpi_bios_version_qtable));
1834
1835         if (!fwvers)
1836                 return;
1837
1838         bios_version = fwvers & 0xffffU;
1839         ec_version = (fwvers >> 16) & 0xffffU;
1840
1841         /* note that unknown versions are set to 0x0000 and we use that */
1842         if ((bios_version > thinkpad_id.bios_release) ||
1843             (ec_version > thinkpad_id.ec_release &&
1844                                 ec_version != TPACPI_MATCH_ANY)) {
1845                 /*
1846                  * The changelogs would let us track down the exact
1847                  * reason, but it is just too much of a pain to track
1848                  * it.  We only list BIOSes that are either really
1849                  * broken, or really stable to begin with, so it is
1850                  * best if the user upgrades the firmware anyway.
1851                  */
1852                 printk(TPACPI_WARN
1853                         "WARNING: Outdated ThinkPad BIOS/EC firmware\n");
1854                 printk(TPACPI_WARN
1855                         "WARNING: This firmware may be missing critical bug "
1856                         "fixes and/or important features\n");
1857         }
1858 }
1859
1860 static bool __init tpacpi_is_fw_known(void)
1861 {
1862         return tpacpi_check_quirks(tpacpi_bios_version_qtable,
1863                         ARRAY_SIZE(tpacpi_bios_version_qtable)) != 0;
1864 }
1865
1866 /****************************************************************************
1867  ****************************************************************************
1868  *
1869  * Subdrivers
1870  *
1871  ****************************************************************************
1872  ****************************************************************************/
1873
1874 /*************************************************************************
1875  * thinkpad-acpi init subdriver
1876  */
1877
1878 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
1879 {
1880         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
1881         printk(TPACPI_INFO "%s\n", TPACPI_URL);
1882
1883         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
1884                 (thinkpad_id.bios_version_str) ?
1885                         thinkpad_id.bios_version_str : "unknown",
1886                 (thinkpad_id.ec_version_str) ?
1887                         thinkpad_id.ec_version_str : "unknown");
1888
1889         if (thinkpad_id.vendor && thinkpad_id.model_str)
1890                 printk(TPACPI_INFO "%s %s, model %s\n",
1891                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
1892                                 "IBM" : ((thinkpad_id.vendor ==
1893                                                 PCI_VENDOR_ID_LENOVO) ?
1894                                         "Lenovo" : "Unknown vendor"),
1895                         thinkpad_id.model_str,
1896                         (thinkpad_id.nummodel_str) ?
1897                                 thinkpad_id.nummodel_str : "unknown");
1898
1899         tpacpi_check_outdated_fw();
1900         return 0;
1901 }
1902
1903 static int thinkpad_acpi_driver_read(struct seq_file *m)
1904 {
1905         seq_printf(m, "driver:\t\t%s\n", TPACPI_DESC);
1906         seq_printf(m, "version:\t%s\n", TPACPI_VERSION);
1907         return 0;
1908 }
1909
1910 static struct ibm_struct thinkpad_acpi_driver_data = {
1911         .name = "driver",
1912         .read = thinkpad_acpi_driver_read,
1913 };
1914
1915 /*************************************************************************
1916  * Hotkey subdriver
1917  */
1918
1919 /*
1920  * ThinkPad firmware event model
1921  *
1922  * The ThinkPad firmware has two main event interfaces: normal ACPI
1923  * notifications (which follow the ACPI standard), and a private event
1924  * interface.
1925  *
1926  * The private event interface also issues events for the hotkeys.  As
1927  * the driver gained features, the event handling code ended up being
1928  * built around the hotkey subdriver.  This will need to be refactored
1929  * to a more formal event API eventually.
1930  *
1931  * Some "hotkeys" are actually supposed to be used as event reports,
1932  * such as "brightness has changed", "volume has changed", depending on
1933  * the ThinkPad model and how the firmware is operating.
1934  *
1935  * Unlike other classes, hotkey-class events have mask/unmask control on
1936  * non-ancient firmware.  However, how it behaves changes a lot with the
1937  * firmware model and version.
1938  */
1939
1940 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1941         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1942         TP_ACPI_HOTKEYSCAN_FNF2,
1943         TP_ACPI_HOTKEYSCAN_FNF3,
1944         TP_ACPI_HOTKEYSCAN_FNF4,
1945         TP_ACPI_HOTKEYSCAN_FNF5,
1946         TP_ACPI_HOTKEYSCAN_FNF6,
1947         TP_ACPI_HOTKEYSCAN_FNF7,
1948         TP_ACPI_HOTKEYSCAN_FNF8,
1949         TP_ACPI_HOTKEYSCAN_FNF9,
1950         TP_ACPI_HOTKEYSCAN_FNF10,
1951         TP_ACPI_HOTKEYSCAN_FNF11,
1952         TP_ACPI_HOTKEYSCAN_FNF12,
1953         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1954         TP_ACPI_HOTKEYSCAN_FNINSERT,
1955         TP_ACPI_HOTKEYSCAN_FNDELETE,
1956         TP_ACPI_HOTKEYSCAN_FNHOME,
1957         TP_ACPI_HOTKEYSCAN_FNEND,
1958         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1959         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1960         TP_ACPI_HOTKEYSCAN_FNSPACE,
1961         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1962         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1963         TP_ACPI_HOTKEYSCAN_MUTE,
1964         TP_ACPI_HOTKEYSCAN_THINKPAD,
1965 };
1966
1967 enum {  /* Keys/events available through NVRAM polling */
1968         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1969         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1970 };
1971
1972 enum {  /* Positions of some of the keys in hotkey masks */
1973         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1974         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1975         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1976         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1977         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1978         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1979         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1980         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1981         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1982         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1983         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1984 };
1985
1986 enum {  /* NVRAM to ACPI HKEY group map */
1987         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1988                                           TP_ACPI_HKEY_ZOOM_MASK |
1989                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1990                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1991         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1992                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1993         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1994                                           TP_ACPI_HKEY_VOLDWN_MASK |
1995                                           TP_ACPI_HKEY_MUTE_MASK,
1996 };
1997
1998 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1999 struct tp_nvram_state {
2000        u16 thinkpad_toggle:1;
2001        u16 zoom_toggle:1;
2002        u16 display_toggle:1;
2003        u16 thinklight_toggle:1;
2004        u16 hibernate_toggle:1;
2005        u16 displayexp_toggle:1;
2006        u16 display_state:1;
2007        u16 brightness_toggle:1;
2008        u16 volume_toggle:1;
2009        u16 mute:1;
2010
2011        u8 brightness_level;
2012        u8 volume_level;
2013 };
2014
2015 /* kthread for the hotkey poller */
2016 static struct task_struct *tpacpi_hotkey_task;
2017
2018 /* Acquired while the poller kthread is running, use to sync start/stop */
2019 static struct mutex hotkey_thread_mutex;
2020
2021 /*
2022  * Acquire mutex to write poller control variables as an
2023  * atomic block.
2024  *
2025  * Increment hotkey_config_change when changing them if you
2026  * want the kthread to forget old state.
2027  *
2028  * See HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
2029  */
2030 static struct mutex hotkey_thread_data_mutex;
2031 static unsigned int hotkey_config_change;
2032
2033 /*
2034  * hotkey poller control variables
2035  *
2036  * Must be atomic or readers will also need to acquire mutex
2037  *
2038  * HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
2039  * should be used only when the changes need to be taken as
2040  * a block, OR when one needs to force the kthread to forget
2041  * old state.
2042  */
2043 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
2044 static unsigned int hotkey_poll_freq = 10; /* Hz */
2045
2046 #define HOTKEY_CONFIG_CRITICAL_START \
2047         do { \
2048                 mutex_lock(&hotkey_thread_data_mutex); \
2049                 hotkey_config_change++; \
2050         } while (0);
2051 #define HOTKEY_CONFIG_CRITICAL_END \
2052         mutex_unlock(&hotkey_thread_data_mutex);
2053
2054 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2055
2056 #define hotkey_source_mask 0U
2057 #define HOTKEY_CONFIG_CRITICAL_START
2058 #define HOTKEY_CONFIG_CRITICAL_END
2059
2060 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2061
2062 static struct mutex hotkey_mutex;
2063
2064 static enum {   /* Reasons for waking up */
2065         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
2066         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
2067         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
2068 } hotkey_wakeup_reason;
2069
2070 static int hotkey_autosleep_ack;
2071
2072 static u32 hotkey_orig_mask;            /* events the BIOS had enabled */
2073 static u32 hotkey_all_mask;             /* all events supported in fw */
2074 static u32 hotkey_reserved_mask;        /* events better left disabled */
2075 static u32 hotkey_driver_mask;          /* events needed by the driver */
2076 static u32 hotkey_user_mask;            /* events visible to userspace */
2077 static u32 hotkey_acpi_mask;            /* events enabled in firmware */
2078
2079 static unsigned int hotkey_report_mode;
2080
2081 static u16 *hotkey_keycode_map;
2082
2083 static struct attribute_set *hotkey_dev_attributes;
2084
2085 static void tpacpi_driver_event(const unsigned int hkey_event);
2086 static void hotkey_driver_event(const unsigned int scancode);
2087 static void hotkey_poll_setup(const bool may_warn);
2088
2089 /* HKEY.MHKG() return bits */
2090 #define TP_HOTKEY_TABLET_MASK (1 << 3)
2091
2092 static int hotkey_get_wlsw(void)
2093 {
2094         int status;
2095
2096         if (!tp_features.hotkey_wlsw)
2097                 return -ENODEV;
2098
2099 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2100         if (dbg_wlswemul)
2101                 return (tpacpi_wlsw_emulstate) ?
2102                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2103 #endif
2104
2105         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
2106                 return -EIO;
2107
2108         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2109 }
2110
2111 static int hotkey_get_tablet_mode(int *status)
2112 {
2113         int s;
2114
2115         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
2116                 return -EIO;
2117
2118         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
2119         return 0;
2120 }
2121
2122 /*
2123  * Reads current event mask from firmware, and updates
2124  * hotkey_acpi_mask accordingly.  Also resets any bits
2125  * from hotkey_user_mask that are unavailable to be
2126  * delivered (shadow requirement of the userspace ABI).
2127  *
2128  * Call with hotkey_mutex held
2129  */
2130 static int hotkey_mask_get(void)
2131 {
2132         if (tp_features.hotkey_mask) {
2133                 u32 m = 0;
2134
2135                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
2136                         return -EIO;
2137
2138                 hotkey_acpi_mask = m;
2139         } else {
2140                 /* no mask support doesn't mean no event support... */
2141                 hotkey_acpi_mask = hotkey_all_mask;
2142         }
2143
2144         /* sync userspace-visible mask */
2145         hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask);
2146
2147         return 0;
2148 }
2149
2150 void static hotkey_mask_warn_incomplete_mask(void)
2151 {
2152         /* log only what the user can fix... */
2153         const u32 wantedmask = hotkey_driver_mask &
2154                 ~(hotkey_acpi_mask | hotkey_source_mask) &
2155                 (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK);
2156
2157         if (wantedmask)
2158                 printk(TPACPI_NOTICE
2159                         "required events 0x%08x not enabled!\n",
2160                         wantedmask);
2161 }
2162
2163 /*
2164  * Set the firmware mask when supported
2165  *
2166  * Also calls hotkey_mask_get to update hotkey_acpi_mask.
2167  *
2168  * NOTE: does not set bits in hotkey_user_mask, but may reset them.
2169  *
2170  * Call with hotkey_mutex held
2171  */
2172 static int hotkey_mask_set(u32 mask)
2173 {
2174         int i;
2175         int rc = 0;
2176
2177         const u32 fwmask = mask & ~hotkey_source_mask;
2178
2179         if (tp_features.hotkey_mask) {
2180                 for (i = 0; i < 32; i++) {
2181                         if (!acpi_evalf(hkey_handle,
2182                                         NULL, "MHKM", "vdd", i + 1,
2183                                         !!(mask & (1 << i)))) {
2184                                 rc = -EIO;
2185                                 break;
2186                         }
2187                 }
2188         }
2189
2190         /*
2191          * We *must* make an inconditional call to hotkey_mask_get to
2192          * refresh hotkey_acpi_mask and update hotkey_user_mask
2193          *
2194          * Take the opportunity to also log when we cannot _enable_
2195          * a given event.
2196          */
2197         if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) {
2198                 printk(TPACPI_NOTICE
2199                        "asked for hotkey mask 0x%08x, but "
2200                        "firmware forced it to 0x%08x\n",
2201                        fwmask, hotkey_acpi_mask);
2202         }
2203
2204         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING)
2205                 hotkey_mask_warn_incomplete_mask();
2206
2207         return rc;
2208 }
2209
2210 /*
2211  * Sets hotkey_user_mask and tries to set the firmware mask
2212  *
2213  * Call with hotkey_mutex held
2214  */
2215 static int hotkey_user_mask_set(const u32 mask)
2216 {
2217         int rc;
2218
2219         /* Give people a chance to notice they are doing something that
2220          * is bound to go boom on their users sooner or later */
2221         if (!tp_warned.hotkey_mask_ff &&
2222             (mask == 0xffff || mask == 0xffffff ||
2223              mask == 0xffffffff)) {
2224                 tp_warned.hotkey_mask_ff = 1;
2225                 printk(TPACPI_NOTICE
2226                        "setting the hotkey mask to 0x%08x is likely "
2227                        "not the best way to go about it\n", mask);
2228                 printk(TPACPI_NOTICE
2229                        "please consider using the driver defaults, "
2230                        "and refer to up-to-date thinkpad-acpi "
2231                        "documentation\n");
2232         }
2233
2234         /* Try to enable what the user asked for, plus whatever we need.
2235          * this syncs everything but won't enable bits in hotkey_user_mask */
2236         rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask);
2237
2238         /* Enable the available bits in hotkey_user_mask */
2239         hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask);
2240
2241         return rc;
2242 }
2243
2244 /*
2245  * Sets the driver hotkey mask.
2246  *
2247  * Can be called even if the hotkey subdriver is inactive
2248  */
2249 static int tpacpi_hotkey_driver_mask_set(const u32 mask)
2250 {
2251         int rc;
2252
2253         /* Do the right thing if hotkey_init has not been called yet */
2254         if (!tp_features.hotkey) {
2255                 hotkey_driver_mask = mask;
2256                 return 0;
2257         }
2258
2259         mutex_lock(&hotkey_mutex);
2260
2261         HOTKEY_CONFIG_CRITICAL_START
2262         hotkey_driver_mask = mask;
2263 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2264         hotkey_source_mask |= (mask & ~hotkey_all_mask);
2265 #endif
2266         HOTKEY_CONFIG_CRITICAL_END
2267
2268         rc = hotkey_mask_set((hotkey_acpi_mask | hotkey_driver_mask) &
2269                                                         ~hotkey_source_mask);
2270         hotkey_poll_setup(true);
2271
2272         mutex_unlock(&hotkey_mutex);
2273
2274         return rc;
2275 }
2276
2277 static int hotkey_status_get(int *status)
2278 {
2279         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
2280                 return -EIO;
2281
2282         return 0;
2283 }
2284
2285 static int hotkey_status_set(bool enable)
2286 {
2287         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
2288                 return -EIO;
2289
2290         return 0;
2291 }
2292
2293 static void tpacpi_input_send_tabletsw(void)
2294 {
2295         int state;
2296
2297         if (tp_features.hotkey_tablet &&
2298             !hotkey_get_tablet_mode(&state)) {
2299                 mutex_lock(&tpacpi_inputdev_send_mutex);
2300
2301                 input_report_switch(tpacpi_inputdev,
2302                                     SW_TABLET_MODE, !!state);
2303                 input_sync(tpacpi_inputdev);
2304
2305                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2306         }
2307 }
2308
2309 /* Do NOT call without validating scancode first */
2310 static void tpacpi_input_send_key(const unsigned int scancode)
2311 {
2312         const unsigned int keycode = hotkey_keycode_map[scancode];
2313
2314         if (keycode != KEY_RESERVED) {
2315                 mutex_lock(&tpacpi_inputdev_send_mutex);
2316
2317                 input_report_key(tpacpi_inputdev, keycode, 1);
2318                 if (keycode == KEY_UNKNOWN)
2319                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2320                                     scancode);
2321                 input_sync(tpacpi_inputdev);
2322
2323                 input_report_key(tpacpi_inputdev, keycode, 0);
2324                 if (keycode == KEY_UNKNOWN)
2325                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2326                                     scancode);
2327                 input_sync(tpacpi_inputdev);
2328
2329                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2330         }
2331 }
2332
2333 /* Do NOT call without validating scancode first */
2334 static void tpacpi_input_send_key_masked(const unsigned int scancode)
2335 {
2336         hotkey_driver_event(scancode);
2337         if (hotkey_user_mask & (1 << scancode))
2338                 tpacpi_input_send_key(scancode);
2339 }
2340
2341 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2342 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
2343
2344 /* Do NOT call without validating scancode first */
2345 static void tpacpi_hotkey_send_key(unsigned int scancode)
2346 {
2347         tpacpi_input_send_key_masked(scancode);
2348         if (hotkey_report_mode < 2) {
2349                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
2350                                 0x80, TP_HKEY_EV_HOTKEY_BASE + scancode);
2351         }
2352 }
2353
2354 static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m)
2355 {
2356         u8 d;
2357
2358         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
2359                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
2360                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
2361                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
2362                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
2363                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
2364         }
2365         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
2366                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
2367                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2368         }
2369         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2370                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2371                 n->displayexp_toggle =
2372                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2373         }
2374         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2375                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2376                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2377                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2378                 n->brightness_toggle =
2379                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2380         }
2381         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2382                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2383                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2384                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2385                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2386                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2387         }
2388 }
2389
2390 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2391                                            struct tp_nvram_state *newn,
2392                                            const u32 event_mask)
2393 {
2394
2395 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2396         do { \
2397                 if ((event_mask & (1 << __scancode)) && \
2398                     oldn->__member != newn->__member) \
2399                         tpacpi_hotkey_send_key(__scancode); \
2400         } while (0)
2401
2402 #define TPACPI_MAY_SEND_KEY(__scancode) \
2403         do { \
2404                 if (event_mask & (1 << __scancode)) \
2405                         tpacpi_hotkey_send_key(__scancode); \
2406         } while (0)
2407
2408         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2409         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2410         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2411         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2412
2413         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2414
2415         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2416
2417         /* handle volume */
2418         if (oldn->volume_toggle != newn->volume_toggle) {
2419                 if (oldn->mute != newn->mute) {
2420                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2421                 }
2422                 if (oldn->volume_level > newn->volume_level) {
2423                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2424                 } else if (oldn->volume_level < newn->volume_level) {
2425                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2426                 } else if (oldn->mute == newn->mute) {
2427                         /* repeated key presses that didn't change state */
2428                         if (newn->mute) {
2429                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2430                         } else if (newn->volume_level != 0) {
2431                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2432                         } else {
2433                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2434                         }
2435                 }
2436         }
2437
2438         /* handle brightness */
2439         if (oldn->brightness_toggle != newn->brightness_toggle) {
2440                 if (oldn->brightness_level < newn->brightness_level) {
2441                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2442                 } else if (oldn->brightness_level > newn->brightness_level) {
2443                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2444                 } else {
2445                         /* repeated key presses that didn't change state */
2446                         if (newn->brightness_level != 0) {
2447                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2448                         } else {
2449                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2450                         }
2451                 }
2452         }
2453
2454 #undef TPACPI_COMPARE_KEY
2455 #undef TPACPI_MAY_SEND_KEY
2456 }
2457
2458 /*
2459  * Polling driver
2460  *
2461  * We track all events in hotkey_source_mask all the time, since
2462  * most of them are edge-based.  We only issue those requested by
2463  * hotkey_user_mask or hotkey_driver_mask, though.
2464  */
2465 static int hotkey_kthread(void *data)
2466 {
2467         struct tp_nvram_state s[2];
2468         u32 poll_mask, event_mask;
2469         unsigned int si, so;
2470         unsigned long t;
2471         unsigned int change_detector, must_reset;
2472         unsigned int poll_freq;
2473
2474         mutex_lock(&hotkey_thread_mutex);
2475
2476         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2477                 goto exit;
2478
2479         set_freezable();
2480
2481         so = 0;
2482         si = 1;
2483         t = 0;
2484
2485         /* Initial state for compares */
2486         mutex_lock(&hotkey_thread_data_mutex);
2487         change_detector = hotkey_config_change;
2488         poll_mask = hotkey_source_mask;
2489         event_mask = hotkey_source_mask &
2490                         (hotkey_driver_mask | hotkey_user_mask);
2491         poll_freq = hotkey_poll_freq;
2492         mutex_unlock(&hotkey_thread_data_mutex);
2493         hotkey_read_nvram(&s[so], poll_mask);
2494
2495         while (!kthread_should_stop()) {
2496                 if (t == 0) {
2497                         if (likely(poll_freq))
2498                                 t = 1000/poll_freq;
2499                         else
2500                                 t = 100;        /* should never happen... */
2501                 }
2502                 t = msleep_interruptible(t);
2503                 if (unlikely(kthread_should_stop()))
2504                         break;
2505                 must_reset = try_to_freeze();
2506                 if (t > 0 && !must_reset)
2507                         continue;
2508
2509                 mutex_lock(&hotkey_thread_data_mutex);
2510                 if (must_reset || hotkey_config_change != change_detector) {
2511                         /* forget old state on thaw or config change */
2512                         si = so;
2513                         t = 0;
2514                         change_detector = hotkey_config_change;
2515                 }
2516                 poll_mask = hotkey_source_mask;
2517                 event_mask = hotkey_source_mask &
2518                                 (hotkey_driver_mask | hotkey_user_mask);
2519                 poll_freq = hotkey_poll_freq;
2520                 mutex_unlock(&hotkey_thread_data_mutex);
2521
2522                 if (likely(poll_mask)) {
2523                         hotkey_read_nvram(&s[si], poll_mask);
2524                         if (likely(si != so)) {
2525                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2526                                                                 event_mask);
2527                         }
2528                 }
2529
2530                 so = si;
2531                 si ^= 1;
2532         }
2533
2534 exit:
2535         mutex_unlock(&hotkey_thread_mutex);
2536         return 0;
2537 }
2538
2539 /* call with hotkey_mutex held */
2540 static void hotkey_poll_stop_sync(void)
2541 {
2542         if (tpacpi_hotkey_task) {
2543                 if (frozen(tpacpi_hotkey_task) ||
2544                     freezing(tpacpi_hotkey_task))
2545                         thaw_process(tpacpi_hotkey_task);
2546
2547                 kthread_stop(tpacpi_hotkey_task);
2548                 tpacpi_hotkey_task = NULL;
2549                 mutex_lock(&hotkey_thread_mutex);
2550                 /* at this point, the thread did exit */
2551                 mutex_unlock(&hotkey_thread_mutex);
2552         }
2553 }
2554
2555 /* call with hotkey_mutex held */
2556 static void hotkey_poll_setup(const bool may_warn)
2557 {
2558         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2559         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2560
2561         if (hotkey_poll_freq > 0 &&
2562             (poll_driver_mask ||
2563              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2564                 if (!tpacpi_hotkey_task) {
2565                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2566                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2567                         if (IS_ERR(tpacpi_hotkey_task)) {
2568                                 tpacpi_hotkey_task = NULL;
2569                                 printk(TPACPI_ERR
2570                                        "could not create kernel thread "
2571                                        "for hotkey polling\n");
2572                         }
2573                 }
2574         } else {
2575                 hotkey_poll_stop_sync();
2576                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2577                     hotkey_poll_freq == 0) {
2578                         printk(TPACPI_NOTICE
2579                                 "hot keys 0x%08x and/or events 0x%08x "
2580                                 "require polling, which is currently "
2581                                 "disabled\n",
2582                                 poll_user_mask, poll_driver_mask);
2583                 }
2584         }
2585 }
2586
2587 static void hotkey_poll_setup_safe(const bool may_warn)
2588 {
2589         mutex_lock(&hotkey_mutex);
2590         hotkey_poll_setup(may_warn);
2591         mutex_unlock(&hotkey_mutex);
2592 }
2593
2594 /* call with hotkey_mutex held */
2595 static void hotkey_poll_set_freq(unsigned int freq)
2596 {
2597         if (!freq)
2598                 hotkey_poll_stop_sync();
2599
2600         hotkey_poll_freq = freq;
2601 }
2602
2603 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2604
2605 static void hotkey_poll_setup(const bool __unused)
2606 {
2607 }
2608
2609 static void hotkey_poll_setup_safe(const bool __unused)
2610 {
2611 }
2612
2613 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2614
2615 static int hotkey_inputdev_open(struct input_dev *dev)
2616 {
2617         switch (tpacpi_lifecycle) {
2618         case TPACPI_LIFE_INIT:
2619         case TPACPI_LIFE_RUNNING:
2620                 hotkey_poll_setup_safe(false);
2621                 return 0;
2622         case TPACPI_LIFE_EXITING:
2623                 return -EBUSY;
2624         }
2625
2626         /* Should only happen if tpacpi_lifecycle is corrupt */
2627         BUG();
2628         return -EBUSY;
2629 }
2630
2631 static void hotkey_inputdev_close(struct input_dev *dev)
2632 {
2633         /* disable hotkey polling when possible */
2634         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING &&
2635             !(hotkey_source_mask & hotkey_driver_mask))
2636                 hotkey_poll_setup_safe(false);
2637 }
2638
2639 /* sysfs hotkey enable ------------------------------------------------- */
2640 static ssize_t hotkey_enable_show(struct device *dev,
2641                            struct device_attribute *attr,
2642                            char *buf)
2643 {
2644         int res, status;
2645
2646         printk_deprecated_attribute("hotkey_enable",
2647                         "Hotkey reporting is always enabled");
2648
2649         res = hotkey_status_get(&status);
2650         if (res)
2651                 return res;
2652
2653         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2654 }
2655
2656 static ssize_t hotkey_enable_store(struct device *dev,
2657                             struct device_attribute *attr,
2658                             const char *buf, size_t count)
2659 {
2660         unsigned long t;
2661
2662         printk_deprecated_attribute("hotkey_enable",
2663                         "Hotkeys can be disabled through hotkey_mask");
2664
2665         if (parse_strtoul(buf, 1, &t))
2666                 return -EINVAL;
2667
2668         if (t == 0)
2669                 return -EPERM;
2670
2671         return count;
2672 }
2673
2674 static struct device_attribute dev_attr_hotkey_enable =
2675         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2676                 hotkey_enable_show, hotkey_enable_store);
2677
2678 /* sysfs hotkey mask --------------------------------------------------- */
2679 static ssize_t hotkey_mask_show(struct device *dev,
2680                            struct device_attribute *attr,
2681                            char *buf)
2682 {
2683         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2684 }
2685
2686 static ssize_t hotkey_mask_store(struct device *dev,
2687                             struct device_attribute *attr,
2688                             const char *buf, size_t count)
2689 {
2690         unsigned long t;
2691         int res;
2692
2693         if (parse_strtoul(buf, 0xffffffffUL, &t))
2694                 return -EINVAL;
2695
2696         if (mutex_lock_killable(&hotkey_mutex))
2697                 return -ERESTARTSYS;
2698
2699         res = hotkey_user_mask_set(t);
2700
2701 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2702         hotkey_poll_setup(true);
2703 #endif
2704
2705         mutex_unlock(&hotkey_mutex);
2706
2707         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2708
2709         return (res) ? res : count;
2710 }
2711
2712 static struct device_attribute dev_attr_hotkey_mask =
2713         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2714                 hotkey_mask_show, hotkey_mask_store);
2715
2716 /* sysfs hotkey bios_enabled ------------------------------------------- */
2717 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2718                            struct device_attribute *attr,
2719                            char *buf)
2720 {
2721         return sprintf(buf, "0\n");
2722 }
2723
2724 static struct device_attribute dev_attr_hotkey_bios_enabled =
2725         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2726
2727 /* sysfs hotkey bios_mask ---------------------------------------------- */
2728 static ssize_t hotkey_bios_mask_show(struct device *dev,
2729                            struct device_attribute *attr,
2730                            char *buf)
2731 {
2732         printk_deprecated_attribute("hotkey_bios_mask",
2733                         "This attribute is useless.");
2734         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2735 }
2736
2737 static struct device_attribute dev_attr_hotkey_bios_mask =
2738         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2739
2740 /* sysfs hotkey all_mask ----------------------------------------------- */
2741 static ssize_t hotkey_all_mask_show(struct device *dev,
2742                            struct device_attribute *attr,
2743                            char *buf)
2744 {
2745         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2746                                 hotkey_all_mask | hotkey_source_mask);
2747 }
2748
2749 static struct device_attribute dev_attr_hotkey_all_mask =
2750         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2751
2752 /* sysfs hotkey recommended_mask --------------------------------------- */
2753 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2754                                             struct device_attribute *attr,
2755                                             char *buf)
2756 {
2757         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2758                         (hotkey_all_mask | hotkey_source_mask)
2759                         & ~hotkey_reserved_mask);
2760 }
2761
2762 static struct device_attribute dev_attr_hotkey_recommended_mask =
2763         __ATTR(hotkey_recommended_mask, S_IRUGO,
2764                 hotkey_recommended_mask_show, NULL);
2765
2766 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2767
2768 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2769 static ssize_t hotkey_source_mask_show(struct device *dev,
2770                            struct device_attribute *attr,
2771                            char *buf)
2772 {
2773         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2774 }
2775
2776 static ssize_t hotkey_source_mask_store(struct device *dev,
2777                             struct device_attribute *attr,
2778                             const char *buf, size_t count)
2779 {
2780         unsigned long t;
2781         u32 r_ev;
2782         int rc;
2783
2784         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2785                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2786                 return -EINVAL;
2787
2788         if (mutex_lock_killable(&hotkey_mutex))
2789                 return -ERESTARTSYS;
2790
2791         HOTKEY_CONFIG_CRITICAL_START
2792         hotkey_source_mask = t;
2793         HOTKEY_CONFIG_CRITICAL_END
2794
2795         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2796                         ~hotkey_source_mask);
2797         hotkey_poll_setup(true);
2798
2799         /* check if events needed by the driver got disabled */
2800         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2801                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2802
2803         mutex_unlock(&hotkey_mutex);
2804
2805         if (rc < 0)
2806                 printk(TPACPI_ERR "hotkey_source_mask: failed to update the"
2807                         "firmware event mask!\n");
2808
2809         if (r_ev)
2810                 printk(TPACPI_NOTICE "hotkey_source_mask: "
2811                         "some important events were disabled: "
2812                         "0x%04x\n", r_ev);
2813
2814         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2815
2816         return (rc < 0) ? rc : count;
2817 }
2818
2819 static struct device_attribute dev_attr_hotkey_source_mask =
2820         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2821                 hotkey_source_mask_show, hotkey_source_mask_store);
2822
2823 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2824 static ssize_t hotkey_poll_freq_show(struct device *dev,
2825                            struct device_attribute *attr,
2826                            char *buf)
2827 {
2828         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2829 }
2830
2831 static ssize_t hotkey_poll_freq_store(struct device *dev,
2832                             struct device_attribute *attr,
2833                             const char *buf, size_t count)
2834 {
2835         unsigned long t;
2836
2837         if (parse_strtoul(buf, 25, &t))
2838                 return -EINVAL;
2839
2840         if (mutex_lock_killable(&hotkey_mutex))
2841                 return -ERESTARTSYS;
2842
2843         hotkey_poll_set_freq(t);
2844         hotkey_poll_setup(true);
2845
2846         mutex_unlock(&hotkey_mutex);
2847
2848         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2849
2850         return count;
2851 }
2852
2853 static struct device_attribute dev_attr_hotkey_poll_freq =
2854         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2855                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2856
2857 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2858
2859 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2860 static ssize_t hotkey_radio_sw_show(struct device *dev,
2861                            struct device_attribute *attr,
2862                            char *buf)
2863 {
2864         int res;
2865         res = hotkey_get_wlsw();
2866         if (res < 0)
2867                 return res;
2868
2869         /* Opportunistic update */
2870         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2871
2872         return snprintf(buf, PAGE_SIZE, "%d\n",
2873                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2874 }
2875
2876 static struct device_attribute dev_attr_hotkey_radio_sw =
2877         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
2878
2879 static void hotkey_radio_sw_notify_change(void)
2880 {
2881         if (tp_features.hotkey_wlsw)
2882                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2883                              "hotkey_radio_sw");
2884 }
2885
2886 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2887 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2888                            struct device_attribute *attr,
2889                            char *buf)
2890 {
2891         int res, s;
2892         res = hotkey_get_tablet_mode(&s);
2893         if (res < 0)
2894                 return res;
2895
2896         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2897 }
2898
2899 static struct device_attribute dev_attr_hotkey_tablet_mode =
2900         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2901
2902 static void hotkey_tablet_mode_notify_change(void)
2903 {
2904         if (tp_features.hotkey_tablet)
2905                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2906                              "hotkey_tablet_mode");
2907 }
2908
2909 /* sysfs hotkey report_mode -------------------------------------------- */
2910 static ssize_t hotkey_report_mode_show(struct device *dev,
2911                            struct device_attribute *attr,
2912                            char *buf)
2913 {
2914         return snprintf(buf, PAGE_SIZE, "%d\n",
2915                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2916 }
2917
2918 static struct device_attribute dev_attr_hotkey_report_mode =
2919         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2920
2921 /* sysfs wakeup reason (pollable) -------------------------------------- */
2922 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2923                            struct device_attribute *attr,
2924                            char *buf)
2925 {
2926         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2927 }
2928
2929 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2930         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2931
2932 static void hotkey_wakeup_reason_notify_change(void)
2933 {
2934         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2935                      "wakeup_reason");
2936 }
2937
2938 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2939 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2940                            struct device_attribute *attr,
2941                            char *buf)
2942 {
2943         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2944 }
2945
2946 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2947         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2948                hotkey_wakeup_hotunplug_complete_show, NULL);
2949
2950 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2951 {
2952         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2953                      "wakeup_hotunplug_complete");
2954 }
2955
2956 /* --------------------------------------------------------------------- */
2957
2958 static struct attribute *hotkey_attributes[] __initdata = {
2959         &dev_attr_hotkey_enable.attr,
2960         &dev_attr_hotkey_bios_enabled.attr,
2961         &dev_attr_hotkey_bios_mask.attr,
2962         &dev_attr_hotkey_report_mode.attr,
2963         &dev_attr_hotkey_wakeup_reason.attr,
2964         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2965         &dev_attr_hotkey_mask.attr,
2966         &dev_attr_hotkey_all_mask.attr,
2967         &dev_attr_hotkey_recommended_mask.attr,
2968 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2969         &dev_attr_hotkey_source_mask.attr,
2970         &dev_attr_hotkey_poll_freq.attr,
2971 #endif
2972 };
2973
2974 /*
2975  * Sync both the hw and sw blocking state of all switches
2976  */
2977 static void tpacpi_send_radiosw_update(void)
2978 {
2979         int wlsw;
2980
2981         /*
2982          * We must sync all rfkill controllers *before* issuing any
2983          * rfkill input events, or we will race the rfkill core input
2984          * handler.
2985          *
2986          * tpacpi_inputdev_send_mutex works as a syncronization point
2987          * for the above.
2988          *
2989          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2990          */
2991
2992         wlsw = hotkey_get_wlsw();
2993
2994         /* Sync hw blocking state first if it is hw-blocked */
2995         if (wlsw == TPACPI_RFK_RADIO_OFF)
2996                 tpacpi_rfk_update_hwblock_state(true);
2997
2998         /* Sync sw blocking state */
2999         tpacpi_rfk_update_swstate_all();
3000
3001         /* Sync hw blocking state last if it is hw-unblocked */
3002         if (wlsw == TPACPI_RFK_RADIO_ON)
3003                 tpacpi_rfk_update_hwblock_state(false);
3004
3005         /* Issue rfkill input event for WLSW switch */
3006         if (!(wlsw < 0)) {
3007                 mutex_lock(&tpacpi_inputdev_send_mutex);
3008
3009                 input_report_switch(tpacpi_inputdev,
3010                                     SW_RFKILL_ALL, (wlsw > 0));
3011                 input_sync(tpacpi_inputdev);
3012
3013                 mutex_unlock(&tpacpi_inputdev_send_mutex);
3014         }
3015
3016         /*
3017          * this can be unconditional, as we will poll state again
3018          * if userspace uses the notify to read data
3019          */
3020         hotkey_radio_sw_notify_change();
3021 }
3022
3023 static void hotkey_exit(void)
3024 {
3025 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3026         mutex_lock(&hotkey_mutex);
3027         hotkey_poll_stop_sync();
3028         mutex_unlock(&hotkey_mutex);
3029 #endif
3030
3031         if (hotkey_dev_attributes)
3032                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3033
3034         kfree(hotkey_keycode_map);
3035
3036         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
3037                    "restoring original HKEY status and mask\n");
3038         /* yes, there is a bitwise or below, we want the
3039          * functions to be called even if one of them fail */
3040         if (((tp_features.hotkey_mask &&
3041               hotkey_mask_set(hotkey_orig_mask)) |
3042              hotkey_status_set(false)) != 0)
3043                 printk(TPACPI_ERR
3044                        "failed to restore hot key mask "
3045                        "to BIOS defaults\n");
3046 }
3047
3048 static void __init hotkey_unmap(const unsigned int scancode)
3049 {
3050         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
3051                 clear_bit(hotkey_keycode_map[scancode],
3052                           tpacpi_inputdev->keybit);
3053                 hotkey_keycode_map[scancode] = KEY_RESERVED;
3054         }
3055 }
3056
3057 /*
3058  * HKEY quirks:
3059  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
3060  */
3061
3062 #define TPACPI_HK_Q_INIMASK     0x0001
3063
3064 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
3065         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
3066         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
3067         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
3068         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
3069         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
3070         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
3071         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
3072         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
3073         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
3074         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
3075         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
3076         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
3077         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
3078         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
3079         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
3080         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
3081         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
3082         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
3083         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
3084 };
3085
3086 static int __init hotkey_init(struct ibm_init_struct *iibm)
3087 {
3088         /* Requirements for changing the default keymaps:
3089          *
3090          * 1. Many of the keys are mapped to KEY_RESERVED for very
3091          *    good reasons.  Do not change them unless you have deep
3092          *    knowledge on the IBM and Lenovo ThinkPad firmware for
3093          *    the various ThinkPad models.  The driver behaves
3094          *    differently for KEY_RESERVED: such keys have their
3095          *    hot key mask *unset* in mask_recommended, and also
3096          *    in the initial hot key mask programmed into the
3097          *    firmware at driver load time, which means the firm-
3098          *    ware may react very differently if you change them to
3099          *    something else;
3100          *
3101          * 2. You must be subscribed to the linux-thinkpad and
3102          *    ibm-acpi-devel mailing lists, and you should read the
3103          *    list archives since 2007 if you want to change the
3104          *    keymaps.  This requirement exists so that you will
3105          *    know the past history of problems with the thinkpad-
3106          *    acpi driver keymaps, and also that you will be
3107          *    listening to any bug reports;
3108          *
3109          * 3. Do not send thinkpad-acpi specific patches directly to
3110          *    for merging, *ever*.  Send them to the linux-acpi
3111          *    mailinglist for comments.  Merging is to be done only
3112          *    through acpi-test and the ACPI maintainer.
3113          *
3114          * If the above is too much to ask, don't change the keymap.
3115          * Ask the thinkpad-acpi maintainer to do it, instead.
3116          */
3117         static u16 ibm_keycode_map[] __initdata = {
3118                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3119                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
3120                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3121                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3122
3123                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3124                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3125                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3126                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3127
3128                 /* brightness: firmware always reacts to them */
3129                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3130                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3131
3132                 /* Thinklight: firmware always react to it */
3133                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3134
3135                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3136                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3137
3138                 /* Volume: firmware always react to it and reprograms
3139                  * the built-in *extra* mixer.  Never map it to control
3140                  * another mixer by default. */
3141                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3142                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3143                 KEY_RESERVED,   /* 0x16: MUTE */
3144
3145                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3146
3147                 /* (assignments unknown, please report if found) */
3148                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3149                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3150         };
3151         static u16 lenovo_keycode_map[] __initdata = {
3152                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3153                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3154                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3155                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3156
3157                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3158                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3159                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3160                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3161
3162                 /* These should be enabled --only-- when ACPI video