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