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