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