Linux-libre 4.14.69-gnu
[librecmc/linux-libre.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.25"
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/fb.h>
70 #include <linux/platform_device.h>
71 #include <linux/hwmon.h>
72 #include <linux/hwmon-sysfs.h>
73 #include <linux/input.h>
74 #include <linux/leds.h>
75 #include <linux/rfkill.h>
76 #include <linux/dmi.h>
77 #include <linux/jiffies.h>
78 #include <linux/workqueue.h>
79 #include <linux/acpi.h>
80 #include <linux/pci_ids.h>
81 #include <linux/thinkpad_acpi.h>
82 #include <sound/core.h>
83 #include <sound/control.h>
84 #include <sound/initval.h>
85 #include <linux/uaccess.h>
86 #include <acpi/video.h>
87
88 /* ThinkPad CMOS commands */
89 #define TP_CMOS_VOLUME_DOWN     0
90 #define TP_CMOS_VOLUME_UP       1
91 #define TP_CMOS_VOLUME_MUTE     2
92 #define TP_CMOS_BRIGHTNESS_UP   4
93 #define TP_CMOS_BRIGHTNESS_DOWN 5
94 #define TP_CMOS_THINKLIGHT_ON   12
95 #define TP_CMOS_THINKLIGHT_OFF  13
96
97 /* NVRAM Addresses */
98 enum tp_nvram_addr {
99         TP_NVRAM_ADDR_HK2               = 0x57,
100         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
101         TP_NVRAM_ADDR_VIDEO             = 0x59,
102         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
103         TP_NVRAM_ADDR_MIXER             = 0x60,
104 };
105
106 /* NVRAM bit masks */
107 enum {
108         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
109         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
110         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
111         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
112         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
113         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
114         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
115         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
116         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
117         TP_NVRAM_MASK_MUTE              = 0x40,
118         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
119         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
120         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
121 };
122
123 /* Misc NVRAM-related */
124 enum {
125         TP_NVRAM_LEVEL_VOLUME_MAX = 14,
126 };
127
128 /* ACPI HIDs */
129 #define TPACPI_ACPI_IBM_HKEY_HID        "IBM0068"
130 #define TPACPI_ACPI_LENOVO_HKEY_HID     "LEN0068"
131 #define TPACPI_ACPI_LENOVO_HKEY_V2_HID  "LEN0268"
132 #define TPACPI_ACPI_EC_HID              "PNP0C09"
133
134 /* Input IDs */
135 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
136 #define TPACPI_HKEY_INPUT_VERSION       0x4101
137
138 /* ACPI \WGSV commands */
139 enum {
140         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
141         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
142         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
143         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
144 };
145
146 /* TP_ACPI_WGSV_GET_STATE bits */
147 enum {
148         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
149         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
150         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
151         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
152         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
153         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
154         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
155         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
156         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
157         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
158 };
159
160 /* HKEY events */
161 enum tpacpi_hkey_event_t {
162         /* Hotkey-related */
163         TP_HKEY_EV_HOTKEY_BASE          = 0x1001, /* first hotkey (FN+F1) */
164         TP_HKEY_EV_BRGHT_UP             = 0x1010, /* Brightness up */
165         TP_HKEY_EV_BRGHT_DOWN           = 0x1011, /* Brightness down */
166         TP_HKEY_EV_KBD_LIGHT            = 0x1012, /* Thinklight/kbd backlight */
167         TP_HKEY_EV_VOL_UP               = 0x1015, /* Volume up or unmute */
168         TP_HKEY_EV_VOL_DOWN             = 0x1016, /* Volume down or unmute */
169         TP_HKEY_EV_VOL_MUTE             = 0x1017, /* Mixer output mute */
170
171         /* Reasons for waking up from S3/S4 */
172         TP_HKEY_EV_WKUP_S3_UNDOCK       = 0x2304, /* undock requested, S3 */
173         TP_HKEY_EV_WKUP_S4_UNDOCK       = 0x2404, /* undock requested, S4 */
174         TP_HKEY_EV_WKUP_S3_BAYEJ        = 0x2305, /* bay ejection req, S3 */
175         TP_HKEY_EV_WKUP_S4_BAYEJ        = 0x2405, /* bay ejection req, S4 */
176         TP_HKEY_EV_WKUP_S3_BATLOW       = 0x2313, /* battery empty, S3 */
177         TP_HKEY_EV_WKUP_S4_BATLOW       = 0x2413, /* battery empty, S4 */
178
179         /* Auto-sleep after eject request */
180         TP_HKEY_EV_BAYEJ_ACK            = 0x3003, /* bay ejection complete */
181         TP_HKEY_EV_UNDOCK_ACK           = 0x4003, /* undock complete */
182
183         /* Misc bay events */
184         TP_HKEY_EV_OPTDRV_EJ            = 0x3006, /* opt. drive tray ejected */
185         TP_HKEY_EV_HOTPLUG_DOCK         = 0x4010, /* docked into hotplug dock
186                                                      or port replicator */
187         TP_HKEY_EV_HOTPLUG_UNDOCK       = 0x4011, /* undocked from hotplug
188                                                      dock or port replicator */
189
190         /* User-interface events */
191         TP_HKEY_EV_LID_CLOSE            = 0x5001, /* laptop lid closed */
192         TP_HKEY_EV_LID_OPEN             = 0x5002, /* laptop lid opened */
193         TP_HKEY_EV_TABLET_TABLET        = 0x5009, /* tablet swivel up */
194         TP_HKEY_EV_TABLET_NOTEBOOK      = 0x500a, /* tablet swivel down */
195         TP_HKEY_EV_TABLET_CHANGED       = 0x60c0, /* X1 Yoga (2016):
196                                                    * enter/leave tablet mode
197                                                    */
198         TP_HKEY_EV_PEN_INSERTED         = 0x500b, /* tablet pen inserted */
199         TP_HKEY_EV_PEN_REMOVED          = 0x500c, /* tablet pen removed */
200         TP_HKEY_EV_BRGHT_CHANGED        = 0x5010, /* backlight control event */
201
202         /* Key-related user-interface events */
203         TP_HKEY_EV_KEY_NUMLOCK          = 0x6000, /* NumLock key pressed */
204         TP_HKEY_EV_KEY_FN               = 0x6005, /* Fn key pressed? E420 */
205         TP_HKEY_EV_KEY_FN_ESC           = 0x6060, /* Fn+Esc key pressed X240 */
206
207         /* Thermal events */
208         TP_HKEY_EV_ALARM_BAT_HOT        = 0x6011, /* battery too hot */
209         TP_HKEY_EV_ALARM_BAT_XHOT       = 0x6012, /* battery critically hot */
210         TP_HKEY_EV_ALARM_SENSOR_HOT     = 0x6021, /* sensor too hot */
211         TP_HKEY_EV_ALARM_SENSOR_XHOT    = 0x6022, /* sensor critically hot */
212         TP_HKEY_EV_THM_TABLE_CHANGED    = 0x6030, /* thermal table changed */
213
214         /* AC-related events */
215         TP_HKEY_EV_AC_CHANGED           = 0x6040, /* AC status changed */
216
217         /* Further user-interface events */
218         TP_HKEY_EV_PALM_DETECTED        = 0x60b0, /* palm hoveres keyboard */
219         TP_HKEY_EV_PALM_UNDETECTED      = 0x60b1, /* palm removed */
220
221         /* Misc */
222         TP_HKEY_EV_RFKILL_CHANGED       = 0x7000, /* rfkill switch changed */
223 };
224
225 /****************************************************************************
226  * Main driver
227  */
228
229 #define TPACPI_NAME "thinkpad"
230 #define TPACPI_DESC "ThinkPad ACPI Extras"
231 #define TPACPI_FILE TPACPI_NAME "_acpi"
232 #define TPACPI_URL "http://ibm-acpi.sf.net/"
233 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
234
235 #define TPACPI_PROC_DIR "ibm"
236 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
237 #define TPACPI_DRVR_NAME TPACPI_FILE
238 #define TPACPI_DRVR_SHORTNAME "tpacpi"
239 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
240
241 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
242 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
243
244 #define TPACPI_MAX_ACPI_ARGS 3
245
246 /* Debugging printk groups */
247 #define TPACPI_DBG_ALL          0xffff
248 #define TPACPI_DBG_DISCLOSETASK 0x8000
249 #define TPACPI_DBG_INIT         0x0001
250 #define TPACPI_DBG_EXIT         0x0002
251 #define TPACPI_DBG_RFKILL       0x0004
252 #define TPACPI_DBG_HKEY         0x0008
253 #define TPACPI_DBG_FAN          0x0010
254 #define TPACPI_DBG_BRGHT        0x0020
255 #define TPACPI_DBG_MIXER        0x0040
256
257 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off")
258 #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled")
259 #define strlencmp(a, b) (strncmp((a), (b), strlen(b)))
260
261
262 /****************************************************************************
263  * Driver-wide structs and misc. variables
264  */
265
266 struct ibm_struct;
267
268 struct tp_acpi_drv_struct {
269         const struct acpi_device_id *hid;
270         struct acpi_driver *driver;
271
272         void (*notify) (struct ibm_struct *, u32);
273         acpi_handle *handle;
274         u32 type;
275         struct acpi_device *device;
276 };
277
278 struct ibm_struct {
279         char *name;
280
281         int (*read) (struct seq_file *);
282         int (*write) (char *);
283         void (*exit) (void);
284         void (*resume) (void);
285         void (*suspend) (void);
286         void (*shutdown) (void);
287
288         struct list_head all_drivers;
289
290         struct tp_acpi_drv_struct *acpi;
291
292         struct {
293                 u8 acpi_driver_registered:1;
294                 u8 acpi_notify_installed:1;
295                 u8 proc_created:1;
296                 u8 init_called:1;
297                 u8 experimental:1;
298         } flags;
299 };
300
301 struct ibm_init_struct {
302         char param[32];
303
304         int (*init) (struct ibm_init_struct *);
305         umode_t base_procfs_mode;
306         struct ibm_struct *data;
307 };
308
309 static struct {
310         u32 bluetooth:1;
311         u32 hotkey:1;
312         u32 hotkey_mask:1;
313         u32 hotkey_wlsw:1;
314         enum {
315                 TP_HOTKEY_TABLET_NONE = 0,
316                 TP_HOTKEY_TABLET_USES_MHKG,
317                 /* X1 Yoga 2016, seen on BIOS N1FET44W */
318                 TP_HOTKEY_TABLET_USES_CMMD,
319         } hotkey_tablet;
320         u32 kbdlight:1;
321         u32 light:1;
322         u32 light_status:1;
323         u32 bright_acpimode:1;
324         u32 bright_unkfw:1;
325         u32 wan:1;
326         u32 uwb:1;
327         u32 fan_ctrl_status_undef:1;
328         u32 second_fan:1;
329         u32 beep_needs_two_args:1;
330         u32 mixer_no_level_control:1;
331         u32 input_device_registered:1;
332         u32 platform_drv_registered:1;
333         u32 platform_drv_attrs_registered:1;
334         u32 sensors_pdrv_registered:1;
335         u32 sensors_pdrv_attrs_registered:1;
336         u32 sensors_pdev_attrs_registered:1;
337         u32 hotkey_poll_active:1;
338         u32 has_adaptive_kbd:1;
339 } tp_features;
340
341 static struct {
342         u16 hotkey_mask_ff:1;
343         u16 volume_ctrl_forbidden:1;
344 } tp_warned;
345
346 struct thinkpad_id_data {
347         unsigned int vendor;    /* ThinkPad vendor:
348                                  * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */
349
350         char *bios_version_str; /* Something like 1ZET51WW (1.03z) */
351         char *ec_version_str;   /* Something like 1ZHT51WW-1.04a */
352
353         u16 bios_model;         /* 1Y = 0x5931, 0 = unknown */
354         u16 ec_model;
355         u16 bios_release;       /* 1ZETK1WW = 0x314b, 0 = unknown */
356         u16 ec_release;
357
358         char *model_str;        /* ThinkPad T43 */
359         char *nummodel_str;     /* 9384A9C for a 9384-A9C model */
360 };
361 static struct thinkpad_id_data thinkpad_id;
362
363 static enum {
364         TPACPI_LIFE_INIT = 0,
365         TPACPI_LIFE_RUNNING,
366         TPACPI_LIFE_EXITING,
367 } tpacpi_lifecycle;
368
369 static int experimental;
370 static u32 dbg_level;
371
372 static struct workqueue_struct *tpacpi_wq;
373
374 enum led_status_t {
375         TPACPI_LED_OFF = 0,
376         TPACPI_LED_ON,
377         TPACPI_LED_BLINK,
378 };
379
380 /* tpacpi LED class */
381 struct tpacpi_led_classdev {
382         struct led_classdev led_classdev;
383         int led;
384 };
385
386 /* brightness level capabilities */
387 static unsigned int bright_maxlvl;      /* 0 = unknown */
388
389 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
390 static int dbg_wlswemul;
391 static bool tpacpi_wlsw_emulstate;
392 static int dbg_bluetoothemul;
393 static bool tpacpi_bluetooth_emulstate;
394 static int dbg_wwanemul;
395 static bool tpacpi_wwan_emulstate;
396 static int dbg_uwbemul;
397 static bool tpacpi_uwb_emulstate;
398 #endif
399
400
401 /*************************************************************************
402  *  Debugging helpers
403  */
404
405 #define dbg_printk(a_dbg_level, format, arg...)                         \
406 do {                                                                    \
407         if (dbg_level & (a_dbg_level))                                  \
408                 printk(KERN_DEBUG pr_fmt("%s: " format),                \
409                        __func__, ##arg);                                \
410 } while (0)
411
412 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
413 #define vdbg_printk dbg_printk
414 static const char *str_supported(int is_supported);
415 #else
416 static inline const char *str_supported(int is_supported) { return ""; }
417 #define vdbg_printk(a_dbg_level, format, arg...)        \
418         do { if (0) no_printk(format, ##arg); } while (0)
419 #endif
420
421 static void tpacpi_log_usertask(const char * const what)
422 {
423         printk(KERN_DEBUG pr_fmt("%s: access by process with PID %d\n"),
424                what, task_tgid_vnr(current));
425 }
426
427 #define tpacpi_disclose_usertask(what, format, arg...)                  \
428 do {                                                                    \
429         if (unlikely((dbg_level & TPACPI_DBG_DISCLOSETASK) &&           \
430                      (tpacpi_lifecycle == TPACPI_LIFE_RUNNING))) {      \
431                 printk(KERN_DEBUG pr_fmt("%s: PID %d: " format),        \
432                        what, task_tgid_vnr(current), ## arg);           \
433         }                                                               \
434 } while (0)
435
436 /*
437  * Quirk handling helpers
438  *
439  * ThinkPad IDs and versions seen in the field so far
440  * are two-characters from the set [0-9A-Z], i.e. base 36.
441  *
442  * We use values well outside that range as specials.
443  */
444
445 #define TPACPI_MATCH_ANY                0xffffU
446 #define TPACPI_MATCH_UNKNOWN            0U
447
448 /* TPID('1', 'Y') == 0x5931 */
449 #define TPID(__c1, __c2) (((__c2) << 8) | (__c1))
450
451 #define TPACPI_Q_IBM(__id1, __id2, __quirk)     \
452         { .vendor = PCI_VENDOR_ID_IBM,          \
453           .bios = TPID(__id1, __id2),           \
454           .ec = TPACPI_MATCH_ANY,               \
455           .quirks = (__quirk) }
456
457 #define TPACPI_Q_LNV(__id1, __id2, __quirk)     \
458         { .vendor = PCI_VENDOR_ID_LENOVO,       \
459           .bios = TPID(__id1, __id2),           \
460           .ec = TPACPI_MATCH_ANY,               \
461           .quirks = (__quirk) }
462
463 #define TPACPI_QEC_LNV(__id1, __id2, __quirk)   \
464         { .vendor = PCI_VENDOR_ID_LENOVO,       \
465           .bios = TPACPI_MATCH_ANY,             \
466           .ec = TPID(__id1, __id2),             \
467           .quirks = (__quirk) }
468
469 struct tpacpi_quirk {
470         unsigned int vendor;
471         u16 bios;
472         u16 ec;
473         unsigned long quirks;
474 };
475
476 /**
477  * tpacpi_check_quirks() - search BIOS/EC version on a list
478  * @qlist:              array of &struct tpacpi_quirk
479  * @qlist_size:         number of elements in @qlist
480  *
481  * Iterates over a quirks list until one is found that matches the
482  * ThinkPad's vendor, BIOS and EC model.
483  *
484  * Returns 0 if nothing matches, otherwise returns the quirks field of
485  * the matching &struct tpacpi_quirk entry.
486  *
487  * The match criteria is: vendor, ec and bios much match.
488  */
489 static unsigned long __init tpacpi_check_quirks(
490                         const struct tpacpi_quirk *qlist,
491                         unsigned int qlist_size)
492 {
493         while (qlist_size) {
494                 if ((qlist->vendor == thinkpad_id.vendor ||
495                                 qlist->vendor == TPACPI_MATCH_ANY) &&
496                     (qlist->bios == thinkpad_id.bios_model ||
497                                 qlist->bios == TPACPI_MATCH_ANY) &&
498                     (qlist->ec == thinkpad_id.ec_model ||
499                                 qlist->ec == TPACPI_MATCH_ANY))
500                         return qlist->quirks;
501
502                 qlist_size--;
503                 qlist++;
504         }
505         return 0;
506 }
507
508 static inline bool __pure __init tpacpi_is_lenovo(void)
509 {
510         return thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO;
511 }
512
513 static inline bool __pure __init tpacpi_is_ibm(void)
514 {
515         return thinkpad_id.vendor == PCI_VENDOR_ID_IBM;
516 }
517
518 /****************************************************************************
519  ****************************************************************************
520  *
521  * ACPI Helpers and device model
522  *
523  ****************************************************************************
524  ****************************************************************************/
525
526 /*************************************************************************
527  * ACPI basic handles
528  */
529
530 static acpi_handle root_handle;
531 static acpi_handle ec_handle;
532
533 #define TPACPI_HANDLE(object, parent, paths...)                 \
534         static acpi_handle  object##_handle;                    \
535         static const acpi_handle * const object##_parent __initconst =  \
536                                                 &parent##_handle; \
537         static char *object##_paths[] __initdata = { paths }
538
539 TPACPI_HANDLE(ecrd, ec, "ECRD");        /* 570 */
540 TPACPI_HANDLE(ecwr, ec, "ECWR");        /* 570 */
541
542 TPACPI_HANDLE(cmos, root, "\\UCMS",     /* R50, R50e, R50p, R51, */
543                                         /* T4x, X31, X40 */
544            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
545            "\\CMS",             /* R40, R40e */
546            );                   /* all others */
547
548 TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY",   /* 600e/x, 770e, 770x */
549            "^HKEY",             /* R30, R31 */
550            "HKEY",              /* all others */
551            );                   /* 570 */
552
553 /*************************************************************************
554  * ACPI helpers
555  */
556
557 static int acpi_evalf(acpi_handle handle,
558                       int *res, char *method, char *fmt, ...)
559 {
560         char *fmt0 = fmt;
561         struct acpi_object_list params;
562         union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS];
563         struct acpi_buffer result, *resultp;
564         union acpi_object out_obj;
565         acpi_status status;
566         va_list ap;
567         char res_type;
568         int success;
569         int quiet;
570
571         if (!*fmt) {
572                 pr_err("acpi_evalf() called with empty format\n");
573                 return 0;
574         }
575
576         if (*fmt == 'q') {
577                 quiet = 1;
578                 fmt++;
579         } else
580                 quiet = 0;
581
582         res_type = *(fmt++);
583
584         params.count = 0;
585         params.pointer = &in_objs[0];
586
587         va_start(ap, fmt);
588         while (*fmt) {
589                 char c = *(fmt++);
590                 switch (c) {
591                 case 'd':       /* int */
592                         in_objs[params.count].integer.value = va_arg(ap, int);
593                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
594                         break;
595                         /* add more types as needed */
596                 default:
597                         pr_err("acpi_evalf() called with invalid format character '%c'\n",
598                                c);
599                         va_end(ap);
600                         return 0;
601                 }
602         }
603         va_end(ap);
604
605         if (res_type != 'v') {
606                 result.length = sizeof(out_obj);
607                 result.pointer = &out_obj;
608                 resultp = &result;
609         } else
610                 resultp = NULL;
611
612         status = acpi_evaluate_object(handle, method, &params, resultp);
613
614         switch (res_type) {
615         case 'd':               /* int */
616                 success = (status == AE_OK &&
617                            out_obj.type == ACPI_TYPE_INTEGER);
618                 if (success && res)
619                         *res = out_obj.integer.value;
620                 break;
621         case 'v':               /* void */
622                 success = status == AE_OK;
623                 break;
624                 /* add more types as needed */
625         default:
626                 pr_err("acpi_evalf() called with invalid format character '%c'\n",
627                        res_type);
628                 return 0;
629         }
630
631         if (!success && !quiet)
632                 pr_err("acpi_evalf(%s, %s, ...) failed: %s\n",
633                        method, fmt0, acpi_format_exception(status));
634
635         return success;
636 }
637
638 static int acpi_ec_read(int i, u8 *p)
639 {
640         int v;
641
642         if (ecrd_handle) {
643                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
644                         return 0;
645                 *p = v;
646         } else {
647                 if (ec_read(i, p) < 0)
648                         return 0;
649         }
650
651         return 1;
652 }
653
654 static int acpi_ec_write(int i, u8 v)
655 {
656         if (ecwr_handle) {
657                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
658                         return 0;
659         } else {
660                 if (ec_write(i, v) < 0)
661                         return 0;
662         }
663
664         return 1;
665 }
666
667 static int issue_thinkpad_cmos_command(int cmos_cmd)
668 {
669         if (!cmos_handle)
670                 return -ENXIO;
671
672         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
673                 return -EIO;
674
675         return 0;
676 }
677
678 /*************************************************************************
679  * ACPI device model
680  */
681
682 #define TPACPI_ACPIHANDLE_INIT(object) \
683         drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \
684                 object##_paths, ARRAY_SIZE(object##_paths))
685
686 static void __init drv_acpi_handle_init(const char *name,
687                            acpi_handle *handle, const acpi_handle parent,
688                            char **paths, const int num_paths)
689 {
690         int i;
691         acpi_status status;
692
693         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
694                 name);
695
696         for (i = 0; i < num_paths; i++) {
697                 status = acpi_get_handle(parent, paths[i], handle);
698                 if (ACPI_SUCCESS(status)) {
699                         dbg_printk(TPACPI_DBG_INIT,
700                                    "Found ACPI handle %s for %s\n",
701                                    paths[i], name);
702                         return;
703                 }
704         }
705
706         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
707                     name);
708         *handle = NULL;
709 }
710
711 static acpi_status __init tpacpi_acpi_handle_locate_callback(acpi_handle handle,
712                         u32 level, void *context, void **return_value)
713 {
714         struct acpi_device *dev;
715         if (!strcmp(context, "video")) {
716                 if (acpi_bus_get_device(handle, &dev))
717                         return AE_OK;
718                 if (strcmp(ACPI_VIDEO_HID, acpi_device_hid(dev)))
719                         return AE_OK;
720         }
721
722         *(acpi_handle *)return_value = handle;
723
724         return AE_CTRL_TERMINATE;
725 }
726
727 static void __init tpacpi_acpi_handle_locate(const char *name,
728                 const char *hid,
729                 acpi_handle *handle)
730 {
731         acpi_status status;
732         acpi_handle device_found;
733
734         BUG_ON(!name || !handle);
735         vdbg_printk(TPACPI_DBG_INIT,
736                         "trying to locate ACPI handle for %s, using HID %s\n",
737                         name, hid ? hid : "NULL");
738
739         memset(&device_found, 0, sizeof(device_found));
740         status = acpi_get_devices(hid, tpacpi_acpi_handle_locate_callback,
741                                   (void *)name, &device_found);
742
743         *handle = NULL;
744
745         if (ACPI_SUCCESS(status)) {
746                 *handle = device_found;
747                 dbg_printk(TPACPI_DBG_INIT,
748                            "Found ACPI handle for %s\n", name);
749         } else {
750                 vdbg_printk(TPACPI_DBG_INIT,
751                             "Could not locate an ACPI handle for %s: %s\n",
752                             name, acpi_format_exception(status));
753         }
754 }
755
756 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
757 {
758         struct ibm_struct *ibm = data;
759
760         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
761                 return;
762
763         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
764                 return;
765
766         ibm->acpi->notify(ibm, event);
767 }
768
769 static int __init setup_acpi_notify(struct ibm_struct *ibm)
770 {
771         acpi_status status;
772         int rc;
773
774         BUG_ON(!ibm->acpi);
775
776         if (!*ibm->acpi->handle)
777                 return 0;
778
779         vdbg_printk(TPACPI_DBG_INIT,
780                 "setting up ACPI notify for %s\n", ibm->name);
781
782         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
783         if (rc < 0) {
784                 pr_err("acpi_bus_get_device(%s) failed: %d\n", ibm->name, rc);
785                 return -ENODEV;
786         }
787
788         ibm->acpi->device->driver_data = ibm;
789         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
790                 TPACPI_ACPI_EVENT_PREFIX,
791                 ibm->name);
792
793         status = acpi_install_notify_handler(*ibm->acpi->handle,
794                         ibm->acpi->type, dispatch_acpi_notify, ibm);
795         if (ACPI_FAILURE(status)) {
796                 if (status == AE_ALREADY_EXISTS) {
797                         pr_notice("another device driver is already handling %s events\n",
798                                   ibm->name);
799                 } else {
800                         pr_err("acpi_install_notify_handler(%s) failed: %s\n",
801                                ibm->name, acpi_format_exception(status));
802                 }
803                 return -ENODEV;
804         }
805         ibm->flags.acpi_notify_installed = 1;
806         return 0;
807 }
808
809 static int __init tpacpi_device_add(struct acpi_device *device)
810 {
811         return 0;
812 }
813
814 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
815 {
816         int rc;
817
818         dbg_printk(TPACPI_DBG_INIT,
819                 "registering %s as an ACPI driver\n", ibm->name);
820
821         BUG_ON(!ibm->acpi);
822
823         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
824         if (!ibm->acpi->driver) {
825                 pr_err("failed to allocate memory for ibm->acpi->driver\n");
826                 return -ENOMEM;
827         }
828
829         sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name);
830         ibm->acpi->driver->ids = ibm->acpi->hid;
831
832         ibm->acpi->driver->ops.add = &tpacpi_device_add;
833
834         rc = acpi_bus_register_driver(ibm->acpi->driver);
835         if (rc < 0) {
836                 pr_err("acpi_bus_register_driver(%s) failed: %d\n",
837                        ibm->name, rc);
838                 kfree(ibm->acpi->driver);
839                 ibm->acpi->driver = NULL;
840         } else if (!rc)
841                 ibm->flags.acpi_driver_registered = 1;
842
843         return rc;
844 }
845
846
847 /****************************************************************************
848  ****************************************************************************
849  *
850  * Procfs Helpers
851  *
852  ****************************************************************************
853  ****************************************************************************/
854
855 static int dispatch_proc_show(struct seq_file *m, void *v)
856 {
857         struct ibm_struct *ibm = m->private;
858
859         if (!ibm || !ibm->read)
860                 return -EINVAL;
861         return ibm->read(m);
862 }
863
864 static int dispatch_proc_open(struct inode *inode, struct file *file)
865 {
866         return single_open(file, dispatch_proc_show, PDE_DATA(inode));
867 }
868
869 static ssize_t dispatch_proc_write(struct file *file,
870                         const char __user *userbuf,
871                         size_t count, loff_t *pos)
872 {
873         struct ibm_struct *ibm = PDE_DATA(file_inode(file));
874         char *kernbuf;
875         int ret;
876
877         if (!ibm || !ibm->write)
878                 return -EINVAL;
879         if (count > PAGE_SIZE - 2)
880                 return -EINVAL;
881
882         kernbuf = kmalloc(count + 2, GFP_KERNEL);
883         if (!kernbuf)
884                 return -ENOMEM;
885
886         if (copy_from_user(kernbuf, userbuf, count)) {
887                 kfree(kernbuf);
888                 return -EFAULT;
889         }
890
891         kernbuf[count] = 0;
892         strcat(kernbuf, ",");
893         ret = ibm->write(kernbuf);
894         if (ret == 0)
895                 ret = count;
896
897         kfree(kernbuf);
898
899         return ret;
900 }
901
902 static const struct file_operations dispatch_proc_fops = {
903         .owner          = THIS_MODULE,
904         .open           = dispatch_proc_open,
905         .read           = seq_read,
906         .llseek         = seq_lseek,
907         .release        = single_release,
908         .write          = dispatch_proc_write,
909 };
910
911 static char *next_cmd(char **cmds)
912 {
913         char *start = *cmds;
914         char *end;
915
916         while ((end = strchr(start, ',')) && end == start)
917                 start = end + 1;
918
919         if (!end)
920                 return NULL;
921
922         *end = 0;
923         *cmds = end + 1;
924         return start;
925 }
926
927
928 /****************************************************************************
929  ****************************************************************************
930  *
931  * Device model: input, hwmon and platform
932  *
933  ****************************************************************************
934  ****************************************************************************/
935
936 static struct platform_device *tpacpi_pdev;
937 static struct platform_device *tpacpi_sensors_pdev;
938 static struct device *tpacpi_hwmon;
939 static struct input_dev *tpacpi_inputdev;
940 static struct mutex tpacpi_inputdev_send_mutex;
941 static LIST_HEAD(tpacpi_all_drivers);
942
943 #ifdef CONFIG_PM_SLEEP
944 static int tpacpi_suspend_handler(struct device *dev)
945 {
946         struct ibm_struct *ibm, *itmp;
947
948         list_for_each_entry_safe(ibm, itmp,
949                                  &tpacpi_all_drivers,
950                                  all_drivers) {
951                 if (ibm->suspend)
952                         (ibm->suspend)();
953         }
954
955         return 0;
956 }
957
958 static int tpacpi_resume_handler(struct device *dev)
959 {
960         struct ibm_struct *ibm, *itmp;
961
962         list_for_each_entry_safe(ibm, itmp,
963                                  &tpacpi_all_drivers,
964                                  all_drivers) {
965                 if (ibm->resume)
966                         (ibm->resume)();
967         }
968
969         return 0;
970 }
971 #endif
972
973 static SIMPLE_DEV_PM_OPS(tpacpi_pm,
974                          tpacpi_suspend_handler, tpacpi_resume_handler);
975
976 static void tpacpi_shutdown_handler(struct platform_device *pdev)
977 {
978         struct ibm_struct *ibm, *itmp;
979
980         list_for_each_entry_safe(ibm, itmp,
981                                  &tpacpi_all_drivers,
982                                  all_drivers) {
983                 if (ibm->shutdown)
984                         (ibm->shutdown)();
985         }
986 }
987
988 static struct platform_driver tpacpi_pdriver = {
989         .driver = {
990                 .name = TPACPI_DRVR_NAME,
991                 .pm = &tpacpi_pm,
992         },
993         .shutdown = tpacpi_shutdown_handler,
994 };
995
996 static struct platform_driver tpacpi_hwmon_pdriver = {
997         .driver = {
998                 .name = TPACPI_HWMON_DRVR_NAME,
999         },
1000 };
1001
1002 /*************************************************************************
1003  * sysfs support helpers
1004  */
1005
1006 struct attribute_set {
1007         unsigned int members, max_members;
1008         struct attribute_group group;
1009 };
1010
1011 struct attribute_set_obj {
1012         struct attribute_set s;
1013         struct attribute *a;
1014 } __attribute__((packed));
1015
1016 static struct attribute_set *create_attr_set(unsigned int max_members,
1017                                                 const char *name)
1018 {
1019         struct attribute_set_obj *sobj;
1020
1021         if (max_members == 0)
1022                 return NULL;
1023
1024         /* Allocates space for implicit NULL at the end too */
1025         sobj = kzalloc(sizeof(struct attribute_set_obj) +
1026                     max_members * sizeof(struct attribute *),
1027                     GFP_KERNEL);
1028         if (!sobj)
1029                 return NULL;
1030         sobj->s.max_members = max_members;
1031         sobj->s.group.attrs = &sobj->a;
1032         sobj->s.group.name = name;
1033
1034         return &sobj->s;
1035 }
1036
1037 #define destroy_attr_set(_set) \
1038         kfree(_set);
1039
1040 /* not multi-threaded safe, use it in a single thread per set */
1041 static int add_to_attr_set(struct attribute_set *s, struct attribute *attr)
1042 {
1043         if (!s || !attr)
1044                 return -EINVAL;
1045
1046         if (s->members >= s->max_members)
1047                 return -ENOMEM;
1048
1049         s->group.attrs[s->members] = attr;
1050         s->members++;
1051
1052         return 0;
1053 }
1054
1055 static int add_many_to_attr_set(struct attribute_set *s,
1056                         struct attribute **attr,
1057                         unsigned int count)
1058 {
1059         int i, res;
1060
1061         for (i = 0; i < count; i++) {
1062                 res = add_to_attr_set(s, attr[i]);
1063                 if (res)
1064                         return res;
1065         }
1066
1067         return 0;
1068 }
1069
1070 static void delete_attr_set(struct attribute_set *s, struct kobject *kobj)
1071 {
1072         sysfs_remove_group(kobj, &s->group);
1073         destroy_attr_set(s);
1074 }
1075
1076 #define register_attr_set_with_sysfs(_attr_set, _kobj) \
1077         sysfs_create_group(_kobj, &_attr_set->group)
1078
1079 static int parse_strtoul(const char *buf,
1080                 unsigned long max, unsigned long *value)
1081 {
1082         char *endp;
1083
1084         *value = simple_strtoul(skip_spaces(buf), &endp, 0);
1085         endp = skip_spaces(endp);
1086         if (*endp || *value > max)
1087                 return -EINVAL;
1088
1089         return 0;
1090 }
1091
1092 static void tpacpi_disable_brightness_delay(void)
1093 {
1094         if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0))
1095                 pr_notice("ACPI backlight control delay disabled\n");
1096 }
1097
1098 static void printk_deprecated_attribute(const char * const what,
1099                                         const char * const details)
1100 {
1101         tpacpi_log_usertask("deprecated sysfs attribute");
1102         pr_warn("WARNING: sysfs attribute %s is deprecated and will be removed. %s\n",
1103                 what, details);
1104 }
1105
1106 /*************************************************************************
1107  * rfkill and radio control support helpers
1108  */
1109
1110 /*
1111  * ThinkPad-ACPI firmware handling model:
1112  *
1113  * WLSW (master wireless switch) is event-driven, and is common to all
1114  * firmware-controlled radios.  It cannot be controlled, just monitored,
1115  * as expected.  It overrides all radio state in firmware
1116  *
1117  * The kernel, a masked-off hotkey, and WLSW can change the radio state
1118  * (TODO: verify how WLSW interacts with the returned radio state).
1119  *
1120  * The only time there are shadow radio state changes, is when
1121  * masked-off hotkeys are used.
1122  */
1123
1124 /*
1125  * Internal driver API for radio state:
1126  *
1127  * int: < 0 = error, otherwise enum tpacpi_rfkill_state
1128  * bool: true means radio blocked (off)
1129  */
1130 enum tpacpi_rfkill_state {
1131         TPACPI_RFK_RADIO_OFF = 0,
1132         TPACPI_RFK_RADIO_ON
1133 };
1134
1135 /* rfkill switches */
1136 enum tpacpi_rfk_id {
1137         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
1138         TPACPI_RFK_WWAN_SW_ID,
1139         TPACPI_RFK_UWB_SW_ID,
1140         TPACPI_RFK_SW_MAX
1141 };
1142
1143 static const char *tpacpi_rfkill_names[] = {
1144         [TPACPI_RFK_BLUETOOTH_SW_ID] = "bluetooth",
1145         [TPACPI_RFK_WWAN_SW_ID] = "wwan",
1146         [TPACPI_RFK_UWB_SW_ID] = "uwb",
1147         [TPACPI_RFK_SW_MAX] = NULL
1148 };
1149
1150 /* ThinkPad-ACPI rfkill subdriver */
1151 struct tpacpi_rfk {
1152         struct rfkill *rfkill;
1153         enum tpacpi_rfk_id id;
1154         const struct tpacpi_rfk_ops *ops;
1155 };
1156
1157 struct tpacpi_rfk_ops {
1158         /* firmware interface */
1159         int (*get_status)(void);
1160         int (*set_status)(const enum tpacpi_rfkill_state);
1161 };
1162
1163 static struct tpacpi_rfk *tpacpi_rfkill_switches[TPACPI_RFK_SW_MAX];
1164
1165 /* Query FW and update rfkill sw state for a given rfkill switch */
1166 static int tpacpi_rfk_update_swstate(const struct tpacpi_rfk *tp_rfk)
1167 {
1168         int status;
1169
1170         if (!tp_rfk)
1171                 return -ENODEV;
1172
1173         status = (tp_rfk->ops->get_status)();
1174         if (status < 0)
1175                 return status;
1176
1177         rfkill_set_sw_state(tp_rfk->rfkill,
1178                             (status == TPACPI_RFK_RADIO_OFF));
1179
1180         return status;
1181 }
1182
1183 /* Query FW and update rfkill sw state for all rfkill switches */
1184 static void tpacpi_rfk_update_swstate_all(void)
1185 {
1186         unsigned int i;
1187
1188         for (i = 0; i < TPACPI_RFK_SW_MAX; i++)
1189                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[i]);
1190 }
1191
1192 /*
1193  * Sync the HW-blocking state of all rfkill switches,
1194  * do notice it causes the rfkill core to schedule uevents
1195  */
1196 static void tpacpi_rfk_update_hwblock_state(bool blocked)
1197 {
1198         unsigned int i;
1199         struct tpacpi_rfk *tp_rfk;
1200
1201         for (i = 0; i < TPACPI_RFK_SW_MAX; i++) {
1202                 tp_rfk = tpacpi_rfkill_switches[i];
1203                 if (tp_rfk) {
1204                         if (rfkill_set_hw_state(tp_rfk->rfkill,
1205                                                 blocked)) {
1206                                 /* ignore -- we track sw block */
1207                         }
1208                 }
1209         }
1210 }
1211
1212 /* Call to get the WLSW state from the firmware */
1213 static int hotkey_get_wlsw(void);
1214
1215 /* Call to query WLSW state and update all rfkill switches */
1216 static bool tpacpi_rfk_check_hwblock_state(void)
1217 {
1218         int res = hotkey_get_wlsw();
1219         int hw_blocked;
1220
1221         /* When unknown or unsupported, we have to assume it is unblocked */
1222         if (res < 0)
1223                 return false;
1224
1225         hw_blocked = (res == TPACPI_RFK_RADIO_OFF);
1226         tpacpi_rfk_update_hwblock_state(hw_blocked);
1227
1228         return hw_blocked;
1229 }
1230
1231 static int tpacpi_rfk_hook_set_block(void *data, bool blocked)
1232 {
1233         struct tpacpi_rfk *tp_rfk = data;
1234         int res;
1235
1236         dbg_printk(TPACPI_DBG_RFKILL,
1237                    "request to change radio state to %s\n",
1238                    blocked ? "blocked" : "unblocked");
1239
1240         /* try to set radio state */
1241         res = (tp_rfk->ops->set_status)(blocked ?
1242                                 TPACPI_RFK_RADIO_OFF : TPACPI_RFK_RADIO_ON);
1243
1244         /* and update the rfkill core with whatever the FW really did */
1245         tpacpi_rfk_update_swstate(tp_rfk);
1246
1247         return (res < 0) ? res : 0;
1248 }
1249
1250 static const struct rfkill_ops tpacpi_rfk_rfkill_ops = {
1251         .set_block = tpacpi_rfk_hook_set_block,
1252 };
1253
1254 static int __init tpacpi_new_rfkill(const enum tpacpi_rfk_id id,
1255                         const struct tpacpi_rfk_ops *tp_rfkops,
1256                         const enum rfkill_type rfktype,
1257                         const char *name,
1258                         const bool set_default)
1259 {
1260         struct tpacpi_rfk *atp_rfk;
1261         int res;
1262         bool sw_state = false;
1263         bool hw_state;
1264         int sw_status;
1265
1266         BUG_ON(id >= TPACPI_RFK_SW_MAX || tpacpi_rfkill_switches[id]);
1267
1268         atp_rfk = kzalloc(sizeof(struct tpacpi_rfk), GFP_KERNEL);
1269         if (atp_rfk)
1270                 atp_rfk->rfkill = rfkill_alloc(name,
1271                                                 &tpacpi_pdev->dev,
1272                                                 rfktype,
1273                                                 &tpacpi_rfk_rfkill_ops,
1274                                                 atp_rfk);
1275         if (!atp_rfk || !atp_rfk->rfkill) {
1276                 pr_err("failed to allocate memory for rfkill class\n");
1277                 kfree(atp_rfk);
1278                 return -ENOMEM;
1279         }
1280
1281         atp_rfk->id = id;
1282         atp_rfk->ops = tp_rfkops;
1283
1284         sw_status = (tp_rfkops->get_status)();
1285         if (sw_status < 0) {
1286                 pr_err("failed to read initial state for %s, error %d\n",
1287                        name, sw_status);
1288         } else {
1289                 sw_state = (sw_status == TPACPI_RFK_RADIO_OFF);
1290                 if (set_default) {
1291                         /* try to keep the initial state, since we ask the
1292                          * firmware to preserve it across S5 in NVRAM */
1293                         rfkill_init_sw_state(atp_rfk->rfkill, sw_state);
1294                 }
1295         }
1296         hw_state = tpacpi_rfk_check_hwblock_state();
1297         rfkill_set_hw_state(atp_rfk->rfkill, hw_state);
1298
1299         res = rfkill_register(atp_rfk->rfkill);
1300         if (res < 0) {
1301                 pr_err("failed to register %s rfkill switch: %d\n", name, res);
1302                 rfkill_destroy(atp_rfk->rfkill);
1303                 kfree(atp_rfk);
1304                 return res;
1305         }
1306
1307         tpacpi_rfkill_switches[id] = atp_rfk;
1308
1309         pr_info("rfkill switch %s: radio is %sblocked\n",
1310                 name, (sw_state || hw_state) ? "" : "un");
1311         return 0;
1312 }
1313
1314 static void tpacpi_destroy_rfkill(const enum tpacpi_rfk_id id)
1315 {
1316         struct tpacpi_rfk *tp_rfk;
1317
1318         BUG_ON(id >= TPACPI_RFK_SW_MAX);
1319
1320         tp_rfk = tpacpi_rfkill_switches[id];
1321         if (tp_rfk) {
1322                 rfkill_unregister(tp_rfk->rfkill);
1323                 rfkill_destroy(tp_rfk->rfkill);
1324                 tpacpi_rfkill_switches[id] = NULL;
1325                 kfree(tp_rfk);
1326         }
1327 }
1328
1329 static void printk_deprecated_rfkill_attribute(const char * const what)
1330 {
1331         printk_deprecated_attribute(what,
1332                         "Please switch to generic rfkill before year 2010");
1333 }
1334
1335 /* sysfs <radio> enable ------------------------------------------------ */
1336 static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id,
1337                                             struct device_attribute *attr,
1338                                             char *buf)
1339 {
1340         int status;
1341
1342         printk_deprecated_rfkill_attribute(attr->attr.name);
1343
1344         /* This is in the ABI... */
1345         if (tpacpi_rfk_check_hwblock_state()) {
1346                 status = TPACPI_RFK_RADIO_OFF;
1347         } else {
1348                 status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1349                 if (status < 0)
1350                         return status;
1351         }
1352
1353         return snprintf(buf, PAGE_SIZE, "%d\n",
1354                         (status == TPACPI_RFK_RADIO_ON) ? 1 : 0);
1355 }
1356
1357 static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id,
1358                             struct device_attribute *attr,
1359                             const char *buf, size_t count)
1360 {
1361         unsigned long t;
1362         int res;
1363
1364         printk_deprecated_rfkill_attribute(attr->attr.name);
1365
1366         if (parse_strtoul(buf, 1, &t))
1367                 return -EINVAL;
1368
1369         tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t);
1370
1371         /* This is in the ABI... */
1372         if (tpacpi_rfk_check_hwblock_state() && !!t)
1373                 return -EPERM;
1374
1375         res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ?
1376                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF);
1377         tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1378
1379         return (res < 0) ? res : count;
1380 }
1381
1382 /* procfs -------------------------------------------------------------- */
1383 static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, struct seq_file *m)
1384 {
1385         if (id >= TPACPI_RFK_SW_MAX)
1386                 seq_printf(m, "status:\t\tnot supported\n");
1387         else {
1388                 int status;
1389
1390                 /* This is in the ABI... */
1391                 if (tpacpi_rfk_check_hwblock_state()) {
1392                         status = TPACPI_RFK_RADIO_OFF;
1393                 } else {
1394                         status = tpacpi_rfk_update_swstate(
1395                                                 tpacpi_rfkill_switches[id]);
1396                         if (status < 0)
1397                                 return status;
1398                 }
1399
1400                 seq_printf(m, "status:\t\t%s\n",
1401                                 (status == TPACPI_RFK_RADIO_ON) ?
1402                                         "enabled" : "disabled");
1403                 seq_printf(m, "commands:\tenable, disable\n");
1404         }
1405
1406         return 0;
1407 }
1408
1409 static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf)
1410 {
1411         char *cmd;
1412         int status = -1;
1413         int res = 0;
1414
1415         if (id >= TPACPI_RFK_SW_MAX)
1416                 return -ENODEV;
1417
1418         while ((cmd = next_cmd(&buf))) {
1419                 if (strlencmp(cmd, "enable") == 0)
1420                         status = TPACPI_RFK_RADIO_ON;
1421                 else if (strlencmp(cmd, "disable") == 0)
1422                         status = TPACPI_RFK_RADIO_OFF;
1423                 else
1424                         return -EINVAL;
1425         }
1426
1427         if (status != -1) {
1428                 tpacpi_disclose_usertask("procfs", "attempt to %s %s\n",
1429                                 (status == TPACPI_RFK_RADIO_ON) ?
1430                                                 "enable" : "disable",
1431                                 tpacpi_rfkill_names[id]);
1432                 res = (tpacpi_rfkill_switches[id]->ops->set_status)(status);
1433                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1434         }
1435
1436         return res;
1437 }
1438
1439 /*************************************************************************
1440  * thinkpad-acpi driver attributes
1441  */
1442
1443 /* interface_version --------------------------------------------------- */
1444 static ssize_t interface_version_show(struct device_driver *drv, char *buf)
1445 {
1446         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
1447 }
1448 static DRIVER_ATTR_RO(interface_version);
1449
1450 /* debug_level --------------------------------------------------------- */
1451 static ssize_t debug_level_show(struct device_driver *drv, char *buf)
1452 {
1453         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
1454 }
1455
1456 static ssize_t debug_level_store(struct device_driver *drv, const char *buf,
1457                                  size_t count)
1458 {
1459         unsigned long t;
1460
1461         if (parse_strtoul(buf, 0xffff, &t))
1462                 return -EINVAL;
1463
1464         dbg_level = t;
1465
1466         return count;
1467 }
1468 static DRIVER_ATTR_RW(debug_level);
1469
1470 /* version ------------------------------------------------------------- */
1471 static ssize_t version_show(struct device_driver *drv, char *buf)
1472 {
1473         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1474                         TPACPI_DESC, TPACPI_VERSION);
1475 }
1476 static DRIVER_ATTR_RO(version);
1477
1478 /* --------------------------------------------------------------------- */
1479
1480 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1481
1482 /* wlsw_emulstate ------------------------------------------------------ */
1483 static ssize_t wlsw_emulstate_show(struct device_driver *drv, char *buf)
1484 {
1485         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate);
1486 }
1487
1488 static ssize_t wlsw_emulstate_store(struct device_driver *drv, const char *buf,
1489                                     size_t count)
1490 {
1491         unsigned long t;
1492
1493         if (parse_strtoul(buf, 1, &t))
1494                 return -EINVAL;
1495
1496         if (tpacpi_wlsw_emulstate != !!t) {
1497                 tpacpi_wlsw_emulstate = !!t;
1498                 tpacpi_rfk_update_hwblock_state(!t);    /* negative logic */
1499         }
1500
1501         return count;
1502 }
1503 static DRIVER_ATTR_RW(wlsw_emulstate);
1504
1505 /* bluetooth_emulstate ------------------------------------------------- */
1506 static ssize_t bluetooth_emulstate_show(struct device_driver *drv, char *buf)
1507 {
1508         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate);
1509 }
1510
1511 static ssize_t bluetooth_emulstate_store(struct device_driver *drv,
1512                                          const char *buf, size_t count)
1513 {
1514         unsigned long t;
1515
1516         if (parse_strtoul(buf, 1, &t))
1517                 return -EINVAL;
1518
1519         tpacpi_bluetooth_emulstate = !!t;
1520
1521         return count;
1522 }
1523 static DRIVER_ATTR_RW(bluetooth_emulstate);
1524
1525 /* wwan_emulstate ------------------------------------------------- */
1526 static ssize_t wwan_emulstate_show(struct device_driver *drv, char *buf)
1527 {
1528         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate);
1529 }
1530
1531 static ssize_t wwan_emulstate_store(struct device_driver *drv, const char *buf,
1532                                     size_t count)
1533 {
1534         unsigned long t;
1535
1536         if (parse_strtoul(buf, 1, &t))
1537                 return -EINVAL;
1538
1539         tpacpi_wwan_emulstate = !!t;
1540
1541         return count;
1542 }
1543 static DRIVER_ATTR_RW(wwan_emulstate);
1544
1545 /* uwb_emulstate ------------------------------------------------- */
1546 static ssize_t uwb_emulstate_show(struct device_driver *drv, char *buf)
1547 {
1548         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate);
1549 }
1550
1551 static ssize_t uwb_emulstate_store(struct device_driver *drv, const char *buf,
1552                                    size_t count)
1553 {
1554         unsigned long t;
1555
1556         if (parse_strtoul(buf, 1, &t))
1557                 return -EINVAL;
1558
1559         tpacpi_uwb_emulstate = !!t;
1560
1561         return count;
1562 }
1563 static DRIVER_ATTR_RW(uwb_emulstate);
1564 #endif
1565
1566 /* --------------------------------------------------------------------- */
1567
1568 static struct driver_attribute *tpacpi_driver_attributes[] = {
1569         &driver_attr_debug_level, &driver_attr_version,
1570         &driver_attr_interface_version,
1571 };
1572
1573 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1574 {
1575         int i, res;
1576
1577         i = 0;
1578         res = 0;
1579         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1580                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1581                 i++;
1582         }
1583
1584 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1585         if (!res && dbg_wlswemul)
1586                 res = driver_create_file(drv, &driver_attr_wlsw_emulstate);
1587         if (!res && dbg_bluetoothemul)
1588                 res = driver_create_file(drv, &driver_attr_bluetooth_emulstate);
1589         if (!res && dbg_wwanemul)
1590                 res = driver_create_file(drv, &driver_attr_wwan_emulstate);
1591         if (!res && dbg_uwbemul)
1592                 res = driver_create_file(drv, &driver_attr_uwb_emulstate);
1593 #endif
1594
1595         return res;
1596 }
1597
1598 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1599 {
1600         int i;
1601
1602         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1603                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1604
1605 #ifdef THINKPAD_ACPI_DEBUGFACILITIES
1606         driver_remove_file(drv, &driver_attr_wlsw_emulstate);
1607         driver_remove_file(drv, &driver_attr_bluetooth_emulstate);
1608         driver_remove_file(drv, &driver_attr_wwan_emulstate);
1609         driver_remove_file(drv, &driver_attr_uwb_emulstate);
1610 #endif
1611 }
1612
1613 /*************************************************************************
1614  * Firmware Data
1615  */
1616
1617 /*
1618  * Table of recommended minimum BIOS versions
1619  *
1620  * Reasons for listing:
1621  *    1. Stable BIOS, listed because the unknown amount of
1622  *       bugs and bad ACPI behaviour on older versions
1623  *
1624  *    2. BIOS or EC fw with known bugs that trigger on Linux
1625  *
1626  *    3. BIOS with known reduced functionality in older versions
1627  *
1628  *  We recommend the latest BIOS and EC version.
1629  *  We only support the latest BIOS and EC fw version as a rule.
1630  *
1631  *  Sources: IBM ThinkPad Public Web Documents (update changelogs),
1632  *  Information from users in ThinkWiki
1633  *
1634  *  WARNING: we use this table also to detect that the machine is
1635  *  a ThinkPad in some cases, so don't remove entries lightly.
1636  */
1637
1638 #define TPV_Q(__v, __id1, __id2, __bv1, __bv2)          \
1639         { .vendor       = (__v),                        \
1640           .bios         = TPID(__id1, __id2),           \
1641           .ec           = TPACPI_MATCH_ANY,             \
1642           .quirks       = TPACPI_MATCH_ANY << 16        \
1643                           | (__bv1) << 8 | (__bv2) }
1644
1645 #define TPV_Q_X(__v, __bid1, __bid2, __bv1, __bv2,      \
1646                 __eid, __ev1, __ev2)                    \
1647         { .vendor       = (__v),                        \
1648           .bios         = TPID(__bid1, __bid2),         \
1649           .ec           = __eid,                        \
1650           .quirks       = (__ev1) << 24 | (__ev2) << 16 \
1651                           | (__bv1) << 8 | (__bv2) }
1652
1653 #define TPV_QI0(__id1, __id2, __bv1, __bv2) \
1654         TPV_Q(PCI_VENDOR_ID_IBM, __id1, __id2, __bv1, __bv2)
1655
1656 /* Outdated IBM BIOSes often lack the EC id string */
1657 #define TPV_QI1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1658         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1659                 __bv1, __bv2, TPID(__id1, __id2),       \
1660                 __ev1, __ev2),                          \
1661         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1662                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1663                 __ev1, __ev2)
1664
1665 /* Outdated IBM BIOSes often lack the EC id string */
1666 #define TPV_QI2(__bid1, __bid2, __bv1, __bv2,           \
1667                 __eid1, __eid2, __ev1, __ev2)           \
1668         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1669                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1670                 __ev1, __ev2),                          \
1671         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1672                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1673                 __ev1, __ev2)
1674
1675 #define TPV_QL0(__id1, __id2, __bv1, __bv2) \
1676         TPV_Q(PCI_VENDOR_ID_LENOVO, __id1, __id2, __bv1, __bv2)
1677
1678 #define TPV_QL1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1679         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __id1, __id2,     \
1680                 __bv1, __bv2, TPID(__id1, __id2),       \
1681                 __ev1, __ev2)
1682
1683 #define TPV_QL2(__bid1, __bid2, __bv1, __bv2,           \
1684                 __eid1, __eid2, __ev1, __ev2)           \
1685         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __bid1, __bid2,   \
1686                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1687                 __ev1, __ev2)
1688
1689 static const struct tpacpi_quirk tpacpi_bios_version_qtable[] __initconst = {
1690         /*  Numeric models ------------------ */
1691         /*      FW MODEL   BIOS VERS          */
1692         TPV_QI0('I', 'M',  '6', '5'),            /* 570 */
1693         TPV_QI0('I', 'U',  '2', '6'),            /* 570E */
1694         TPV_QI0('I', 'B',  '5', '4'),            /* 600 */
1695         TPV_QI0('I', 'H',  '4', '7'),            /* 600E */
1696         TPV_QI0('I', 'N',  '3', '6'),            /* 600E */
1697         TPV_QI0('I', 'T',  '5', '5'),            /* 600X */
1698         TPV_QI0('I', 'D',  '4', '8'),            /* 770, 770E, 770ED */
1699         TPV_QI0('I', 'I',  '4', '2'),            /* 770X */
1700         TPV_QI0('I', 'O',  '2', '3'),            /* 770Z */
1701
1702         /* A-series ------------------------- */
1703         /*      FW MODEL   BIOS VERS  EC VERS */
1704         TPV_QI0('I', 'W',  '5', '9'),            /* A20m */
1705         TPV_QI0('I', 'V',  '6', '9'),            /* A20p */
1706         TPV_QI0('1', '0',  '2', '6'),            /* A21e, A22e */
1707         TPV_QI0('K', 'U',  '3', '6'),            /* A21e */
1708         TPV_QI0('K', 'X',  '3', '6'),            /* A21m, A22m */
1709         TPV_QI0('K', 'Y',  '3', '8'),            /* A21p, A22p */
1710         TPV_QI0('1', 'B',  '1', '7'),            /* A22e */
1711         TPV_QI0('1', '3',  '2', '0'),            /* A22m */
1712         TPV_QI0('1', 'E',  '7', '3'),            /* A30/p (0) */
1713         TPV_QI1('1', 'G',  '4', '1',  '1', '7'), /* A31/p (0) */
1714         TPV_QI1('1', 'N',  '1', '6',  '0', '7'), /* A31/p (0) */
1715
1716         /* G-series ------------------------- */
1717         /*      FW MODEL   BIOS VERS          */
1718         TPV_QI0('1', 'T',  'A', '6'),            /* G40 */
1719         TPV_QI0('1', 'X',  '5', '7'),            /* G41 */
1720
1721         /* R-series, T-series --------------- */
1722         /*      FW MODEL   BIOS VERS  EC VERS */
1723         TPV_QI0('1', 'C',  'F', '0'),            /* R30 */
1724         TPV_QI0('1', 'F',  'F', '1'),            /* R31 */
1725         TPV_QI0('1', 'M',  '9', '7'),            /* R32 */
1726         TPV_QI0('1', 'O',  '6', '1'),            /* R40 */
1727         TPV_QI0('1', 'P',  '6', '5'),            /* R40 */
1728         TPV_QI0('1', 'S',  '7', '0'),            /* R40e */
1729         TPV_QI1('1', 'R',  'D', 'R',  '7', '1'), /* R50/p, R51,
1730                                                     T40/p, T41/p, T42/p (1) */
1731         TPV_QI1('1', 'V',  '7', '1',  '2', '8'), /* R50e, R51 (1) */
1732         TPV_QI1('7', '8',  '7', '1',  '0', '6'), /* R51e (1) */
1733         TPV_QI1('7', '6',  '6', '9',  '1', '6'), /* R52 (1) */
1734         TPV_QI1('7', '0',  '6', '9',  '2', '8'), /* R52, T43 (1) */
1735
1736         TPV_QI0('I', 'Y',  '6', '1'),            /* T20 */
1737         TPV_QI0('K', 'Z',  '3', '4'),            /* T21 */
1738         TPV_QI0('1', '6',  '3', '2'),            /* T22 */
1739         TPV_QI1('1', 'A',  '6', '4',  '2', '3'), /* T23 (0) */
1740         TPV_QI1('1', 'I',  '7', '1',  '2', '0'), /* T30 (0) */
1741         TPV_QI1('1', 'Y',  '6', '5',  '2', '9'), /* T43/p (1) */
1742
1743         TPV_QL1('7', '9',  'E', '3',  '5', '0'), /* T60/p */
1744         TPV_QL1('7', 'C',  'D', '2',  '2', '2'), /* R60, R60i */
1745         TPV_QL1('7', 'E',  'D', '0',  '1', '5'), /* R60e, R60i */
1746
1747         /*      BIOS FW    BIOS VERS  EC FW     EC VERS */
1748         TPV_QI2('1', 'W',  '9', '0',  '1', 'V', '2', '8'), /* R50e (1) */
1749         TPV_QL2('7', 'I',  '3', '4',  '7', '9', '5', '0'), /* T60/p wide */
1750
1751         /* X-series ------------------------- */
1752         /*      FW MODEL   BIOS VERS  EC VERS */
1753         TPV_QI0('I', 'Z',  '9', 'D'),            /* X20, X21 */
1754         TPV_QI0('1', 'D',  '7', '0'),            /* X22, X23, X24 */
1755         TPV_QI1('1', 'K',  '4', '8',  '1', '8'), /* X30 (0) */
1756         TPV_QI1('1', 'Q',  '9', '7',  '2', '3'), /* X31, X32 (0) */
1757         TPV_QI1('1', 'U',  'D', '3',  'B', '2'), /* X40 (0) */
1758         TPV_QI1('7', '4',  '6', '4',  '2', '7'), /* X41 (0) */
1759         TPV_QI1('7', '5',  '6', '0',  '2', '0'), /* X41t (0) */
1760
1761         TPV_QL1('7', 'B',  'D', '7',  '4', '0'), /* X60/s */
1762         TPV_QL1('7', 'J',  '3', '0',  '1', '3'), /* X60t */
1763
1764         /* (0) - older versions lack DMI EC fw string and functionality */
1765         /* (1) - older versions known to lack functionality */
1766 };
1767
1768 #undef TPV_QL1
1769 #undef TPV_QL0
1770 #undef TPV_QI2
1771 #undef TPV_QI1
1772 #undef TPV_QI0
1773 #undef TPV_Q_X
1774 #undef TPV_Q
1775
1776 static void __init tpacpi_check_outdated_fw(void)
1777 {
1778         unsigned long fwvers;
1779         u16 ec_version, bios_version;
1780
1781         fwvers = tpacpi_check_quirks(tpacpi_bios_version_qtable,
1782                                 ARRAY_SIZE(tpacpi_bios_version_qtable));
1783
1784         if (!fwvers)
1785                 return;
1786
1787         bios_version = fwvers & 0xffffU;
1788         ec_version = (fwvers >> 16) & 0xffffU;
1789
1790         /* note that unknown versions are set to 0x0000 and we use that */
1791         if ((bios_version > thinkpad_id.bios_release) ||
1792             (ec_version > thinkpad_id.ec_release &&
1793                                 ec_version != TPACPI_MATCH_ANY)) {
1794                 /*
1795                  * The changelogs would let us track down the exact
1796                  * reason, but it is just too much of a pain to track
1797                  * it.  We only list BIOSes that are either really
1798                  * broken, or really stable to begin with, so it is
1799                  * best if the user upgrades the firmware anyway.
1800                  */
1801                 pr_warn("WARNING: Outdated ThinkPad BIOS/EC firmware\n");
1802                 pr_warn("WARNING: This firmware may be missing critical bug fixes and/or important features\n");
1803         }
1804 }
1805
1806 static bool __init tpacpi_is_fw_known(void)
1807 {
1808         return tpacpi_check_quirks(tpacpi_bios_version_qtable,
1809                         ARRAY_SIZE(tpacpi_bios_version_qtable)) != 0;
1810 }
1811
1812 /****************************************************************************
1813  ****************************************************************************
1814  *
1815  * Subdrivers
1816  *
1817  ****************************************************************************
1818  ****************************************************************************/
1819
1820 /*************************************************************************
1821  * thinkpad-acpi metadata subdriver
1822  */
1823
1824 static int thinkpad_acpi_driver_read(struct seq_file *m)
1825 {
1826         seq_printf(m, "driver:\t\t%s\n", TPACPI_DESC);
1827         seq_printf(m, "version:\t%s\n", TPACPI_VERSION);
1828         return 0;
1829 }
1830
1831 static struct ibm_struct thinkpad_acpi_driver_data = {
1832         .name = "driver",
1833         .read = thinkpad_acpi_driver_read,
1834 };
1835
1836 /*************************************************************************
1837  * Hotkey subdriver
1838  */
1839
1840 /*
1841  * ThinkPad firmware event model
1842  *
1843  * The ThinkPad firmware has two main event interfaces: normal ACPI
1844  * notifications (which follow the ACPI standard), and a private event
1845  * interface.
1846  *
1847  * The private event interface also issues events for the hotkeys.  As
1848  * the driver gained features, the event handling code ended up being
1849  * built around the hotkey subdriver.  This will need to be refactored
1850  * to a more formal event API eventually.
1851  *
1852  * Some "hotkeys" are actually supposed to be used as event reports,
1853  * such as "brightness has changed", "volume has changed", depending on
1854  * the ThinkPad model and how the firmware is operating.
1855  *
1856  * Unlike other classes, hotkey-class events have mask/unmask control on
1857  * non-ancient firmware.  However, how it behaves changes a lot with the
1858  * firmware model and version.
1859  */
1860
1861 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1862         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1863         TP_ACPI_HOTKEYSCAN_FNF2,
1864         TP_ACPI_HOTKEYSCAN_FNF3,
1865         TP_ACPI_HOTKEYSCAN_FNF4,
1866         TP_ACPI_HOTKEYSCAN_FNF5,
1867         TP_ACPI_HOTKEYSCAN_FNF6,
1868         TP_ACPI_HOTKEYSCAN_FNF7,
1869         TP_ACPI_HOTKEYSCAN_FNF8,
1870         TP_ACPI_HOTKEYSCAN_FNF9,
1871         TP_ACPI_HOTKEYSCAN_FNF10,
1872         TP_ACPI_HOTKEYSCAN_FNF11,
1873         TP_ACPI_HOTKEYSCAN_FNF12,
1874         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1875         TP_ACPI_HOTKEYSCAN_FNINSERT,
1876         TP_ACPI_HOTKEYSCAN_FNDELETE,
1877         TP_ACPI_HOTKEYSCAN_FNHOME,
1878         TP_ACPI_HOTKEYSCAN_FNEND,
1879         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1880         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1881         TP_ACPI_HOTKEYSCAN_FNSPACE,
1882         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1883         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1884         TP_ACPI_HOTKEYSCAN_MUTE,
1885         TP_ACPI_HOTKEYSCAN_THINKPAD,
1886         TP_ACPI_HOTKEYSCAN_UNK1,
1887         TP_ACPI_HOTKEYSCAN_UNK2,
1888         TP_ACPI_HOTKEYSCAN_UNK3,
1889         TP_ACPI_HOTKEYSCAN_UNK4,
1890         TP_ACPI_HOTKEYSCAN_UNK5,
1891         TP_ACPI_HOTKEYSCAN_UNK6,
1892         TP_ACPI_HOTKEYSCAN_UNK7,
1893         TP_ACPI_HOTKEYSCAN_UNK8,
1894
1895         /* Adaptive keyboard keycodes */
1896         TP_ACPI_HOTKEYSCAN_ADAPTIVE_START,
1897         TP_ACPI_HOTKEYSCAN_MUTE2        = TP_ACPI_HOTKEYSCAN_ADAPTIVE_START,
1898         TP_ACPI_HOTKEYSCAN_BRIGHTNESS_ZERO,
1899         TP_ACPI_HOTKEYSCAN_CLIPPING_TOOL,
1900         TP_ACPI_HOTKEYSCAN_CLOUD,
1901         TP_ACPI_HOTKEYSCAN_UNK9,
1902         TP_ACPI_HOTKEYSCAN_VOICE,
1903         TP_ACPI_HOTKEYSCAN_UNK10,
1904         TP_ACPI_HOTKEYSCAN_GESTURES,
1905         TP_ACPI_HOTKEYSCAN_UNK11,
1906         TP_ACPI_HOTKEYSCAN_UNK12,
1907         TP_ACPI_HOTKEYSCAN_UNK13,
1908         TP_ACPI_HOTKEYSCAN_CONFIG,
1909         TP_ACPI_HOTKEYSCAN_NEW_TAB,
1910         TP_ACPI_HOTKEYSCAN_RELOAD,
1911         TP_ACPI_HOTKEYSCAN_BACK,
1912         TP_ACPI_HOTKEYSCAN_MIC_DOWN,
1913         TP_ACPI_HOTKEYSCAN_MIC_UP,
1914         TP_ACPI_HOTKEYSCAN_MIC_CANCELLATION,
1915         TP_ACPI_HOTKEYSCAN_CAMERA_MODE,
1916         TP_ACPI_HOTKEYSCAN_ROTATE_DISPLAY,
1917
1918         /* Lenovo extended keymap, starting at 0x1300 */
1919         TP_ACPI_HOTKEYSCAN_EXTENDED_START,
1920         /* first new observed key (star, favorites) is 0x1311 */
1921         TP_ACPI_HOTKEYSCAN_STAR = 69,
1922         TP_ACPI_HOTKEYSCAN_CLIPPING_TOOL2,
1923         TP_ACPI_HOTKEYSCAN_UNK25,
1924         TP_ACPI_HOTKEYSCAN_BLUETOOTH,
1925         TP_ACPI_HOTKEYSCAN_KEYBOARD,
1926
1927         /* Hotkey keymap size */
1928         TPACPI_HOTKEY_MAP_LEN
1929 };
1930
1931 enum {  /* Keys/events available through NVRAM polling */
1932         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1933         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1934 };
1935
1936 enum {  /* Positions of some of the keys in hotkey masks */
1937         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1938         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1939         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1940         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1941         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1942         TP_ACPI_HKEY_KBD_LIGHT_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1943         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1944         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1945         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1946         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1947         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1948 };
1949
1950 enum {  /* NVRAM to ACPI HKEY group map */
1951         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1952                                           TP_ACPI_HKEY_ZOOM_MASK |
1953                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1954                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1955         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1956                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1957         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1958                                           TP_ACPI_HKEY_VOLDWN_MASK |
1959                                           TP_ACPI_HKEY_MUTE_MASK,
1960 };
1961
1962 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1963 struct tp_nvram_state {
1964        u16 thinkpad_toggle:1;
1965        u16 zoom_toggle:1;
1966        u16 display_toggle:1;
1967        u16 thinklight_toggle:1;
1968        u16 hibernate_toggle:1;
1969        u16 displayexp_toggle:1;
1970        u16 display_state:1;
1971        u16 brightness_toggle:1;
1972        u16 volume_toggle:1;
1973        u16 mute:1;
1974
1975        u8 brightness_level;
1976        u8 volume_level;
1977 };
1978
1979 /* kthread for the hotkey poller */
1980 static struct task_struct *tpacpi_hotkey_task;
1981
1982 /*
1983  * Acquire mutex to write poller control variables as an
1984  * atomic block.
1985  *
1986  * Increment hotkey_config_change when changing them if you
1987  * want the kthread to forget old state.
1988  *
1989  * See HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
1990  */
1991 static struct mutex hotkey_thread_data_mutex;
1992 static unsigned int hotkey_config_change;
1993
1994 /*
1995  * hotkey poller control variables
1996  *
1997  * Must be atomic or readers will also need to acquire mutex
1998  *
1999  * HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
2000  * should be used only when the changes need to be taken as
2001  * a block, OR when one needs to force the kthread to forget
2002  * old state.
2003  */
2004 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
2005 static unsigned int hotkey_poll_freq = 10; /* Hz */
2006
2007 #define HOTKEY_CONFIG_CRITICAL_START \
2008         do { \
2009                 mutex_lock(&hotkey_thread_data_mutex); \
2010                 hotkey_config_change++; \
2011         } while (0);
2012 #define HOTKEY_CONFIG_CRITICAL_END \
2013         mutex_unlock(&hotkey_thread_data_mutex);
2014
2015 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2016
2017 #define hotkey_source_mask 0U
2018 #define HOTKEY_CONFIG_CRITICAL_START
2019 #define HOTKEY_CONFIG_CRITICAL_END
2020
2021 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2022
2023 static struct mutex hotkey_mutex;
2024
2025 static enum {   /* Reasons for waking up */
2026         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
2027         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
2028         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
2029 } hotkey_wakeup_reason;
2030
2031 static int hotkey_autosleep_ack;
2032
2033 static u32 hotkey_orig_mask;            /* events the BIOS had enabled */
2034 static u32 hotkey_all_mask;             /* all events supported in fw */
2035 static u32 hotkey_adaptive_all_mask;    /* all adaptive events supported in fw */
2036 static u32 hotkey_reserved_mask;        /* events better left disabled */
2037 static u32 hotkey_driver_mask;          /* events needed by the driver */
2038 static u32 hotkey_user_mask;            /* events visible to userspace */
2039 static u32 hotkey_acpi_mask;            /* events enabled in firmware */
2040
2041 static u16 *hotkey_keycode_map;
2042
2043 static struct attribute_set *hotkey_dev_attributes;
2044
2045 static void tpacpi_driver_event(const unsigned int hkey_event);
2046 static void hotkey_driver_event(const unsigned int scancode);
2047 static void hotkey_poll_setup(const bool may_warn);
2048
2049 /* HKEY.MHKG() return bits */
2050 #define TP_HOTKEY_TABLET_MASK (1 << 3)
2051 /* ThinkPad X1 Yoga (2016) */
2052 #define TP_EC_CMMD_TABLET_MODE 0x6
2053
2054 static int hotkey_get_wlsw(void)
2055 {
2056         int status;
2057
2058         if (!tp_features.hotkey_wlsw)
2059                 return -ENODEV;
2060
2061 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2062         if (dbg_wlswemul)
2063                 return (tpacpi_wlsw_emulstate) ?
2064                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2065 #endif
2066
2067         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
2068                 return -EIO;
2069
2070         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2071 }
2072
2073 static int hotkey_get_tablet_mode(int *status)
2074 {
2075         int s;
2076
2077         switch (tp_features.hotkey_tablet) {
2078         case TP_HOTKEY_TABLET_USES_MHKG:
2079                 if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
2080                         return -EIO;
2081
2082                 *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
2083                 break;
2084         case TP_HOTKEY_TABLET_USES_CMMD:
2085                 if (!acpi_evalf(ec_handle, &s, "CMMD", "d"))
2086                         return -EIO;
2087
2088                 *status = (s == TP_EC_CMMD_TABLET_MODE);
2089                 break;
2090         default:
2091                 break;
2092         }
2093
2094         return 0;
2095 }
2096
2097 /*
2098  * Reads current event mask from firmware, and updates
2099  * hotkey_acpi_mask accordingly.  Also resets any bits
2100  * from hotkey_user_mask that are unavailable to be
2101  * delivered (shadow requirement of the userspace ABI).
2102  *
2103  * Call with hotkey_mutex held
2104  */
2105 static int hotkey_mask_get(void)
2106 {
2107         if (tp_features.hotkey_mask) {
2108                 u32 m = 0;
2109
2110                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
2111                         return -EIO;
2112
2113                 hotkey_acpi_mask = m;
2114         } else {
2115                 /* no mask support doesn't mean no event support... */
2116                 hotkey_acpi_mask = hotkey_all_mask;
2117         }
2118
2119         /* sync userspace-visible mask */
2120         hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask);
2121
2122         return 0;
2123 }
2124
2125 static void hotkey_mask_warn_incomplete_mask(void)
2126 {
2127         /* log only what the user can fix... */
2128         const u32 wantedmask = hotkey_driver_mask &
2129                 ~(hotkey_acpi_mask | hotkey_source_mask) &
2130                 (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK);
2131
2132         if (wantedmask)
2133                 pr_notice("required events 0x%08x not enabled!\n", wantedmask);
2134 }
2135
2136 /*
2137  * Set the firmware mask when supported
2138  *
2139  * Also calls hotkey_mask_get to update hotkey_acpi_mask.
2140  *
2141  * NOTE: does not set bits in hotkey_user_mask, but may reset them.
2142  *
2143  * Call with hotkey_mutex held
2144  */
2145 static int hotkey_mask_set(u32 mask)
2146 {
2147         int i;
2148         int rc = 0;
2149
2150         const u32 fwmask = mask & ~hotkey_source_mask;
2151
2152         if (tp_features.hotkey_mask) {
2153                 for (i = 0; i < 32; i++) {
2154                         if (!acpi_evalf(hkey_handle,
2155                                         NULL, "MHKM", "vdd", i + 1,
2156                                         !!(mask & (1 << i)))) {
2157                                 rc = -EIO;
2158                                 break;
2159                         }
2160                 }
2161         }
2162
2163         /*
2164          * We *must* make an inconditional call to hotkey_mask_get to
2165          * refresh hotkey_acpi_mask and update hotkey_user_mask
2166          *
2167          * Take the opportunity to also log when we cannot _enable_
2168          * a given event.
2169          */
2170         if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) {
2171                 pr_notice("asked for hotkey mask 0x%08x, but firmware forced it to 0x%08x\n",
2172                           fwmask, hotkey_acpi_mask);
2173         }
2174
2175         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING)
2176                 hotkey_mask_warn_incomplete_mask();
2177
2178         return rc;
2179 }
2180
2181 /*
2182  * Sets hotkey_user_mask and tries to set the firmware mask
2183  *
2184  * Call with hotkey_mutex held
2185  */
2186 static int hotkey_user_mask_set(const u32 mask)
2187 {
2188         int rc;
2189
2190         /* Give people a chance to notice they are doing something that
2191          * is bound to go boom on their users sooner or later */
2192         if (!tp_warned.hotkey_mask_ff &&
2193             (mask == 0xffff || mask == 0xffffff ||
2194              mask == 0xffffffff)) {
2195                 tp_warned.hotkey_mask_ff = 1;
2196                 pr_notice("setting the hotkey mask to 0x%08x is likely not the best way to go about it\n",
2197                           mask);
2198                 pr_notice("please consider using the driver defaults, and refer to up-to-date thinkpad-acpi documentation\n");
2199         }
2200
2201         /* Try to enable what the user asked for, plus whatever we need.
2202          * this syncs everything but won't enable bits in hotkey_user_mask */
2203         rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask);
2204
2205         /* Enable the available bits in hotkey_user_mask */
2206         hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask);
2207
2208         return rc;
2209 }
2210
2211 /*
2212  * Sets the driver hotkey mask.
2213  *
2214  * Can be called even if the hotkey subdriver is inactive
2215  */
2216 static int tpacpi_hotkey_driver_mask_set(const u32 mask)
2217 {
2218         int rc;
2219
2220         /* Do the right thing if hotkey_init has not been called yet */
2221         if (!tp_features.hotkey) {
2222                 hotkey_driver_mask = mask;
2223                 return 0;
2224         }
2225
2226         mutex_lock(&hotkey_mutex);
2227
2228         HOTKEY_CONFIG_CRITICAL_START
2229         hotkey_driver_mask = mask;
2230 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2231         hotkey_source_mask |= (mask & ~hotkey_all_mask);
2232 #endif
2233         HOTKEY_CONFIG_CRITICAL_END
2234
2235         rc = hotkey_mask_set((hotkey_acpi_mask | hotkey_driver_mask) &
2236                                                         ~hotkey_source_mask);
2237         hotkey_poll_setup(true);
2238
2239         mutex_unlock(&hotkey_mutex);
2240
2241         return rc;
2242 }
2243
2244 static int hotkey_status_get(int *status)
2245 {
2246         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
2247                 return -EIO;
2248
2249         return 0;
2250 }
2251
2252 static int hotkey_status_set(bool enable)
2253 {
2254         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
2255                 return -EIO;
2256
2257         return 0;
2258 }
2259
2260 static void tpacpi_input_send_tabletsw(void)
2261 {
2262         int state;
2263
2264         if (tp_features.hotkey_tablet &&
2265             !hotkey_get_tablet_mode(&state)) {
2266                 mutex_lock(&tpacpi_inputdev_send_mutex);
2267
2268                 input_report_switch(tpacpi_inputdev,
2269                                     SW_TABLET_MODE, !!state);
2270                 input_sync(tpacpi_inputdev);
2271
2272                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2273         }
2274 }
2275
2276 /* Do NOT call without validating scancode first */
2277 static void tpacpi_input_send_key(const unsigned int scancode)
2278 {
2279         const unsigned int keycode = hotkey_keycode_map[scancode];
2280
2281         if (keycode != KEY_RESERVED) {
2282                 mutex_lock(&tpacpi_inputdev_send_mutex);
2283
2284                 input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN, scancode);
2285                 input_report_key(tpacpi_inputdev, keycode, 1);
2286                 input_sync(tpacpi_inputdev);
2287
2288                 input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN, scancode);
2289                 input_report_key(tpacpi_inputdev, keycode, 0);
2290                 input_sync(tpacpi_inputdev);
2291
2292                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2293         }
2294 }
2295
2296 /* Do NOT call without validating scancode first */
2297 static void tpacpi_input_send_key_masked(const unsigned int scancode)
2298 {
2299         hotkey_driver_event(scancode);
2300         if (hotkey_user_mask & (1 << scancode))
2301                 tpacpi_input_send_key(scancode);
2302 }
2303
2304 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2305 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
2306
2307 /* Do NOT call without validating scancode first */
2308 static void tpacpi_hotkey_send_key(unsigned int scancode)
2309 {
2310         tpacpi_input_send_key_masked(scancode);
2311 }
2312
2313 static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m)
2314 {
2315         u8 d;
2316
2317         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
2318                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
2319                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
2320                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
2321                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
2322                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
2323         }
2324         if (m & TP_ACPI_HKEY_KBD_LIGHT_MASK) {
2325                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
2326                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2327         }
2328         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2329                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2330                 n->displayexp_toggle =
2331                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2332         }
2333         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2334                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2335                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2336                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2337                 n->brightness_toggle =
2338                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2339         }
2340         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2341                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2342                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2343                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2344                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2345                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2346         }
2347 }
2348
2349 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2350 do { \
2351         if ((event_mask & (1 << __scancode)) && \
2352             oldn->__member != newn->__member) \
2353                 tpacpi_hotkey_send_key(__scancode); \
2354 } while (0)
2355
2356 #define TPACPI_MAY_SEND_KEY(__scancode) \
2357 do { \
2358         if (event_mask & (1 << __scancode)) \
2359                 tpacpi_hotkey_send_key(__scancode); \
2360 } while (0)
2361
2362 static void issue_volchange(const unsigned int oldvol,
2363                             const unsigned int newvol,
2364                             const u32 event_mask)
2365 {
2366         unsigned int i = oldvol;
2367
2368         while (i > newvol) {
2369                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2370                 i--;
2371         }
2372         while (i < newvol) {
2373                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2374                 i++;
2375         }
2376 }
2377
2378 static void issue_brightnesschange(const unsigned int oldbrt,
2379                                    const unsigned int newbrt,
2380                                    const u32 event_mask)
2381 {
2382         unsigned int i = oldbrt;
2383
2384         while (i > newbrt) {
2385                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2386                 i--;
2387         }
2388         while (i < newbrt) {
2389                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2390                 i++;
2391         }
2392 }
2393
2394 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2395                                            struct tp_nvram_state *newn,
2396                                            const u32 event_mask)
2397 {
2398
2399         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2400         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2401         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2402         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2403
2404         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2405
2406         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2407
2408         /*
2409          * Handle volume
2410          *
2411          * This code is supposed to duplicate the IBM firmware behaviour:
2412          * - Pressing MUTE issues mute hotkey message, even when already mute
2413          * - Pressing Volume up/down issues volume up/down hotkey messages,
2414          *   even when already at maximum or minimum volume
2415          * - The act of unmuting issues volume up/down notification,
2416          *   depending which key was used to unmute
2417          *
2418          * We are constrained to what the NVRAM can tell us, which is not much
2419          * and certainly not enough if more than one volume hotkey was pressed
2420          * since the last poll cycle.
2421          *
2422          * Just to make our life interesting, some newer Lenovo ThinkPads have
2423          * bugs in the BIOS and may fail to update volume_toggle properly.
2424          */
2425         if (newn->mute) {
2426                 /* muted */
2427                 if (!oldn->mute ||
2428                     oldn->volume_toggle != newn->volume_toggle ||
2429                     oldn->volume_level != newn->volume_level) {
2430                         /* recently muted, or repeated mute keypress, or
2431                          * multiple presses ending in mute */
2432                         issue_volchange(oldn->volume_level, newn->volume_level,
2433                                 event_mask);
2434                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2435                 }
2436         } else {
2437                 /* unmute */
2438                 if (oldn->mute) {
2439                         /* recently unmuted, issue 'unmute' keypress */
2440                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2441                 }
2442                 if (oldn->volume_level != newn->volume_level) {
2443                         issue_volchange(oldn->volume_level, newn->volume_level,
2444                                 event_mask);
2445                 } else if (oldn->volume_toggle != newn->volume_toggle) {
2446                         /* repeated vol up/down keypress at end of scale ? */
2447                         if (newn->volume_level == 0)
2448                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2449                         else if (newn->volume_level >= TP_NVRAM_LEVEL_VOLUME_MAX)
2450                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2451                 }
2452         }
2453
2454         /* handle brightness */
2455         if (oldn->brightness_level != newn->brightness_level) {
2456                 issue_brightnesschange(oldn->brightness_level,
2457                                        newn->brightness_level, event_mask);
2458         } else if (oldn->brightness_toggle != newn->brightness_toggle) {
2459                 /* repeated key presses that didn't change state */
2460                 if (newn->brightness_level == 0)
2461                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2462                 else if (newn->brightness_level >= bright_maxlvl
2463                                 && !tp_features.bright_unkfw)
2464                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2465         }
2466
2467 #undef TPACPI_COMPARE_KEY
2468 #undef TPACPI_MAY_SEND_KEY
2469 }
2470
2471 /*
2472  * Polling driver
2473  *
2474  * We track all events in hotkey_source_mask all the time, since
2475  * most of them are edge-based.  We only issue those requested by
2476  * hotkey_user_mask or hotkey_driver_mask, though.
2477  */
2478 static int hotkey_kthread(void *data)
2479 {
2480         struct tp_nvram_state s[2];
2481         u32 poll_mask, event_mask;
2482         unsigned int si, so;
2483         unsigned long t;
2484         unsigned int change_detector;
2485         unsigned int poll_freq;
2486         bool was_frozen;
2487
2488         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2489                 goto exit;
2490
2491         set_freezable();
2492
2493         so = 0;
2494         si = 1;
2495         t = 0;
2496
2497         /* Initial state for compares */
2498         mutex_lock(&hotkey_thread_data_mutex);
2499         change_detector = hotkey_config_change;
2500         poll_mask = hotkey_source_mask;
2501         event_mask = hotkey_source_mask &
2502                         (hotkey_driver_mask | hotkey_user_mask);
2503         poll_freq = hotkey_poll_freq;
2504         mutex_unlock(&hotkey_thread_data_mutex);
2505         hotkey_read_nvram(&s[so], poll_mask);
2506
2507         while (!kthread_should_stop()) {
2508                 if (t == 0) {
2509                         if (likely(poll_freq))
2510                                 t = 1000/poll_freq;
2511                         else
2512                                 t = 100;        /* should never happen... */
2513                 }
2514                 t = msleep_interruptible(t);
2515                 if (unlikely(kthread_freezable_should_stop(&was_frozen)))
2516                         break;
2517
2518                 if (t > 0 && !was_frozen)
2519                         continue;
2520
2521                 mutex_lock(&hotkey_thread_data_mutex);
2522                 if (was_frozen || hotkey_config_change != change_detector) {
2523                         /* forget old state on thaw or config change */
2524                         si = so;
2525                         t = 0;
2526                         change_detector = hotkey_config_change;
2527                 }
2528                 poll_mask = hotkey_source_mask;
2529                 event_mask = hotkey_source_mask &
2530                                 (hotkey_driver_mask | hotkey_user_mask);
2531                 poll_freq = hotkey_poll_freq;
2532                 mutex_unlock(&hotkey_thread_data_mutex);
2533
2534                 if (likely(poll_mask)) {
2535                         hotkey_read_nvram(&s[si], poll_mask);
2536                         if (likely(si != so)) {
2537                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2538                                                                 event_mask);
2539                         }
2540                 }
2541
2542                 so = si;
2543                 si ^= 1;
2544         }
2545
2546 exit:
2547         return 0;
2548 }
2549
2550 /* call with hotkey_mutex held */
2551 static void hotkey_poll_stop_sync(void)
2552 {
2553         if (tpacpi_hotkey_task) {
2554                 kthread_stop(tpacpi_hotkey_task);
2555                 tpacpi_hotkey_task = NULL;
2556         }
2557 }
2558
2559 /* call with hotkey_mutex held */
2560 static void hotkey_poll_setup(const bool may_warn)
2561 {
2562         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2563         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2564
2565         if (hotkey_poll_freq > 0 &&
2566             (poll_driver_mask ||
2567              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2568                 if (!tpacpi_hotkey_task) {
2569                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2570                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2571                         if (IS_ERR(tpacpi_hotkey_task)) {
2572                                 tpacpi_hotkey_task = NULL;
2573                                 pr_err("could not create kernel thread for hotkey polling\n");
2574                         }
2575                 }
2576         } else {
2577                 hotkey_poll_stop_sync();
2578                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2579                     hotkey_poll_freq == 0) {
2580                         pr_notice("hot keys 0x%08x and/or events 0x%08x require polling, which is currently disabled\n",
2581                                   poll_user_mask, poll_driver_mask);
2582                 }
2583         }
2584 }
2585
2586 static void hotkey_poll_setup_safe(const bool may_warn)
2587 {
2588         mutex_lock(&hotkey_mutex);
2589         hotkey_poll_setup(may_warn);
2590         mutex_unlock(&hotkey_mutex);
2591 }
2592
2593 /* call with hotkey_mutex held */
2594 static void hotkey_poll_set_freq(unsigned int freq)
2595 {
2596         if (!freq)
2597                 hotkey_poll_stop_sync();
2598
2599         hotkey_poll_freq = freq;
2600 }
2601
2602 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2603
2604 static void hotkey_poll_setup(const bool __unused)
2605 {
2606 }
2607
2608 static void hotkey_poll_setup_safe(const bool __unused)
2609 {
2610 }
2611
2612 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2613
2614 static int hotkey_inputdev_open(struct input_dev *dev)
2615 {
2616         switch (tpacpi_lifecycle) {
2617         case TPACPI_LIFE_INIT:
2618         case TPACPI_LIFE_RUNNING:
2619                 hotkey_poll_setup_safe(false);
2620                 return 0;
2621         case TPACPI_LIFE_EXITING:
2622                 return -EBUSY;
2623         }
2624
2625         /* Should only happen if tpacpi_lifecycle is corrupt */
2626         BUG();
2627         return -EBUSY;
2628 }
2629
2630 static void hotkey_inputdev_close(struct input_dev *dev)
2631 {
2632         /* disable hotkey polling when possible */
2633         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING &&
2634             !(hotkey_source_mask & hotkey_driver_mask))
2635                 hotkey_poll_setup_safe(false);
2636 }
2637
2638 /* sysfs hotkey enable ------------------------------------------------- */
2639 static ssize_t hotkey_enable_show(struct device *dev,
2640                            struct device_attribute *attr,
2641                            char *buf)
2642 {
2643         int res, status;
2644
2645         printk_deprecated_attribute("hotkey_enable",
2646                         "Hotkey reporting is always enabled");
2647
2648         res = hotkey_status_get(&status);
2649         if (res)
2650                 return res;
2651
2652         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2653 }
2654
2655 static ssize_t hotkey_enable_store(struct device *dev,
2656                             struct device_attribute *attr,
2657                             const char *buf, size_t count)
2658 {
2659         unsigned long t;
2660
2661         printk_deprecated_attribute("hotkey_enable",
2662                         "Hotkeys can be disabled through hotkey_mask");
2663
2664         if (parse_strtoul(buf, 1, &t))
2665                 return -EINVAL;
2666
2667         if (t == 0)
2668                 return -EPERM;
2669
2670         return count;
2671 }
2672
2673 static DEVICE_ATTR_RW(hotkey_enable);
2674
2675 /* sysfs hotkey mask --------------------------------------------------- */
2676 static ssize_t hotkey_mask_show(struct device *dev,
2677                            struct device_attribute *attr,
2678                            char *buf)
2679 {
2680         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2681 }
2682
2683 static ssize_t hotkey_mask_store(struct device *dev,
2684                             struct device_attribute *attr,
2685                             const char *buf, size_t count)
2686 {
2687         unsigned long t;
2688         int res;
2689
2690         if (parse_strtoul(buf, 0xffffffffUL, &t))
2691                 return -EINVAL;
2692
2693         if (mutex_lock_killable(&hotkey_mutex))
2694                 return -ERESTARTSYS;
2695
2696         res = hotkey_user_mask_set(t);
2697
2698 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2699         hotkey_poll_setup(true);
2700 #endif
2701
2702         mutex_unlock(&hotkey_mutex);
2703
2704         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2705
2706         return (res) ? res : count;
2707 }
2708
2709 static DEVICE_ATTR_RW(hotkey_mask);
2710
2711 /* sysfs hotkey bios_enabled ------------------------------------------- */
2712 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2713                            struct device_attribute *attr,
2714                            char *buf)
2715 {
2716         return sprintf(buf, "0\n");
2717 }
2718
2719 static DEVICE_ATTR_RO(hotkey_bios_enabled);
2720
2721 /* sysfs hotkey bios_mask ---------------------------------------------- */
2722 static ssize_t hotkey_bios_mask_show(struct device *dev,
2723                            struct device_attribute *attr,
2724                            char *buf)
2725 {
2726         printk_deprecated_attribute("hotkey_bios_mask",
2727                         "This attribute is useless.");
2728         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2729 }
2730
2731 static DEVICE_ATTR_RO(hotkey_bios_mask);
2732
2733 /* sysfs hotkey all_mask ----------------------------------------------- */
2734 static ssize_t hotkey_all_mask_show(struct device *dev,
2735                            struct device_attribute *attr,
2736                            char *buf)
2737 {
2738         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2739                                 hotkey_all_mask | hotkey_source_mask);
2740 }
2741
2742 static DEVICE_ATTR_RO(hotkey_all_mask);
2743
2744 /* sysfs hotkey all_mask ----------------------------------------------- */
2745 static ssize_t hotkey_adaptive_all_mask_show(struct device *dev,
2746                            struct device_attribute *attr,
2747                            char *buf)
2748 {
2749         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2750                         hotkey_adaptive_all_mask | hotkey_source_mask);
2751 }
2752
2753 static DEVICE_ATTR_RO(hotkey_adaptive_all_mask);
2754
2755 /* sysfs hotkey recommended_mask --------------------------------------- */
2756 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2757                                             struct device_attribute *attr,
2758                                             char *buf)
2759 {
2760         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2761                         (hotkey_all_mask | hotkey_source_mask)
2762                         & ~hotkey_reserved_mask);
2763 }
2764
2765 static DEVICE_ATTR_RO(hotkey_recommended_mask);
2766
2767 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2768
2769 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2770 static ssize_t hotkey_source_mask_show(struct device *dev,
2771                            struct device_attribute *attr,
2772                            char *buf)
2773 {
2774         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2775 }
2776
2777 static ssize_t hotkey_source_mask_store(struct device *dev,
2778                             struct device_attribute *attr,
2779                             const char *buf, size_t count)
2780 {
2781         unsigned long t;
2782         u32 r_ev;
2783         int rc;
2784
2785         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2786                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2787                 return -EINVAL;
2788
2789         if (mutex_lock_killable(&hotkey_mutex))
2790                 return -ERESTARTSYS;
2791
2792         HOTKEY_CONFIG_CRITICAL_START
2793         hotkey_source_mask = t;
2794         HOTKEY_CONFIG_CRITICAL_END
2795
2796         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2797                         ~hotkey_source_mask);
2798         hotkey_poll_setup(true);
2799
2800         /* check if events needed by the driver got disabled */
2801         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2802                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2803
2804         mutex_unlock(&hotkey_mutex);
2805
2806         if (rc < 0)
2807                 pr_err("hotkey_source_mask: failed to update the firmware event mask!\n");
2808
2809         if (r_ev)
2810                 pr_notice("hotkey_source_mask: some important events were disabled: 0x%04x\n",
2811                           r_ev);
2812
2813         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2814
2815         return (rc < 0) ? rc : count;
2816 }
2817
2818 static DEVICE_ATTR_RW(hotkey_source_mask);
2819
2820 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2821 static ssize_t hotkey_poll_freq_show(struct device *dev,
2822                            struct device_attribute *attr,
2823                            char *buf)
2824 {
2825         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2826 }
2827
2828 static ssize_t hotkey_poll_freq_store(struct device *dev,
2829                             struct device_attribute *attr,
2830                             const char *buf, size_t count)
2831 {
2832         unsigned long t;
2833
2834         if (parse_strtoul(buf, 25, &t))
2835                 return -EINVAL;
2836
2837         if (mutex_lock_killable(&hotkey_mutex))
2838                 return -ERESTARTSYS;
2839
2840         hotkey_poll_set_freq(t);
2841         hotkey_poll_setup(true);
2842
2843         mutex_unlock(&hotkey_mutex);
2844
2845         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2846
2847         return count;
2848 }
2849
2850 static DEVICE_ATTR_RW(hotkey_poll_freq);
2851
2852 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2853
2854 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2855 static ssize_t hotkey_radio_sw_show(struct device *dev,
2856                            struct device_attribute *attr,
2857                            char *buf)
2858 {
2859         int res;
2860         res = hotkey_get_wlsw();
2861         if (res < 0)
2862                 return res;
2863
2864         /* Opportunistic update */
2865         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2866
2867         return snprintf(buf, PAGE_SIZE, "%d\n",
2868                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2869 }
2870
2871 static DEVICE_ATTR_RO(hotkey_radio_sw);
2872
2873 static void hotkey_radio_sw_notify_change(void)
2874 {
2875         if (tp_features.hotkey_wlsw)
2876                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2877                              "hotkey_radio_sw");
2878 }
2879
2880 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2881 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2882                            struct device_attribute *attr,
2883                            char *buf)
2884 {
2885         int res, s;
2886         res = hotkey_get_tablet_mode(&s);
2887         if (res < 0)
2888                 return res;
2889
2890         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2891 }
2892
2893 static DEVICE_ATTR_RO(hotkey_tablet_mode);
2894
2895 static void hotkey_tablet_mode_notify_change(void)
2896 {
2897         if (tp_features.hotkey_tablet)
2898                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2899                              "hotkey_tablet_mode");
2900 }
2901
2902 /* sysfs wakeup reason (pollable) -------------------------------------- */
2903 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2904                            struct device_attribute *attr,
2905                            char *buf)
2906 {
2907         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2908 }
2909
2910 static DEVICE_ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2911
2912 static void hotkey_wakeup_reason_notify_change(void)
2913 {
2914         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2915                      "wakeup_reason");
2916 }
2917
2918 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2919 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2920                            struct device_attribute *attr,
2921                            char *buf)
2922 {
2923         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2924 }
2925
2926 static DEVICE_ATTR(wakeup_hotunplug_complete, S_IRUGO,
2927                    hotkey_wakeup_hotunplug_complete_show, NULL);
2928
2929 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2930 {
2931         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2932                      "wakeup_hotunplug_complete");
2933 }
2934
2935 /* sysfs adaptive kbd mode --------------------------------------------- */
2936
2937 static int adaptive_keyboard_get_mode(void);
2938 static int adaptive_keyboard_set_mode(int new_mode);
2939
2940 enum ADAPTIVE_KEY_MODE {
2941         HOME_MODE,
2942         WEB_BROWSER_MODE,
2943         WEB_CONFERENCE_MODE,
2944         FUNCTION_MODE,
2945         LAYFLAT_MODE
2946 };
2947
2948 static ssize_t adaptive_kbd_mode_show(struct device *dev,
2949                            struct device_attribute *attr,
2950                            char *buf)
2951 {
2952         int current_mode;
2953
2954         current_mode = adaptive_keyboard_get_mode();
2955         if (current_mode < 0)
2956                 return current_mode;
2957
2958         return snprintf(buf, PAGE_SIZE, "%d\n", current_mode);
2959 }
2960
2961 static ssize_t adaptive_kbd_mode_store(struct device *dev,
2962                             struct device_attribute *attr,
2963                             const char *buf, size_t count)
2964 {
2965         unsigned long t;
2966         int res;
2967
2968         if (parse_strtoul(buf, LAYFLAT_MODE, &t))
2969                 return -EINVAL;
2970
2971         res = adaptive_keyboard_set_mode(t);
2972         return (res < 0) ? res : count;
2973 }
2974
2975 static DEVICE_ATTR_RW(adaptive_kbd_mode);
2976
2977 static struct attribute *adaptive_kbd_attributes[] = {
2978         &dev_attr_adaptive_kbd_mode.attr,
2979         NULL
2980 };
2981
2982 static const struct attribute_group adaptive_kbd_attr_group = {
2983         .attrs = adaptive_kbd_attributes,
2984 };
2985
2986 /* --------------------------------------------------------------------- */
2987
2988 static struct attribute *hotkey_attributes[] __initdata = {
2989         &dev_attr_hotkey_enable.attr,
2990         &dev_attr_hotkey_bios_enabled.attr,
2991         &dev_attr_hotkey_bios_mask.attr,
2992         &dev_attr_wakeup_reason.attr,
2993         &dev_attr_wakeup_hotunplug_complete.attr,
2994         &dev_attr_hotkey_mask.attr,
2995         &dev_attr_hotkey_all_mask.attr,
2996         &dev_attr_hotkey_adaptive_all_mask.attr,
2997         &dev_attr_hotkey_recommended_mask.attr,
2998 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2999         &dev_attr_hotkey_source_mask.attr,
3000         &dev_attr_hotkey_poll_freq.attr,
3001 #endif
3002 };
3003
3004 /*
3005  * Sync both the hw and sw blocking state of all switches
3006  */
3007 static void tpacpi_send_radiosw_update(void)
3008 {
3009         int wlsw;
3010
3011         /*
3012          * We must sync all rfkill controllers *before* issuing any
3013          * rfkill input events, or we will race the rfkill core input
3014          * handler.
3015          *
3016          * tpacpi_inputdev_send_mutex works as a synchronization point
3017          * for the above.
3018          *
3019          * We optimize to avoid numerous calls to hotkey_get_wlsw.
3020          */
3021
3022         wlsw = hotkey_get_wlsw();
3023
3024         /* Sync hw blocking state first if it is hw-blocked */
3025         if (wlsw == TPACPI_RFK_RADIO_OFF)
3026                 tpacpi_rfk_update_hwblock_state(true);
3027
3028         /* Sync sw blocking state */
3029         tpacpi_rfk_update_swstate_all();
3030
3031         /* Sync hw blocking state last if it is hw-unblocked */
3032         if (wlsw == TPACPI_RFK_RADIO_ON)
3033                 tpacpi_rfk_update_hwblock_state(false);
3034
3035         /* Issue rfkill input event for WLSW switch */
3036         if (!(wlsw < 0)) {
3037                 mutex_lock(&tpacpi_inputdev_send_mutex);
3038
3039                 input_report_switch(tpacpi_inputdev,
3040                                     SW_RFKILL_ALL, (wlsw > 0));
3041                 input_sync(tpacpi_inputdev);
3042
3043                 mutex_unlock(&tpacpi_inputdev_send_mutex);
3044         }
3045
3046         /*
3047          * this can be unconditional, as we will poll state again
3048          * if userspace uses the notify to read data
3049          */
3050         hotkey_radio_sw_notify_change();
3051 }
3052
3053 static void hotkey_exit(void)
3054 {
3055 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3056         mutex_lock(&hotkey_mutex);
3057         hotkey_poll_stop_sync();
3058         mutex_unlock(&hotkey_mutex);
3059 #endif
3060
3061         if (hotkey_dev_attributes)
3062                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3063
3064         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
3065                    "restoring original HKEY status and mask\n");
3066         /* yes, there is a bitwise or below, we want the
3067          * functions to be called even if one of them fail */
3068         if (((tp_features.hotkey_mask &&
3069               hotkey_mask_set(hotkey_orig_mask)) |
3070              hotkey_status_set(false)) != 0)
3071                 pr_err("failed to restore hot key mask to BIOS defaults\n");
3072 }
3073
3074 static void __init hotkey_unmap(const unsigned int scancode)
3075 {
3076         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
3077                 clear_bit(hotkey_keycode_map[scancode],
3078                           tpacpi_inputdev->keybit);
3079                 hotkey_keycode_map[scancode] = KEY_RESERVED;
3080         }
3081 }
3082
3083 /*
3084  * HKEY quirks:
3085  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
3086  */
3087
3088 #define TPACPI_HK_Q_INIMASK     0x0001
3089
3090 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
3091         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
3092         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
3093         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
3094         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
3095         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
3096         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
3097         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
3098         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
3099         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
3100         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
3101         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
3102         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
3103         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
3104         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
3105         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
3106         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
3107         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
3108         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
3109         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
3110 };
3111
3112 typedef u16 tpacpi_keymap_entry_t;
3113 typedef tpacpi_keymap_entry_t tpacpi_keymap_t[TPACPI_HOTKEY_MAP_LEN];
3114
3115 static int hotkey_init_tablet_mode(void)
3116 {
3117         int in_tablet_mode = 0, res;
3118         char *type = NULL;
3119
3120         if (acpi_evalf(hkey_handle, &res, "MHKG", "qd")) {
3121                 /* For X41t, X60t, X61t Tablets... */
3122                 tp_features.hotkey_tablet = TP_HOTKEY_TABLET_USES_MHKG;
3123                 in_tablet_mode = !!(res & TP_HOTKEY_TABLET_MASK);
3124                 type = "MHKG";
3125         } else if (acpi_evalf(ec_handle, &res, "CMMD", "qd")) {
3126                 /* For X1 Yoga (2016) */
3127                 tp_features.hotkey_tablet = TP_HOTKEY_TABLET_USES_CMMD;
3128                 in_tablet_mode = res == TP_EC_CMMD_TABLET_MODE;
3129                 type = "CMMD";
3130         }
3131
3132         if (!tp_features.hotkey_tablet)
3133                 return 0;
3134
3135         pr_info("Tablet mode switch found (type: %s), currently in %s mode\n",
3136                 type, in_tablet_mode ? "tablet" : "laptop");
3137
3138         res = add_to_attr_set(hotkey_dev_attributes,
3139                               &dev_attr_hotkey_tablet_mode.attr);
3140         if (res)
3141                 return -1;
3142
3143         return in_tablet_mode;
3144 }
3145
3146 static int __init hotkey_init(struct ibm_init_struct *iibm)
3147 {
3148         /* Requirements for changing the default keymaps:
3149          *
3150          * 1. Many of the keys are mapped to KEY_RESERVED for very
3151          *    good reasons.  Do not change them unless you have deep
3152          *    knowledge on the IBM and Lenovo ThinkPad firmware for
3153          *    the various ThinkPad models.  The driver behaves
3154          *    differently for KEY_RESERVED: such keys have their
3155          *    hot key mask *unset* in mask_recommended, and also
3156          *    in the initial hot key mask programmed into the
3157          *    firmware at driver load time, which means the firm-
3158          *    ware may react very differently if you change them to
3159          *    something else;
3160          *
3161          * 2. You must be subscribed to the linux-thinkpad and
3162          *    ibm-acpi-devel mailing lists, and you should read the
3163          *    list archives since 2007 if you want to change the
3164          *    keymaps.  This requirement exists so that you will
3165          *    know the past history of problems with the thinkpad-
3166          *    acpi driver keymaps, and also that you will be
3167          *    listening to any bug reports;
3168          *
3169          * 3. Do not send thinkpad-acpi specific patches directly to
3170          *    for merging, *ever*.  Send them to the linux-acpi
3171          *    mailinglist for comments.  Merging is to be done only
3172          *    through acpi-test and the ACPI maintainer.
3173          *
3174          * If the above is too much to ask, don't change the keymap.
3175          * Ask the thinkpad-acpi maintainer to do it, instead.
3176          */
3177
3178         enum keymap_index {
3179                 TPACPI_KEYMAP_IBM_GENERIC = 0,
3180                 TPACPI_KEYMAP_LENOVO_GENERIC,
3181         };
3182
3183         static const tpacpi_keymap_t tpacpi_keymaps[] __initconst = {
3184         /* Generic keymap for IBM ThinkPads */
3185         [TPACPI_KEYMAP_IBM_GENERIC] = {
3186                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3187                 KEY_FN_F1,      KEY_BATTERY,    KEY_COFFEE,     KEY_SLEEP,
3188                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3189                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3190
3191                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3192                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3193                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3194                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3195
3196                 /* brightness: firmware always reacts to them */
3197                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3198                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3199
3200                 /* Thinklight: firmware always react to it */
3201                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3202
3203                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3204                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3205
3206                 /* Volume: firmware always react to it and reprograms
3207                  * the built-in *extra* mixer.  Never map it to control
3208                  * another mixer by default. */
3209                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3210                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3211                 KEY_RESERVED,   /* 0x16: MUTE */
3212
3213                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3214
3215                 /* (assignments unknown, please report if found) */
3216                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3217                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3218
3219                 /* No assignments, only used for Adaptive keyboards. */
3220                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3221                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3222                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3223                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3224                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3225
3226                 /* No assignment, used for newer Lenovo models */
3227                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3228                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3229                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3230                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3231                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3232                 KEY_UNKNOWN, KEY_UNKNOWN
3233
3234                 },
3235
3236         /* Generic keymap for Lenovo ThinkPads */
3237         [TPACPI_KEYMAP_LENOVO_GENERIC] = {
3238                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3239                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3240                 KEY_WLAN,       KEY_CAMERA, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3241                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3242
3243                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3244                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3245                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3246                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3247
3248                 /* These should be enabled --only-- when ACPI video
3249                  * is disabled (i.e. in "vendor" mode), and are handled
3250                  * in a special way by the init code */
3251                 KEY_BRIGHTNESSUP,       /* 0x0F: FN+HOME (brightness up) */
3252                 KEY_BRIGHTNESSDOWN,     /* 0x10: FN+END (brightness down) */
3253
3254                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3255
3256                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3257                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3258
3259                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
3260                  * react to it and reprograms the built-in *extra* mixer.
3261                  * Never map it to control another mixer by default.
3262                  *
3263                  * T60?, T61, R60?, R61: firmware and EC tries to send
3264                  * these over the regular keyboard, so these are no-ops,
3265                  * but there are still weird bugs re. MUTE, so do not
3266                  * change unless you get test reports from all Lenovo
3267                  * models.  May cause the BIOS to interfere with the
3268                  * HDA mixer.
3269                  */
3270                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3271                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3272                 KEY_RESERVED,   /* 0x16: MUTE */
3273
3274                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3275
3276                 /* (assignments unknown, please report if found) */
3277                 KEY_UNKNOWN, KEY_UNKNOWN,
3278
3279                 /*
3280                  * The mic mute button only sends 0x1a.  It does not
3281                  * automatically mute the mic or change the mute light.
3282                  */
3283                 KEY_MICMUTE,    /* 0x1a: Mic mute (since ?400 or so) */
3284
3285                 /* (assignments unknown, please report if found) */
3286                 KEY_UNKNOWN,
3287
3288                 /* Extra keys in use since the X240 / T440 / T540 */
3289                 KEY_CONFIG, KEY_SEARCH, KEY_SCALE, KEY_FILE,
3290
3291                 /*
3292                  * These are the adaptive keyboard keycodes for Carbon X1 2014.
3293                  * The first item in this list is the Mute button which is
3294                  * emitted with 0x103 through
3295                  * adaptive_keyboard_hotkey_notify_hotkey() when the sound
3296                  * symbol is held.
3297                  * We'll need to offset those by 0x20.
3298                  */
3299                 KEY_RESERVED,        /* Mute held, 0x103 */
3300                 KEY_BRIGHTNESS_MIN,  /* Backlight off */
3301                 KEY_RESERVED,        /* Clipping tool */
3302                 KEY_RESERVED,        /* Cloud */
3303                 KEY_RESERVED,
3304                 KEY_VOICECOMMAND,    /* Voice */
3305                 KEY_RESERVED,
3306                 KEY_RESERVED,        /* Gestures */
3307                 KEY_RESERVED,
3308                 KEY_RESERVED,
3309                 KEY_RESERVED,
3310                 KEY_CONFIG,          /* Settings */
3311                 KEY_RESERVED,        /* New tab */
3312                 KEY_REFRESH,         /* Reload */
3313                 KEY_BACK,            /* Back */
3314                 KEY_RESERVED,        /* Microphone down */
3315                 KEY_RESERVED,        /* Microphone up */
3316                 KEY_RESERVED,        /* Microphone cancellation */
3317                 KEY_RESERVED,        /* Camera mode */
3318                 KEY_RESERVED,        /* Rotate display, 0x116 */
3319
3320                 /*
3321                  * These are found in 2017 models (e.g. T470s, X270).
3322                  * The lowest known value is 0x311, which according to
3323                  * the manual should launch a user defined favorite
3324                  * application.
3325                  *
3326                  * The offset for these is TP_ACPI_HOTKEYSCAN_EXTENDED_START,
3327                  * corresponding to 0x34.
3328                  */
3329
3330                 /* (assignments unknown, please report if found) */
3331                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3332                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3333                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3334                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3335                 KEY_UNKNOWN,
3336
3337                 KEY_FAVORITES,       /* Favorite app, 0x311 */
3338                 KEY_RESERVED,        /* Clipping tool */
3339                 KEY_RESERVED,
3340                 KEY_BLUETOOTH,       /* Bluetooth */
3341                 KEY_KEYBOARD         /* Keyboard, 0x315 */
3342                 },
3343         };
3344
3345         static const struct tpacpi_quirk tpacpi_keymap_qtable[] __initconst = {
3346                 /* Generic maps (fallback) */
3347                 {
3348                   .vendor = PCI_VENDOR_ID_IBM,
3349                   .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
3350                   .quirks = TPACPI_KEYMAP_IBM_GENERIC,
3351                 },
3352                 {
3353                   .vendor = PCI_VENDOR_ID_LENOVO,
3354                   .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
3355                   .quirks = TPACPI_KEYMAP_LENOVO_GENERIC,
3356                 },
3357         };
3358
3359 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(tpacpi_keymap_t)
3360 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(tpacpi_keymap_entry_t)
3361
3362         int res, i;
3363         int status;
3364         int hkeyv;
3365         bool radiosw_state  = false;
3366         bool tabletsw_state = false;
3367
3368         unsigned long quirks;
3369         unsigned long keymap_id;
3370
3371         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3372                         "initializing hotkey subdriver\n");
3373
3374         BUG_ON(!tpacpi_inputdev);
3375         BUG_ON(tpacpi_inputdev->open != NULL ||
3376                tpacpi_inputdev->close != NULL);
3377
3378         TPACPI_ACPIHANDLE_INIT(hkey);
3379         mutex_init(&hotkey_mutex);
3380
3381 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3382         mutex_init(&hotkey_thread_data_mutex);
3383 #endif
3384
3385         /* hotkey not supported on 570 */
3386         tp_features.hotkey = hkey_handle != NULL;
3387
3388         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3389                 "hotkeys are %s\n",
3390                 str_supported(tp_features.hotkey));
3391
3392         if (!tp_features.hotkey)
3393                 return 1;
3394
3395         quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable,
3396                                      ARRAY_SIZE(tpacpi_hotkey_qtable));
3397
3398         tpacpi_disable_brightness_delay();
3399
3400         /* MUST have enough space for all attributes to be added to
3401          * hotkey_dev_attributes */
3402         hotkey_dev_attributes = create_attr_set(
3403                                         ARRAY_SIZE(hotkey_attributes) + 2,
3404                                         NULL);
3405         if (!hotkey_dev_attributes)
3406                 return -ENOMEM;
3407         res = add_many_to_attr_set(hotkey_dev_attributes,
3408                         hotkey_attributes,
3409                         ARRAY_SIZE(hotkey_attributes));
3410         if (res)
3411                 goto err_exit;
3412
3413         /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p,
3414            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
3415            for HKEY interface version 0x100 */
3416         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
3417                 vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3418                             "firmware HKEY interface version: 0x%x\n",
3419                             hkeyv);
3420
3421                 switch (hkeyv >> 8) {
3422                 case 1:
3423                         /*
3424                          * MHKV 0x100 in A31, R40, R40e,
3425                          * T4x, X31, and later
3426                          */
3427
3428                         /* Paranoia check AND init hotkey_all_mask */
3429                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3430                                         "MHKA", "qd")) {
3431                                 pr_err("missing MHKA handler, please report this to %s\n",
3432                                        TPACPI_MAIL);
3433                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3434                                 hotkey_all_mask = 0x080cU;
3435                         } else {
3436                                 tp_features.hotkey_mask = 1;
3437                         }
3438                         break;
3439
3440                 case 2:
3441                         /*
3442                          * MHKV 0x200 in X1, T460s, X260, T560, X1 Tablet (2016)
3443                          */
3444
3445                         /* Paranoia check AND init hotkey_all_mask */
3446                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3447                                         "MHKA", "dd", 1)) {
3448                                 pr_err("missing MHKA handler, please report this to %s\n",
3449                                        TPACPI_MAIL);
3450                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3451                                 hotkey_all_mask = 0x080cU;
3452                         } else {
3453                                 tp_features.hotkey_mask = 1;
3454                         }
3455
3456                         /*
3457                          * Check if we have an adaptive keyboard, like on the
3458                          * Lenovo Carbon X1 2014 (2nd Gen).
3459                          */
3460                         if (acpi_evalf(hkey_handle, &hotkey_adaptive_all_mask,
3461                                        "MHKA", "dd", 2)) {
3462                                 if (hotkey_adaptive_all_mask != 0) {
3463                                         tp_features.has_adaptive_kbd = true;
3464                                         res = sysfs_create_group(
3465                                                 &tpacpi_pdev->dev.kobj,
3466                                                 &adaptive_kbd_attr_group);
3467                                         if (res)
3468                                                 goto err_exit;
3469                                 }
3470                         } else {
3471                                 tp_features.has_adaptive_kbd = false;
3472                                 hotkey_adaptive_all_mask = 0x0U;
3473                         }
3474                         break;
3475
3476                 default:
3477                         pr_err("unknown version of the HKEY interface: 0x%x\n",
3478                                hkeyv);
3479                         pr_err("please report this to %s\n", TPACPI_MAIL);
3480                         break;
3481                 }
3482         }
3483
3484         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3485                 "hotkey masks are %s\n",
3486                 str_supported(tp_features.hotkey_mask));
3487
3488         /* Init hotkey_all_mask if not initialized yet */
3489         if (!tp_features.hotkey_mask && !hotkey_all_mask &&
3490             (quirks & TPACPI_HK_Q_INIMASK))
3491                 hotkey_all_mask = 0x080cU;  /* FN+F12, FN+F4, FN+F3 */
3492
3493         /* Init hotkey_acpi_mask and hotkey_orig_mask */
3494         if (tp_features.hotkey_mask) {
3495                 /* hotkey_source_mask *must* be zero for
3496                  * the first hotkey_mask_get to return hotkey_orig_mask */
3497                 res = hotkey_mask_get();
3498                 if (res)
3499                         goto err_exit;
3500
3501                 hotkey_orig_mask = hotkey_acpi_mask;
3502         } else {
3503                 hotkey_orig_mask = hotkey_all_mask;
3504                 hotkey_acpi_mask = hotkey_all_mask;
3505         }
3506
3507 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3508         if (dbg_wlswemul) {
3509                 tp_features.hotkey_wlsw = 1;
3510                 radiosw_state = !!tpacpi_wlsw_emulstate;
3511                 pr_info("radio switch emulation enabled\n");
3512         } else
3513 #endif
3514         /* Not all thinkpads have a hardware radio switch */
3515         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
3516                 tp_features.hotkey_wlsw = 1;
3517                 radiosw_state = !!status;
3518                 pr_info("radio switch found; radios are %s\n",
3519                         enabled(status, 0));
3520         }
3521         if (tp_features.hotkey_wlsw)
3522                 res = add_to_attr_set(hotkey_dev_attributes,
3523                                 &dev_attr_hotkey_radio_sw.attr);
3524
3525         res = hotkey_init_tablet_mode();
3526         if (res < 0)
3527                 goto err_exit;
3528
3529         tabletsw_state = res;
3530
3531         res = register_attr_set_with_sysfs(hotkey_dev_attributes,
3532                                            &tpacpi_pdev->dev.kobj);
3533         if (res)
3534                 goto err_exit;
3535
3536         /* Set up key map */
3537         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
3538                                         GFP_KERNEL);
3539         if (!hotkey_keycode_map) {
3540                 pr_err("failed to allocate memory for key map\n");
3541                 res = -ENOMEM;
3542                 goto err_exit;
3543         }
3544
3545         keymap_id = tpacpi_check_quirks(tpacpi_keymap_qtable,
3546                                         ARRAY_SIZE(tpacpi_keymap_qtable));
3547         BUG_ON(keymap_id >= ARRAY_SIZE(tpacpi_keymaps));
3548         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3549                    "using keymap number %lu\n", keymap_id);
3550
3551         memcpy(hotkey_keycode_map, &tpacpi_keymaps[keymap_id],
3552                 TPACPI_HOTKEY_MAP_SIZE);
3553
3554         input_set_capability(tpacpi_inputdev, EV_MSC, MSC_SCAN);
3555         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
3556         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
3557         tpacpi_inputdev->keycode = hotkey_keycode_map;
3558         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
3559                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
3560                         input_set_capability(tpacpi_inputdev, EV_KEY,
3561                                                 hotkey_keycode_map[i]);
3562                 } else {
3563                         if (i < sizeof(hotkey_reserved_mask)*8)
3564                                 hotkey_reserved_mask |= 1 << i;
3565                 }
3566         }
3567
3568         if (tp_features.hotkey_wlsw) {
3569                 input_set_capability(tpacpi_inputdev, EV_SW, SW_RFKILL_ALL);
3570                 input_report_switch(tpacpi_inputdev,
3571                                     SW_RFKILL_ALL, radiosw_state);
3572         }
3573         if (tp_features.hotkey_tablet) {
3574                 input_set_capability(tpacpi_inputdev, EV_SW, SW_TABLET_MODE);
3575                 input_report_switch(tpacpi_inputdev,
3576                                     SW_TABLET_MODE, tabletsw_state);
3577         }
3578
3579         /* Do not issue duplicate brightness change events to
3580          * userspace. tpacpi_detect_brightness_capabilities() must have
3581          * been called before this point  */
3582         if (acpi_video_get_backlight_type() != acpi_backlight_vendor) {
3583                 pr_info("This ThinkPad has standard ACPI backlight brightness control, supported by the ACPI video driver\n");
3584                 pr_notice("Disabling thinkpad-acpi brightness events by default...\n");
3585
3586                 /* Disable brightness up/down on Lenovo thinkpads when
3587                  * ACPI is handling them, otherwise it is plain impossible
3588                  * for userspace to do something even remotely sane */
3589                 hotkey_reserved_mask |=
3590                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
3591                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
3592                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME);
3593                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND);
3594         }
3595
3596 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3597         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
3598                                 & ~hotkey_all_mask
3599                                 & ~hotkey_reserved_mask;
3600
3601         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3602                     "hotkey source mask 0x%08x, polling freq %u\n",
3603                     hotkey_source_mask, hotkey_poll_freq);
3604 #endif
3605
3606         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3607                         "enabling firmware HKEY event interface...\n");
3608         res = hotkey_status_set(true);
3609         if (res) {
3610                 hotkey_exit();
3611                 return res;
3612         }
3613         res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask)
3614                                | hotkey_driver_mask)
3615                               & ~hotkey_source_mask);
3616         if (res < 0 && res != -ENXIO) {
3617                 hotkey_exit();
3618                 return res;
3619         }
3620         hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask)
3621                                 & ~hotkey_reserved_mask;
3622         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3623                 "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n",
3624                 hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask);
3625
3626         tpacpi_inputdev->open = &hotkey_inputdev_open;
3627         tpacpi_inputdev->close = &hotkey_inputdev_close;
3628
3629         hotkey_poll_setup_safe(true);
3630
3631         return 0;
3632
3633 err_exit:
3634         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3635         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3636                         &adaptive_kbd_attr_group);
3637
3638         hotkey_dev_attributes = NULL;
3639
3640         return (res < 0) ? res : 1;
3641 }
3642
3643 /* Thinkpad X1 Carbon support 5 modes including Home mode, Web browser
3644  * mode, Web conference mode, Function mode and Lay-flat mode.
3645  * We support Home mode and Function mode currently.
3646  *
3647  * Will consider support rest of modes in future.
3648  *
3649  */
3650 static const int adaptive_keyboard_modes[] = {
3651         HOME_MODE,
3652 /*      WEB_BROWSER_MODE = 2,
3653         WEB_CONFERENCE_MODE = 3, */
3654         FUNCTION_MODE
3655 };
3656
3657 #define DFR_CHANGE_ROW                  0x101
3658 #define DFR_SHOW_QUICKVIEW_ROW          0x102
3659 #define FIRST_ADAPTIVE_KEY              0x103
3660
3661 /* press Fn key a while second, it will switch to Function Mode. Then
3662  * release Fn key, previous mode be restored.
3663  */
3664 static bool adaptive_keyboard_mode_is_saved;
3665 static int adaptive_keyboard_prev_mode;
3666
3667 static int adaptive_keyboard_get_mode(void)
3668 {
3669         int mode = 0;
3670
3671         if (!acpi_evalf(hkey_handle, &mode, "GTRW", "dd", 0)) {
3672                 pr_err("Cannot read adaptive keyboard mode\n");
3673                 return -EIO;
3674         }
3675
3676         return mode;
3677 }
3678
3679 static int adaptive_keyboard_set_mode(int new_mode)
3680 {
3681         if (new_mode < 0 ||
3682                 new_mode > LAYFLAT_MODE)
3683                 return -EINVAL;
3684
3685         if (!acpi_evalf(hkey_handle, NULL, "STRW", "vd", new_mode)) {
3686                 pr_err("Cannot set adaptive keyboard mode\n");
3687                 return -EIO;
3688         }
3689
3690         return 0;
3691 }
3692
3693 static int adaptive_keyboard_get_next_mode(int mode)
3694 {
3695         size_t i;
3696         size_t max_mode = ARRAY_SIZE(adaptive_keyboard_modes) - 1;
3697
3698         for (i = 0; i <= max_mode; i++) {
3699                 if (adaptive_keyboard_modes[i] == mode)
3700                         break;
3701         }
3702
3703         if (i >= max_mode)
3704                 i = 0;
3705         else
3706                 i++;
3707
3708         return adaptive_keyboard_modes[i];
3709 }
3710
3711 static bool adaptive_keyboard_hotkey_notify_hotkey(unsigned int scancode)
3712 {
3713         int current_mode = 0;
3714         int new_mode = 0;
3715         int keycode;
3716
3717         switch (scancode) {
3718         case DFR_CHANGE_ROW:
3719                 if (adaptive_keyboard_mode_is_saved) {
3720                         new_mode = adaptive_keyboard_prev_mode;
3721                         adaptive_keyboard_mode_is_saved = false;
3722                 } else {
3723                         current_mode = adaptive_keyboard_get_mode();
3724                         if (current_mode < 0)
3725                                 return false;
3726                         new_mode = adaptive_keyboard_get_next_mode(
3727                                         current_mode);
3728                 }
3729
3730                 if (adaptive_keyboard_set_mode(new_mode) < 0)
3731                         return false;
3732
3733                 return true;
3734
3735         case DFR_SHOW_QUICKVIEW_ROW:
3736                 current_mode = adaptive_keyboard_get_mode();
3737                 if (current_mode < 0)
3738                         return false;
3739
3740                 adaptive_keyboard_prev_mode = current_mode;
3741                 adaptive_keyboard_mode_is_saved = true;
3742
3743                 if (adaptive_keyboard_set_mode (FUNCTION_MODE) < 0)
3744                         return false;
3745                 return true;
3746
3747         default:
3748                 if (scancode < FIRST_ADAPTIVE_KEY ||
3749                     scancode >= FIRST_ADAPTIVE_KEY +
3750                     TP_ACPI_HOTKEYSCAN_EXTENDED_START -
3751                     TP_ACPI_HOTKEYSCAN_ADAPTIVE_START) {
3752                         pr_info("Unhandled adaptive keyboard key: 0x%x\n",
3753                                 scancode);
3754                         return false;
3755                 }
3756                 keycode = hotkey_keycode_map[scancode - FIRST_ADAPTIVE_KEY +
3757                                              TP_ACPI_HOTKEYSCAN_ADAPTIVE_START];
3758                 if (keycode != KEY_RESERVED) {
3759                         mutex_lock(&tpacpi_inputdev_send_mutex);
3760
3761                         input_report_key(tpacpi_inputdev, keycode, 1);
3762                         input_sync(tpacpi_inputdev);
3763
3764                         input_report_key(tpacpi_inputdev, keycode, 0);
3765                         input_sync(tpacpi_inputdev);
3766
3767                         mutex_unlock(&tpacpi_inputdev_send_mutex);
3768                 }
3769                 return true;
3770         }
3771 }
3772
3773 static bool hotkey_notify_hotkey(const u32 hkey,
3774                                  bool *send_acpi_ev,
3775                                  bool *ignore_acpi_ev)
3776 {
3777         /* 0x1000-0x1FFF: key presses */
3778         unsigned int scancode = hkey & 0xfff;
3779         *send_acpi_ev = true;
3780         *ignore_acpi_ev = false;
3781
3782         /*
3783          * Original events are in the 0x10XX range, the adaptive keyboard
3784          * found in 2014 X1 Carbon emits events are of 0x11XX. In 2017
3785          * models, additional keys are emitted through 0x13XX.
3786          */
3787         switch ((hkey >> 8) & 0xf) {
3788         case 0:
3789                 if (scancode > 0 &&
3790                     scancode <= TP_ACPI_HOTKEYSCAN_ADAPTIVE_START) {
3791                         /* HKEY event 0x1001 is scancode 0x00 */
3792                         scancode--;
3793                         if (!(hotkey_source_mask & (1 << scancode))) {
3794                                 tpacpi_input_send_key_masked(scancode);
3795                                 *send_acpi_ev = false;
3796                         } else {
3797                                 *ignore_acpi_ev = true;
3798                         }
3799                         return true;
3800                 }
3801                 break;
3802
3803         case 1:
3804                 return adaptive_keyboard_hotkey_notify_hotkey(scancode);
3805
3806         case 3:
3807                 /* Extended keycodes start at 0x300 and our offset into the map
3808                  * TP_ACPI_HOTKEYSCAN_EXTENDED_START. The calculated scancode
3809                  * will be positive, but might not be in the correct range.
3810                  */
3811                 scancode -= (0x300 - TP_ACPI_HOTKEYSCAN_EXTENDED_START);
3812                 if (scancode >= TP_ACPI_HOTKEYSCAN_EXTENDED_START &&
3813                     scancode < TPACPI_HOTKEY_MAP_LEN) {
3814                         tpacpi_input_send_key(scancode);
3815                         return true;
3816                 }
3817                 break;
3818         }
3819
3820         return false;
3821 }
3822
3823 static bool hotkey_notify_wakeup(const u32 hkey,
3824                                  bool *send_acpi_ev,
3825                                  bool *ignore_acpi_ev)
3826 {
3827         /* 0x2000-0x2FFF: Wakeup reason */
3828         *send_acpi_ev = true;
3829         *ignore_acpi_ev = false;
3830
3831         switch (hkey) {
3832         case TP_HKEY_EV_WKUP_S3_UNDOCK: /* suspend, undock */
3833         case TP_HKEY_EV_WKUP_S4_UNDOCK: /* hibernation, undock */
3834                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3835                 *ignore_acpi_ev = true;
3836                 break;
3837
3838         case TP_HKEY_EV_WKUP_S3_BAYEJ: /* suspend, bay eject */
3839         case TP_HKEY_EV_WKUP_S4_BAYEJ: /* hibernation, bay eject */
3840                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3841                 *ignore_acpi_ev = true;
3842                 break;
3843
3844         case TP_HKEY_EV_WKUP_S3_BATLOW: /* Battery on critical low level/S3 */
3845         case TP_HKEY_EV_WKUP_S4_BATLOW: /* Battery on critical low level/S4 */
3846                 pr_alert("EMERGENCY WAKEUP: battery almost empty\n");
3847                 /* how to auto-heal: */
3848                 /* 2313: woke up from S3, go to S4/S5 */
3849                 /* 2413: woke up from S4, go to S5 */
3850                 break;
3851
3852         default:
3853                 return false;
3854         }
3855
3856         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3857                 pr_info("woke up due to a hot-unplug request...\n");
3858                 hotkey_wakeup_reason_notify_change();
3859         }
3860         return true;
3861 }
3862
3863 static bool hotkey_notify_dockevent(const u32 hkey,
3864                                  bool *send_acpi_ev,
3865                                  bool *ignore_acpi_ev)
3866 {
3867         /* 0x4000-0x4FFF: dock-related events */
3868         *send_acpi_ev = true;
3869         *ignore_acpi_ev = false;
3870
3871         switch (hkey) {
3872         case TP_HKEY_EV_UNDOCK_ACK:
3873                 /* ACPI undock operation completed after wakeup */
3874                 hotkey_autosleep_ack = 1;
3875                 pr_info("undocked\n");
3876                 hotkey_wakeup_hotunplug_complete_notify_change();
3877                 return true;
3878
3879         case TP_HKEY_EV_HOTPLUG_DOCK: /* docked to port replicator */
3880                 pr_info("docked into hotplug port replicator\n");
3881                 return true;
3882         case TP_HKEY_EV_HOTPLUG_UNDOCK: /* undocked from port replicator */
3883                 pr_info("undocked from hotplug port replicator\n");
3884                 return true;
3885
3886         default:
3887                 return false;
3888         }
3889 }
3890
3891 static bool hotkey_notify_usrevent(const u32 hkey,
3892                                  bool *send_acpi_ev,
3893                                  bool *ignore_acpi_ev)
3894 {
3895         /* 0x5000-0x5FFF: human interface helpers */
3896         *send_acpi_ev = true;
3897         *ignore_acpi_ev = false;
3898
3899         switch (hkey) {
3900         case TP_HKEY_EV_PEN_INSERTED:  /* X61t: tablet pen inserted into bay */
3901         case TP_HKEY_EV_PEN_REMOVED:   /* X61t: tablet pen removed from bay */
3902                 return true;
3903
3904         case TP_HKEY_EV_TABLET_TABLET:   /* X41t-X61t: tablet mode */
3905         case TP_HKEY_EV_TABLET_NOTEBOOK: /* X41t-X61t: normal mode */
3906                 tpacpi_input_send_tabletsw();
3907                 hotkey_tablet_mode_notify_change();
3908                 *send_acpi_ev = false;
3909                 return true;
3910
3911         case TP_HKEY_EV_LID_CLOSE:      /* Lid closed */
3912         case TP_HKEY_EV_LID_OPEN:       /* Lid opened */
3913         case TP_HKEY_EV_BRGHT_CHANGED:  /* brightness changed */
3914                 /* do not propagate these events */
3915                 *ignore_acpi_ev = true;
3916                 return true;
3917
3918         default:
3919                 return false;
3920         }
3921 }
3922
3923 static void thermal_dump_all_sensors(void);
3924
3925 static bool hotkey_notify_6xxx(const u32 hkey,
3926                                  bool *send_acpi_ev,
3927                                  bool *ignore_acpi_ev)
3928 {
3929         bool known = true;
3930
3931         /* 0x6000-0x6FFF: thermal alarms/notices and keyboard events */
3932         *send_acpi_ev = true;
3933         *ignore_acpi_ev = false;
3934
3935         switch (hkey) {
3936         case TP_HKEY_EV_THM_TABLE_CHANGED:
3937                 pr_info("EC reports that Thermal Table has changed\n");
3938                 /* recommended action: do nothing, we don't have
3939                  * Lenovo ATM information */
3940                 return true;
3941         case TP_HKEY_EV_ALARM_BAT_HOT:
3942                 pr_crit("THERMAL ALARM: battery is too hot!\n");
3943                 /* recommended action: warn user through gui */
3944                 break;
3945         case TP_HKEY_EV_ALARM_BAT_XHOT:
3946                 pr_alert("THERMAL EMERGENCY: battery is extremely hot!\n");
3947                 /* recommended action: immediate sleep/hibernate */
3948                 break;
3949         case TP_HKEY_EV_ALARM_SENSOR_HOT:
3950                 pr_crit("THERMAL ALARM: a sensor reports something is too hot!\n");
3951                 /* recommended action: warn user through gui, that */
3952                 /* some internal component is too hot */
3953                 break;
3954         case TP_HKEY_EV_ALARM_SENSOR_XHOT:
3955                 pr_alert("THERMAL EMERGENCY: a sensor reports something is extremely hot!\n");
3956                 /* recommended action: immediate sleep/hibernate */
3957                 break;
3958         case TP_HKEY_EV_AC_CHANGED:
3959                 /* X120e, X121e, X220, X220i, X220t, X230, T420, T420s, W520:
3960                  * AC status changed; can be triggered by plugging or
3961                  * unplugging AC adapter, docking or undocking. */
3962
3963                 /* fallthrough */
3964
3965         case TP_HKEY_EV_KEY_NUMLOCK:
3966         case TP_HKEY_EV_KEY_FN:
3967         case TP_HKEY_EV_KEY_FN_ESC:
3968                 /* key press events, we just ignore them as long as the EC
3969                  * is still reporting them in the normal keyboard stream */
3970                 *send_acpi_ev = false;
3971                 *ignore_acpi_ev = true;
3972                 return true;
3973
3974         case TP_HKEY_EV_TABLET_CHANGED:
3975                 tpacpi_input_send_tabletsw();
3976                 hotkey_tablet_mode_notify_change();
3977                 *send_acpi_ev = false;
3978                 break;
3979
3980         case TP_HKEY_EV_PALM_DETECTED:
3981         case TP_HKEY_EV_PALM_UNDETECTED:
3982                 /* palm detected hovering the keyboard, forward to user-space
3983                  * via netlink for consumption */
3984                 return true;
3985
3986         default:
3987                 pr_warn("unknown possible thermal alarm or keyboard event received\n");
3988                 known = false;
3989         }
3990
3991         thermal_dump_all_sensors();
3992
3993         return known;
3994 }
3995
3996 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3997 {
3998         u32 hkey;
3999         bool send_acpi_ev;
4000         bool ignore_acpi_ev;
4001         bool known_ev;
4002
4003         if (event != 0x80) {
4004                 pr_err("unknown HKEY notification event %d\n", event);
4005                 /* forward it to userspace, maybe it knows how to handle it */
4006                 acpi_bus_generate_netlink_event(
4007                                         ibm->acpi->device->pnp.device_class,
4008                                         dev_name(&ibm->acpi->device->dev),
4009                                         event, 0);
4010                 return;
4011         }
4012
4013         while (1) {
4014                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
4015                         pr_err("failed to retrieve HKEY event\n");
4016                         return;
4017                 }
4018
4019                 if (hkey == 0) {
4020                         /* queue empty */
4021                         return;
4022                 }
4023
4024                 send_acpi_ev = true;
4025                 ignore_acpi_ev = false;
4026
4027                 switch (hkey >> 12) {
4028                 case 1:
4029                         /* 0x1000-0x1FFF: key presses */
4030                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
4031                                                  &ignore_acpi_ev);
4032                         break;
4033                 case 2:
4034                         /* 0x2000-0x2FFF: Wakeup reason */
4035                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
4036                                                  &ignore_acpi_ev);
4037                         break;
4038                 case 3:
4039                         /* 0x3000-0x3FFF: bay-related wakeups */
4040                         switch (hkey) {
4041                         case TP_HKEY_EV_BAYEJ_ACK:
4042                                 hotkey_autosleep_ack = 1;
4043                                 pr_info("bay ejected\n");
4044                                 hotkey_wakeup_hotunplug_complete_notify_change();
4045                                 known_ev = true;
4046                                 break;
4047                         case TP_HKEY_EV_OPTDRV_EJ:
4048                                 /* FIXME: kick libata if SATA link offline */
4049                                 known_ev = true;
4050                                 break;
4051                         default:
4052                                 known_ev = false;
4053                         }
4054                         break;
4055                 case 4:
4056                         /* 0x4000-0x4FFF: dock-related events */
4057                         known_ev = hotkey_notify_dockevent(hkey, &send_acpi_ev,
4058                                                 &ignore_acpi_ev);
4059                         break;
4060                 case 5:
4061                         /* 0x5000-0x5FFF: human interface helpers */
4062                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
4063                                                  &ignore_acpi_ev);
4064                         break;
4065                 case 6:
4066                         /* 0x6000-0x6FFF: thermal alarms/notices and
4067                          *                keyboard events */
4068                         known_ev = hotkey_notify_6xxx(hkey, &send_acpi_ev,
4069                                                  &ignore_acpi_ev);
4070                         break;
4071                 case 7:
4072                         /* 0x7000-0x7FFF: misc */
4073                         if (tp_features.hotkey_wlsw &&
4074                                         hkey == TP_HKEY_EV_RFKILL_CHANGED) {
4075                                 tpacpi_send_radiosw_update();
4076                                 send_acpi_ev = 0;
4077                                 known_ev = true;
4078                                 break;
4079                         }
4080                         /* fallthrough to default */
4081                 default:
4082                         known_ev = false;
4083                 }
4084                 if (!known_ev) {
4085                         pr_notice("unhandled HKEY event 0x%04x\n", hkey);
4086                         pr_notice("please report the conditions when this event happened to %s\n",
4087                                   TPACPI_MAIL);
4088                 }
4089
4090                 /* netlink events */
4091                 if (!ignore_acpi_ev && send_acpi_ev) {
4092                         acpi_bus_generate_netlink_event(
4093                                         ibm->acpi->device->pnp.device_class,
4094                                         dev_name(&ibm->acpi->device->dev),
4095                                         event, hkey);
4096                 }
4097         }
4098 }
4099
4100 static void hotkey_suspend(void)
4101 {
4102         /* Do these on suspend, we get the events on early resume! */
4103         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
4104         hotkey_autosleep_ack = 0;
4105
4106         /* save previous mode of adaptive keyboard of X1 Carbon */
4107         if (tp_features.has_adaptive_kbd) {
4108                 if (!acpi_evalf(hkey_handle, &adaptive_keyboard_prev_mode,
4109                                         "GTRW", "dd", 0)) {
4110                         pr_err("Cannot read adaptive keyboard mode.\n");
4111                 }
4112         }
4113 }
4114
4115 static void hotkey_resume(void)
4116 {
4117         tpacpi_disable_brightness_delay();
4118
4119         if (hotkey_status_set(true) < 0 ||
4120             hotkey_mask_set(hotkey_acpi_mask) < 0)
4121                 pr_err("error while attempting to reset the event firmware interface\n");
4122
4123         tpacpi_send_radiosw_update();
4124         hotkey_tablet_mode_notify_change();
4125         hotkey_wakeup_reason_notify_change();
4126         hotkey_wakeup_hotunplug_complete_notify_change();
4127         hotkey_poll_setup_safe(false);
4128
4129         /* restore previous mode of adapive keyboard of X1 Carbon */
4130         if (tp_features.has_adaptive_kbd) {
4131                 if (!acpi_evalf(hkey_handle, NULL, "STRW", "vd",
4132                                         adaptive_keyboard_prev_mode)) {
4133                         pr_err("Cannot set adaptive keyboard mode.\n");
4134                 }
4135         }
4136 }
4137
4138 /* procfs -------------------------------------------------------------- */
4139 static int hotkey_read(struct seq_file *m)
4140 {
4141         int res, status;
4142
4143         if (!tp_features.hotkey) {
4144                 seq_printf(m, "status:\t\tnot supported\n");
4145                 return 0;
4146         }
4147
4148         if (mutex_lock_killable(&hotkey_mutex))
4149                 return -ERESTARTSYS;
4150         res = hotkey_status_get(&status);
4151         if (!res)
4152                 res = hotkey_mask_get();
4153         mutex_unlock(&hotkey_mutex);
4154         if (res)
4155                 return res;
4156
4157         seq_printf(m, "status:\t\t%s\n", enabled(status, 0));
4158         if (hotkey_all_mask) {
4159                 seq_printf(m, "mask:\t\t0x%08x\n", hotkey_user_mask);
4160                 seq_printf(m, "commands:\tenable, disable, reset, <mask>\n");
4161         } else {
4162                 seq_printf(m, "mask:\t\tnot supported\n");
4163                 seq_printf(m, "commands:\tenable, disable, reset\n");
4164         }
4165
4166         return 0;
4167 }
4168
4169 static void hotkey_enabledisable_warn(bool enable)
4170 {
4171         tpacpi_log_usertask("procfs hotkey enable/disable");
4172         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
4173                   pr_fmt("hotkey enable/disable functionality has been removed from the driver.  Hotkeys are always enabled.\n")))
4174                 pr_err("Please remove the hotkey=enable module parameter, it is deprecated.  Hotkeys are always enabled.\n");
4175 }
4176
4177 static int hotkey_write(char *buf)
4178 {
4179         int res;
4180         u32 mask;
4181         char *cmd;
4182
4183         if (!tp_features.hotkey)
4184                 return -ENODEV;
4185
4186         if (mutex_lock_killable(&hotkey_mutex))
4187                 return -ERESTARTSYS;
4188
4189         mask = hotkey_user_mask;
4190
4191         res = 0;
4192         while ((cmd = next_cmd(&buf))) {
4193                 if (strlencmp(cmd, "enable") == 0) {
4194                         hotkey_enabledisable_warn(1);
4195                 } else if (strlencmp(cmd, "disable") == 0) {
4196                         hotkey_enabledisable_warn(0);
4197                         res = -EPERM;
4198                 } else if (strlencmp(cmd, "reset") == 0) {
4199                         mask = (hotkey_all_mask | hotkey_source_mask)
4200                                 & ~hotkey_reserved_mask;
4201                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
4202                         /* mask set */
4203                 } else if (sscanf(cmd, "%x", &mask) == 1) {
4204                         /* mask set */
4205                 } else {
4206                         res = -EINVAL;
4207                         goto errexit;
4208                 }
4209         }
4210
4211         if (!res) {
4212                 tpacpi_disclose_usertask("procfs hotkey",
4213                         "set mask to 0x%08x\n", mask);
4214                 res = hotkey_user_mask_set(mask);
4215         }
4216
4217 errexit:
4218         mutex_unlock(&hotkey_mutex);
4219         return res;
4220 }
4221
4222 static const struct acpi_device_id ibm_htk_device_ids[] = {
4223         {TPACPI_ACPI_IBM_HKEY_HID, 0},
4224         {TPACPI_ACPI_LENOVO_HKEY_HID, 0},
4225         {TPACPI_ACPI_LENOVO_HKEY_V2_HID, 0},
4226         {"", 0},
4227 };
4228
4229 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
4230         .hid = ibm_htk_device_ids,
4231         .notify = hotkey_notify,
4232         .handle = &hkey_handle,
4233         .type = ACPI_DEVICE_NOTIFY,
4234 };
4235
4236 static struct ibm_struct hotkey_driver_data = {
4237         .name = "hotkey",
4238         .read = hotkey_read,
4239         .write = hotkey_write,
4240         .exit = hotkey_exit,
4241         .resume = hotkey_resume,
4242         .suspend = hotkey_suspend,
4243         .acpi = &ibm_hotkey_acpidriver,
4244 };
4245
4246 /*************************************************************************
4247  * Bluetooth subdriver
4248  */
4249
4250 enum {
4251         /* ACPI GBDC/SBDC bits */
4252         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
4253         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
4254         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
4255                                                    0 = disable, 1 = enable */
4256 };
4257
4258 enum {
4259         /* ACPI \BLTH commands */
4260         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
4261         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
4262         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
4263         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
4264         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
4265 };
4266
4267 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
4268
4269 static int bluetooth_get_status(void)
4270 {
4271         int status;
4272
4273 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4274         if (dbg_bluetoothemul)
4275                 return (tpacpi_bluetooth_emulstate) ?
4276                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4277 #endif
4278
4279         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
4280                 return -EIO;
4281
4282         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
4283                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4284 }
4285
4286 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
4287 {
4288         int status;
4289
4290         vdbg_printk(TPACPI_DBG_RFKILL,
4291                 "will attempt to %s bluetooth\n",
4292                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4293
4294 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4295         if (dbg_bluetoothemul) {
4296                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
4297                 return 0;
4298         }
4299 #endif
4300
4301         if (state == TPACPI_RFK_RADIO_ON)
4302                 status = TP_ACPI_BLUETOOTH_RADIOSSW
4303                           | TP_ACPI_BLUETOOTH_RESUMECTRL;
4304         else
4305                 status = 0;
4306
4307         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
4308                 return -EIO;
4309
4310         return 0;
4311 }
4312
4313 /* sysfs bluetooth enable ---------------------------------------------- */
4314 static ssize_t bluetooth_enable_show(struct device *dev,
4315                            struct device_attribute *attr,
4316                            char *buf)
4317 {
4318         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
4319                         attr, buf);
4320 }
4321
4322 static ssize_t bluetooth_enable_store(struct device *dev,
4323                             struct device_attribute *attr,
4324                             const char *buf, size_t count)
4325 {
4326         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
4327                                 attr, buf, count);
4328 }
4329
4330 static DEVICE_ATTR_RW(bluetooth_enable);
4331
4332 /* --------------------------------------------------------------------- */
4333
4334 static struct attribute *bluetooth_attributes[] = {
4335         &dev_attr_bluetooth_enable.attr,
4336         NULL
4337 };
4338
4339 static const struct attribute_group bluetooth_attr_group = {
4340         .attrs = bluetooth_attributes,
4341 };
4342
4343 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
4344         .get_status = bluetooth_get_status,
4345         .set_status = bluetooth_set_status,
4346 };
4347
4348 static void bluetooth_shutdown(void)
4349 {
4350         /* Order firmware to save current state to NVRAM */
4351         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
4352                         TP_ACPI_BLTH_SAVE_STATE))
4353                 pr_notice("failed to save bluetooth state to NVRAM\n");
4354         else
4355                 vdbg_printk(TPACPI_DBG_RFKILL,
4356                         "bluetooth state saved to NVRAM\n");
4357 }
4358
4359 static void bluetooth_exit(void)
4360 {
4361         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4362                         &bluetooth_attr_group);
4363
4364         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
4365
4366         bluetooth_shutdown();
4367 }
4368
4369 static int __init bluetooth_init(struct ibm_init_struct *iibm)
4370 {
4371         int res;
4372         int status = 0;
4373
4374         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4375                         "initializing bluetooth subdriver\n");
4376
4377         TPACPI_ACPIHANDLE_INIT(hkey);
4378
4379         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4380            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
4381         tp_features.bluetooth = hkey_handle &&
4382             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
4383
4384         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4385                 "bluetooth is %s, status 0x%02x\n",
4386                 str_supported(tp_features.bluetooth),
4387                 status);
4388
4389 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4390         if (dbg_bluetoothemul) {
4391                 tp_features.bluetooth = 1;
4392                 pr_info("bluetooth switch emulation enabled\n");
4393         } else
4394 #endif
4395         if (tp_features.bluetooth &&
4396             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
4397                 /* no bluetooth hardware present in system */
4398                 tp_features.bluetooth = 0;
4399                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4400                            "bluetooth hardware not installed\n");
4401         }
4402
4403         if (!tp_features.bluetooth)
4404                 return 1;
4405
4406         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
4407                                 &bluetooth_tprfk_ops,
4408                                 RFKILL_TYPE_BLUETOOTH,
4409                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
4410                                 true);
4411         if (res)
4412                 return res;
4413
4414         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4415                                 &bluetooth_attr_group);
4416         if (res) {
4417                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
4418                 return res;
4419         }
4420
4421         return 0;
4422 }
4423
4424 /* procfs -------------------------------------------------------------- */
4425 static int bluetooth_read(struct seq_file *m)
4426 {
4427         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, m);
4428 }
4429
4430 static int bluetooth_write(char *buf)
4431 {
4432         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
4433 }
4434
4435 static struct ibm_struct bluetooth_driver_data = {
4436         .name = "bluetooth",
4437         .read = bluetooth_read,
4438         .write = bluetooth_write,
4439         .exit = bluetooth_exit,
4440         .shutdown = bluetooth_shutdown,
4441 };
4442
4443 /*************************************************************************
4444  * Wan subdriver
4445  */
4446
4447 enum {
4448         /* ACPI GWAN/SWAN bits */
4449         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
4450         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
4451         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
4452                                                    0 = disable, 1 = enable */
4453 };
4454
4455 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
4456
4457 static int wan_get_status(void)
4458 {
4459         int status;
4460
4461 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4462         if (dbg_wwanemul)
4463                 return (tpacpi_wwan_emulstate) ?
4464                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4465 #endif
4466
4467         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
4468                 return -EIO;
4469
4470         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
4471                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4472 }
4473
4474 static int wan_set_status(enum tpacpi_rfkill_state state)
4475 {
4476         int status;
4477
4478         vdbg_printk(TPACPI_DBG_RFKILL,
4479                 "will attempt to %s wwan\n",
4480                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4481
4482 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4483         if (dbg_wwanemul) {
4484                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
4485                 return 0;
4486         }
4487 #endif
4488
4489         if (state == TPACPI_RFK_RADIO_ON)
4490                 status = TP_ACPI_WANCARD_RADIOSSW
4491                          | TP_ACPI_WANCARD_RESUMECTRL;
4492         else
4493                 status = 0;
4494
4495         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
4496                 return -EIO;
4497
4498         return 0;
4499 }
4500
4501 /* sysfs wan enable ---------------------------------------------------- */
4502 static ssize_t wan_enable_show(struct device *dev,
4503                            struct device_attribute *attr,
4504                            char *buf)
4505 {
4506         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
4507                         attr, buf);
4508 }
4509
4510 static ssize_t wan_enable_store(struct device *dev,
4511                             struct device_attribute *attr,
4512                             const char *buf, size_t count)
4513 {
4514         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
4515                         attr, buf, count);
4516 }
4517
4518 static DEVICE_ATTR(wwan_enable, S_IWUSR | S_IRUGO,
4519                    wan_enable_show, wan_enable_store);
4520
4521 /* --------------------------------------------------------------------- */
4522
4523 static struct attribute *wan_attributes[] = {
4524         &dev_attr_wwan_enable.attr,
4525         NULL
4526 };
4527
4528 static const struct attribute_group wan_attr_group = {
4529         .attrs = wan_attributes,
4530 };
4531
4532 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
4533         .get_status = wan_get_status,
4534         .set_status = wan_set_status,
4535 };
4536
4537 static void wan_shutdown(void)
4538 {
4539         /* Order firmware to save current state to NVRAM */
4540         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
4541                         TP_ACPI_WGSV_SAVE_STATE))
4542                 pr_notice("failed to save WWAN state to NVRAM\n");
4543         else
4544                 vdbg_printk(TPACPI_DBG_RFKILL,
4545                         "WWAN state saved to NVRAM\n");
4546 }
4547
4548 static void wan_exit(void)
4549 {
4550         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4551                 &wan_attr_group);
4552
4553         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4554
4555         wan_shutdown();
4556 }
4557
4558 static int __init wan_init(struct ibm_init_struct *iibm)
4559 {
4560         int res;
4561         int status = 0;
4562
4563         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4564                         "initializing wan subdriver\n");
4565
4566         TPACPI_ACPIHANDLE_INIT(hkey);
4567
4568         tp_features.wan = hkey_handle &&
4569             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
4570
4571         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4572                 "wan is %s, status 0x%02x\n",
4573                 str_supported(tp_features.wan),
4574                 status);
4575
4576 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4577         if (dbg_wwanemul) {
4578                 tp_features.wan = 1;
4579                 pr_info("wwan switch emulation enabled\n");
4580         } else
4581 #endif
4582         if (tp_features.wan &&
4583             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
4584                 /* no wan hardware present in system */
4585                 tp_features.wan = 0;
4586                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4587                            "wan hardware not installed\n");
4588         }
4589
4590         if (!tp_features.wan)
4591                 return 1;
4592
4593         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
4594                                 &wan_tprfk_ops,
4595                                 RFKILL_TYPE_WWAN,
4596                                 TPACPI_RFK_WWAN_SW_NAME,
4597                                 true);
4598         if (res)
4599                 return res;
4600
4601         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4602                                 &wan_attr_group);
4603
4604         if (res) {
4605                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4606                 return res;
4607         }
4608
4609         return 0;
4610 }
4611
4612 /* procfs -------------------------------------------------------------- */
4613 static int wan_read(struct seq_file *m)
4614 {
4615         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, m);
4616 }
4617
4618 static int wan_write(char *buf)
4619 {
4620         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
4621 }
4622
4623 static struct ibm_struct wan_driver_data = {
4624         .name = "wan",
4625         .read = wan_read,
4626         .write = wan_write,
4627         .exit = wan_exit,
4628         .shutdown = wan_shutdown,
4629 };
4630
4631 /*************************************************************************
4632  * UWB subdriver
4633  */
4634
4635 enum {
4636         /* ACPI GUWB/SUWB bits */
4637         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
4638         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
4639 };
4640
4641 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
4642
4643 static int uwb_get_status(void)
4644 {
4645         int status;
4646
4647 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4648         if (dbg_uwbemul)
4649                 return (tpacpi_uwb_emulstate) ?
4650                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4651 #endif
4652
4653         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
4654                 return -EIO;
4655
4656         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
4657                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4658 }
4659
4660 static int uwb_set_status(enum tpacpi_rfkill_state state)
4661 {
4662         int status;
4663
4664         vdbg_printk(TPACPI_DBG_RFKILL,
4665                 "will attempt to %s UWB\n",
4666                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4667
4668 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4669         if (dbg_uwbemul) {
4670                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
4671                 return 0;
4672         }
4673 #endif
4674
4675         if (state == TPACPI_RFK_RADIO_ON)
4676                 status = TP_ACPI_UWB_RADIOSSW;
4677         else
4678                 status = 0;
4679
4680         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
4681                 return -EIO;
4682
4683         return 0;
4684 }
4685
4686 /* --------------------------------------------------------------------- */
4687
4688 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
4689         .get_status = uwb_get_status,
4690         .set_status = uwb_set_status,
4691 };
4692
4693 static void uwb_exit(void)
4694 {
4695         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
4696 }
4697
4698 static int __init uwb_init(struct ibm_init_struct *iibm)
4699 {
4700         int res;
4701         int status = 0;
4702
4703         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4704                         "initializing uwb subdriver\n");
4705
4706         TPACPI_ACPIHANDLE_INIT(hkey);
4707
4708         tp_features.uwb = hkey_handle &&
4709             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
4710
4711         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4712                 "uwb is %s, status 0x%02x\n",
4713                 str_supported(tp_features.uwb),
4714                 status);
4715
4716 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4717         if (dbg_uwbemul) {
4718                 tp_features.uwb = 1;
4719                 pr_info("uwb switch emulation enabled\n");
4720         } else
4721 #endif
4722         if (tp_features.uwb &&
4723             !(status & TP_ACPI_UWB_HWPRESENT)) {
4724                 /* no uwb hardware present in system */
4725                 tp_features.uwb = 0;
4726                 dbg_printk(TPACPI_DBG_INIT,
4727                            "uwb hardware not installed\n");
4728         }
4729
4730         if (!tp_features.uwb)
4731                 return 1;
4732
4733         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
4734                                 &uwb_tprfk_ops,
4735                                 RFKILL_TYPE_UWB,
4736                                 TPACPI_RFK_UWB_SW_NAME,
4737                                 false);
4738         return res;
4739 }
4740
4741 static struct ibm_struct uwb_driver_data = {
4742         .name = "uwb",
4743         .exit = uwb_exit,
4744         .flags.experimental = 1,
4745 };
4746
4747 /*************************************************************************
4748  * Video subdriver
4749  */
4750
4751 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
4752
4753 enum video_access_mode {
4754         TPACPI_VIDEO_NONE = 0,
4755         TPACPI_VIDEO_570,       /* 570 */
4756         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
4757         TPACPI_VIDEO_NEW,       /* all others */
4758 };
4759
4760 enum {  /* video status flags, based on VIDEO_570 */
4761         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
4762         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
4763         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
4764 };
4765
4766 enum {  /* TPACPI_VIDEO_570 constants */
4767         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
4768         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
4769                                                  * video_status_flags */
4770         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
4771         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
4772 };
4773
4774 static enum video_access_mode video_supported;
4775 static int video_orig_autosw;
4776
4777 static int video_autosw_get(void);
4778 static int video_autosw_set(int enable);
4779
4780 TPACPI_HANDLE(vid, root,
4781               "\\_SB.PCI.AGP.VGA",      /* 570 */
4782               "\\_SB.PCI0.AGP0.VID0",   /* 600e/x, 770x */
4783               "\\_SB.PCI0.VID0",        /* 770e */
4784               "\\_SB.PCI0.VID",         /* A21e, G4x, R50e, X30, X40 */
4785               "\\_SB.PCI0.AGP.VGA",     /* X100e and a few others */
4786               "\\_SB.PCI0.AGP.VID",     /* all others */
4787         );                              /* R30, R31 */
4788
4789 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
4790
4791 static int __init video_init(struct ibm_init_struct *iibm)
4792 {
4793         int ivga;
4794
4795         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
4796
4797         TPACPI_ACPIHANDLE_INIT(vid);
4798         if (tpacpi_is_ibm())
4799                 TPACPI_ACPIHANDLE_INIT(vid2);
4800
4801         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
4802                 /* G41, assume IVGA doesn't change */
4803                 vid_handle = vid2_handle;
4804
4805         if (!vid_handle)
4806                 /* video switching not supported on R30, R31 */
4807                 video_supported = TPACPI_VIDEO_NONE;
4808         else if (tpacpi_is_ibm() &&
4809                  acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
4810                 /* 570 */
4811                 video_supported = TPACPI_VIDEO_570;
4812         else if (tpacpi_is_ibm() &&
4813                  acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
4814                 /* 600e/x, 770e, 770x */
4815                 video_supported = TPACPI_VIDEO_770;
4816         else
4817                 /* all others */
4818                 video_supported = TPACPI_VIDEO_NEW;
4819
4820         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
4821                 str_supported(video_supported != TPACPI_VIDEO_NONE),
4822                 video_supported);
4823
4824         return (video_supported != TPACPI_VIDEO_NONE) ? 0 : 1;
4825 }
4826
4827 static void video_exit(void)
4828 {
4829         dbg_printk(TPACPI_DBG_EXIT,
4830                    "restoring original video autoswitch mode\n");
4831         if (video_autosw_set(video_orig_autosw))
4832                 pr_err("error while trying to restore original video autoswitch mode\n");
4833 }
4834
4835 static int video_outputsw_get(void)
4836 {
4837         int status = 0;
4838         int i;
4839
4840         switch (video_supported) {
4841         case TPACPI_VIDEO_570:
4842                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4843                                  TP_ACPI_VIDEO_570_PHSCMD))
4844                         return -EIO;
4845                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4846                 break;
4847         case TPACPI_VIDEO_770:
4848                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4849                         return -EIO;
4850                 if (i)
4851                         status |= TP_ACPI_VIDEO_S_LCD;
4852                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4853                         return -EIO;
4854                 if (i)
4855                         status |= TP_ACPI_VIDEO_S_CRT;
4856                 break;
4857         case TPACPI_VIDEO_NEW:
4858                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4859                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4860                         return -EIO;
4861                 if (i)
4862                         status |= TP_ACPI_VIDEO_S_CRT;
4863
4864                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4865                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4866                         return -EIO;
4867                 if (i)
4868                         status |= TP_ACPI_VIDEO_S_LCD;
4869                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4870                         return -EIO;
4871                 if (i)
4872                         status |= TP_ACPI_VIDEO_S_DVI;
4873                 break;
4874         default:
4875                 return -ENOSYS;
4876         }
4877
4878         return status;
4879 }
4880
4881 static int video_outputsw_set(int status)
4882 {
4883         int autosw;
4884         int res = 0;
4885
4886         switch (video_supported) {
4887         case TPACPI_VIDEO_570:
4888                 res = acpi_evalf(NULL, NULL,
4889                                  "\\_SB.PHS2", "vdd",
4890                                  TP_ACPI_VIDEO_570_PHS2CMD,
4891                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4892                 break;
4893         case TPACPI_VIDEO_770:
4894                 autosw = video_autosw_get();
4895                 if (autosw < 0)
4896                         return autosw;
4897
4898                 res = video_autosw_set(1);
4899                 if (res)
4900                         return res;
4901                 res = acpi_evalf(vid_handle, NULL,
4902                                  "ASWT", "vdd", status * 0x100, 0);
4903                 if (!autosw && video_autosw_set(autosw)) {
4904                         pr_err("video auto-switch left enabled due to error\n");
4905                         return -EIO;
4906                 }
4907                 break;
4908         case TPACPI_VIDEO_NEW:
4909                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4910                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4911                 break;
4912         default:
4913                 return -ENOSYS;
4914         }
4915
4916         return (res) ? 0 : -EIO;
4917 }
4918
4919 static int video_autosw_get(void)
4920 {
4921         int autosw = 0;
4922
4923         switch (video_supported) {
4924         case TPACPI_VIDEO_570:
4925                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4926                         return -EIO;
4927                 break;
4928         case TPACPI_VIDEO_770:
4929         case TPACPI_VIDEO_NEW:
4930                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4931                         return -EIO;
4932                 break;
4933         default:
4934                 return -ENOSYS;
4935         }
4936
4937         return autosw & 1;
4938 }
4939
4940 static int video_autosw_set(int enable)
4941 {
4942         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable) ? 1 : 0))
4943                 return -EIO;
4944         return 0;
4945 }
4946
4947 static int video_outputsw_cycle(void)
4948 {
4949         int autosw = video_autosw_get();
4950         int res;
4951
4952         if (autosw < 0)
4953                 return autosw;
4954
4955         switch (video_supported) {
4956         case TPACPI_VIDEO_570:
4957                 res = video_autosw_set(1);
4958                 if (res)
4959                         return res;
4960                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4961                 break;
4962         case TPACPI_VIDEO_770:
4963         case TPACPI_VIDEO_NEW:
4964                 res = video_autosw_set(1);
4965                 if (res)
4966                         return res;
4967                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4968                 break;
4969         default:
4970                 return -ENOSYS;
4971         }
4972         if (!autosw && video_autosw_set(autosw)) {
4973                 pr_err("video auto-switch left enabled due to error\n");
4974                 return -EIO;
4975         }
4976
4977         return (res) ? 0 : -EIO;
4978 }
4979
4980 static int video_expand_toggle(void)
4981 {
4982         switch (video_supported) {
4983         case TPACPI_VIDEO_570:
4984                 return acpi_evalf(ec_handle, NULL, "_Q17", "v") ?
4985                         0 : -EIO;
4986         case TPACPI_VIDEO_770:
4987                 return acpi_evalf(vid_handle, NULL, "VEXP", "v") ?
4988                         0 : -EIO;
4989         case TPACPI_VIDEO_NEW:
4990                 return acpi_evalf(NULL, NULL, "\\VEXP", "v") ?
4991                         0 : -EIO;
4992         default:
4993                 return -ENOSYS;
4994         }
4995         /* not reached */
4996 }
4997
4998 static int video_read(struct seq_file *m)
4999 {
5000         int status, autosw;
5001
5002         if (video_supported == TPACPI_VIDEO_NONE) {
5003                 seq_printf(m, "status:\t\tnot supported\n");
5004                 return 0;
5005         }
5006
5007         /* Even reads can crash X.org, so... */
5008         if (!capable(CAP_SYS_ADMIN))
5009                 return -EPERM;
5010
5011         status = video_outputsw_get();
5012         if (status < 0)
5013                 return status;
5014
5015         autosw = video_autosw_get();
5016         if (autosw < 0)
5017                 return autosw;
5018
5019         seq_printf(m, "status:\t\tsupported\n");
5020         seq_printf(m, "lcd:\t\t%s\n", enabled(status, 0));
5021         seq_printf(m, "crt:\t\t%s\n", enabled(status, 1));
5022         if (video_supported == TPACPI_VIDEO_NEW)
5023                 seq_printf(m, "dvi:\t\t%s\n", enabled(status, 3));
5024         seq_printf(m, "auto:\t\t%s\n", enabled(autosw, 0));
5025         seq_printf(m, "commands:\tlcd_enable, lcd_disable\n");
5026         seq_printf(m, "commands:\tcrt_enable, crt_disable\n");
5027         if (video_supported == TPACPI_VIDEO_NEW)
5028                 seq_printf(m, "commands:\tdvi_enable, dvi_disable\n");
5029         seq_printf(m, "commands:\tauto_enable, auto_disable\n");
5030         seq_printf(m, "commands:\tvideo_switch, expand_toggle\n");
5031
5032         return 0;
5033 }
5034
5035 static int video_write(char *buf)
5036 {
5037         char *cmd;
5038         int enable, disable, status;
5039         int res;
5040
5041         if (video_supported == TPACPI_VIDEO_NONE)
5042                 return -ENODEV;
5043
5044         /* Even reads can crash X.org, let alone writes... */
5045         if (!capable(CAP_SYS_ADMIN))
5046                 return -EPERM;
5047
5048         enable = 0;
5049         disable = 0;
5050
5051         while ((cmd = next_cmd(&buf))) {
5052                 if (strlencmp(cmd, "lcd_enable") == 0) {
5053                         enable |= TP_ACPI_VIDEO_S_LCD;
5054                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
5055                         disable |= TP_ACPI_VIDEO_S_LCD;
5056                 } else if (strlencmp(cmd, "crt_enable") == 0) {
5057                         enable |= TP_ACPI_VIDEO_S_CRT;
5058                 } else if (strlencmp(cmd, "crt_disable") == 0) {
5059                         disable |= TP_ACPI_VIDEO_S_CRT;
5060                 } else if (video_supported == TPACPI_VIDEO_NEW &&
5061                            strlencmp(cmd, "dvi_enable") == 0) {
5062                         enable |= TP_ACPI_VIDEO_S_DVI;
5063                 } else if (video_supported == TPACPI_VIDEO_NEW &&
5064                            strlencmp(cmd, "dvi_disable") == 0) {
5065                         disable |= TP_ACPI_VIDEO_S_DVI;
5066                 } else if (strlencmp(cmd, "auto_enable") == 0) {
5067                         res = video_autosw_set(1);
5068                         if (res)
5069                                 return res;
5070                 } else if (strlencmp(cmd, "auto_disable") == 0) {
5071                         res = video_autosw_set(0);
5072                         if (res)
5073                                 return res;
5074                 } else if (strlencmp(cmd, "video_switch") == 0) {
5075                         res = video_outputsw_cycle();
5076                         if (res)
5077                                 return res;
5078                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
5079                         res = video_expand_toggle();
5080                         if (res)
5081                                 return res;
5082                 } else
5083                         return -EINVAL;
5084         }
5085
5086         if (enable || disable) {
5087                 status = video_outputsw_get();
5088                 if (status < 0)
5089                         return status;
5090                 res = video_outputsw_set((status & ~disable) | enable);
5091                 if (res)
5092                         return res;
5093         }
5094
5095         return 0;
5096 }
5097
5098 static struct ibm_struct video_driver_data = {
5099         .name = "video",
5100         .read = video_read,
5101         .write = video_write,
5102         .exit = video_exit,
5103 };
5104
5105 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
5106
5107 /*************************************************************************
5108  * Keyboard backlight subdriver
5109  */
5110
5111 static enum led_brightness kbdlight_brightness;
5112 static DEFINE_MUTEX(kbdlight_mutex);
5113
5114 static int kbdlight_set_level(int level)
5115 {
5116         int ret = 0;
5117
5118         if (!hkey_handle)
5119                 return -ENXIO;
5120
5121         mutex_lock(&kbdlight_mutex);
5122
5123         if (!acpi_evalf(hkey_handle, NULL, "MLCS", "dd", level))
5124                 ret = -EIO;
5125         else
5126                 kbdlight_brightness = level;
5127
5128         mutex_unlock(&kbdlight_mutex);
5129
5130         return ret;
5131 }
5132
5133 static int kbdlight_get_level(void)
5134 {
5135         int status = 0;
5136
5137         if (!hkey_handle)
5138                 return -ENXIO;
5139
5140         if (!acpi_evalf(hkey_handle, &status, "MLCG", "dd", 0))
5141                 return -EIO;
5142
5143         if (status < 0)
5144                 return status;
5145
5146         return status & 0x3;
5147 }
5148
5149 static bool kbdlight_is_supported(void)
5150 {
5151         int status = 0;
5152
5153         if (!hkey_handle)
5154                 return false;
5155
5156         if (!acpi_has_method(hkey_handle, "MLCG")) {
5157                 vdbg_printk(TPACPI_DBG_INIT, "kbdlight MLCG is unavailable\n");
5158                 return false;
5159         }
5160
5161         if (!acpi_evalf(hkey_handle, &status, "MLCG", "qdd", 0)) {
5162                 vdbg_printk(TPACPI_DBG_INIT, "kbdlight MLCG failed\n");
5163                 return false;
5164         }
5165
5166         if (status < 0) {
5167                 vdbg_printk(TPACPI_DBG_INIT, "kbdlight MLCG err: %d\n", status);
5168                 return false;
5169         }
5170
5171         vdbg_printk(TPACPI_DBG_INIT, "kbdlight MLCG returned 0x%x\n", status);
5172         /*
5173          * Guessed test for keyboard backlight:
5174          *
5175          * Machines with backlight keyboard return:
5176          *   b010100000010000000XX - ThinkPad X1 Carbon 3rd
5177          *   b110100010010000000XX - ThinkPad x230
5178          *   b010100000010000000XX - ThinkPad x240
5179          *   b010100000010000000XX - ThinkPad W541
5180          * (XX is current backlight level)
5181          *
5182          * Machines without backlight keyboard return:
5183          *   b10100001000000000000 - ThinkPad x230
5184          *   b10110001000000000000 - ThinkPad E430
5185          *   b00000000000000000000 - ThinkPad E450
5186          *
5187          * Candidate BITs for detection test (XOR):
5188          *   b01000000001000000000
5189          *              ^
5190          */
5191         return status & BIT(9);
5192 }
5193
5194 static int kbdlight_sysfs_set(struct led_classdev *led_cdev,
5195                         enum led_brightness brightness)
5196 {
5197         return kbdlight_set_level(brightness);
5198 }
5199
5200 static enum led_brightness kbdlight_sysfs_get(struct led_classdev *led_cdev)
5201 {
5202         int level;
5203
5204         level = kbdlight_get_level();
5205         if (level < 0)
5206                 return 0;
5207
5208         return level;
5209 }
5210
5211 static struct tpacpi_led_classdev tpacpi_led_kbdlight = {
5212         .led_classdev = {
5213                 .name           = "tpacpi::kbd_backlight",
5214                 .max_brightness = 2,
5215                 .flags          = LED_BRIGHT_HW_CHANGED,
5216                 .brightness_set_blocking = &kbdlight_sysfs_set,
5217                 .brightness_get = &kbdlight_sysfs_get,
5218         }
5219 };
5220
5221 static int __init kbdlight_init(struct ibm_init_struct *iibm)
5222 {
5223         int rc;
5224
5225         vdbg_printk(TPACPI_DBG_INIT, "initializing kbdlight subdriver\n");
5226
5227         TPACPI_ACPIHANDLE_INIT(hkey);
5228
5229         if (!kbdlight_is_supported()) {
5230                 tp_features.kbdlight = 0;
5231                 vdbg_printk(TPACPI_DBG_INIT, "kbdlight is unsupported\n");
5232                 return 1;
5233         }
5234
5235         kbdlight_brightness = kbdlight_sysfs_get(NULL);
5236         tp_features.kbdlight = 1;
5237
5238         rc = led_classdev_register(&tpacpi_pdev->dev,
5239                                    &tpacpi_led_kbdlight.led_classdev);
5240         if (rc < 0) {
5241                 tp_features.kbdlight = 0;
5242                 return rc;
5243         }
5244
5245         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask |
5246                                       TP_ACPI_HKEY_KBD_LIGHT_MASK);
5247         return 0;
5248 }
5249
5250 static void kbdlight_exit(void)
5251 {
5252         if (tp_features.kbdlight)
5253                 led_classdev_unregister(&tpacpi_led_kbdlight.led_classdev);
5254 }
5255
5256 static int kbdlight_set_level_and_update(int level)
5257 {
5258         int ret;
5259         struct led_classdev *led_cdev;
5260
5261         ret = kbdlight_set_level(level);
5262         led_cdev = &tpacpi_led_kbdlight.led_classdev;
5263
5264         if (ret == 0 && !(led_cdev->flags & LED_SUSPENDED))
5265                 led_cdev->brightness = level;
5266
5267         return ret;
5268 }
5269
5270 static int kbdlight_read(struct seq_file *m)
5271 {
5272         int level;
5273
5274         if (!tp_features.kbdlight) {
5275                 seq_printf(m, "status:\t\tnot supported\n");
5276         } else {
5277                 level = kbdlight_get_level();
5278                 if (level < 0)
5279                         seq_printf(m, "status:\t\terror %d\n", level);
5280                 else
5281                         seq_printf(m, "status:\t\t%d\n", level);
5282                 seq_printf(m, "commands:\t0, 1, 2\n");
5283         }
5284
5285         return 0;
5286 }
5287
5288 static int kbdlight_write(char *buf)
5289 {
5290         char *cmd;
5291         int level = -1;
5292
5293         if (!tp_features.kbdlight)
5294                 return -ENODEV;
5295
5296         while ((cmd = next_cmd(&buf))) {
5297                 if (strlencmp(cmd, "0") == 0)
5298                         level = 0;
5299                 else if (strlencmp(cmd, "1") == 0)
5300                         level = 1;
5301                 else if (strlencmp(cmd, "2") == 0)
5302                         level = 2;
5303                 else
5304                         return -EINVAL;
5305         }
5306
5307         if (level == -1)
5308                 return -EINVAL;
5309
5310         return kbdlight_set_level_and_update(level);
5311 }
5312
5313 static void kbdlight_suspend(void)
5314 {
5315         struct led_classdev *led_cdev;
5316
5317         if (!tp_features.kbdlight)
5318                 return;
5319
5320         led_cdev = &tpacpi_led_kbdlight.led_classdev;
5321         led_update_brightness(led_cdev);
5322         led_classdev_suspend(led_cdev);
5323 }
5324
5325 static void kbdlight_resume(void)
5326 {
5327         if (!tp_features.kbdlight)
5328                 return;
5329
5330         led_classdev_resume(&tpacpi_led_kbdlight.led_classdev);
5331 }
5332
5333 static struct ibm_struct kbdlight_driver_data = {
5334         .name = "kbdlight",
5335         .read = kbdlight_read,
5336         .write = kbdlight_write,
5337         .suspend = kbdlight_suspend,
5338         .resume = kbdlight_resume,
5339         .exit = kbdlight_exit,
5340 };
5341
5342 /*************************************************************************
5343  * Light (thinklight) subdriver
5344  */
5345
5346 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
5347 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
5348
5349 static int light_get_status(void)
5350 {
5351         int status = 0;
5352
5353         if (tp_features.light_status) {
5354                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
5355                         return -EIO;
5356                 return (!!status);
5357         }
5358
5359         return -ENXIO;
5360 }
5361
5362 static int light_set_status(int status)
5363 {
5364         int rc;
5365
5366         if (tp_features.light) {
5367                 if (cmos_handle) {
5368                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
5369                                         (status) ?
5370                                                 TP_CMOS_THINKLIGHT_ON :
5371                                                 TP_CMOS_THINKLIGHT_OFF);
5372                 } else {
5373                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
5374                                         (status) ? 1 : 0);
5375                 }
5376                 return (rc) ? 0 : -EIO;
5377         }
5378
5379         return -ENXIO;
5380 }
5381
5382 static int light_sysfs_set(struct led_classdev *led_cdev,
5383                         enum led_brightness brightness)
5384 {
5385         return light_set_status((brightness != LED_OFF) ?
5386                                 TPACPI_LED_ON : TPACPI_LED_OFF);
5387 }
5388
5389 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
5390 {
5391         return (light_get_status() == 1) ? LED_FULL : LED_OFF;
5392 }
5393
5394 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
5395         .led_classdev = {
5396                 .name           = "tpacpi::thinklight",
5397                 .brightness_set_blocking = &light_sysfs_set,
5398                 .brightness_get = &light_sysfs_get,
5399         }
5400 };
5401
5402 static int __init light_init(struct ibm_init_struct *iibm)
5403 {
5404         int rc;
5405
5406         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
5407
5408         if (tpacpi_is_ibm()) {
5409                 TPACPI_ACPIHANDLE_INIT(ledb);
5410                 TPACPI_ACPIHANDLE_INIT(lght);
5411         }
5412         TPACPI_ACPIHANDLE_INIT(cmos);
5413
5414         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
5415         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
5416
5417         if (tp_features.light)
5418                 /* light status not supported on
5419                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
5420                 tp_features.light_status =
5421                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
5422
5423         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
5424                 str_supported(tp_features.light),
5425                 str_supported(tp_features.light_status));
5426
5427         if (!tp_features.light)
5428                 return 1;
5429
5430         rc = led_classdev_register(&tpacpi_pdev->dev,
5431                                    &tpacpi_led_thinklight.led_classdev);
5432
5433         if (rc < 0) {
5434                 tp_features.light = 0;
5435                 tp_features.light_status = 0;
5436         } else  {
5437                 rc = 0;
5438         }
5439
5440         return rc;
5441 }
5442
5443 static void light_exit(void)
5444 {
5445         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
5446 }
5447
5448 static int light_read(struct seq_file *m)
5449 {
5450         int status;
5451
5452         if (!tp_features.light) {
5453                 seq_printf(m, "status:\t\tnot supported\n");
5454         } else if (!tp_features.light_status) {
5455                 seq_printf(m, "status:\t\tunknown\n");
5456                 seq_printf(m, "commands:\ton, off\n");
5457         } else {
5458                 status = light_get_status();
5459                 if (status < 0)
5460                         return status;
5461                 seq_printf(m, "status:\t\t%s\n", onoff(status, 0));
5462                 seq_printf(m, "commands:\ton, off\n");
5463         }
5464
5465         return 0;
5466 }
5467
5468 static int light_write(char *buf)
5469 {
5470         char *cmd;
5471         int newstatus = 0;
5472
5473         if (!tp_features.light)
5474                 return -ENODEV;
5475
5476         while ((cmd = next_cmd(&buf))) {
5477                 if (strlencmp(cmd, "on") == 0) {
5478                         newstatus = 1;
5479                 } else if (strlencmp(cmd, "off") == 0) {
5480                         newstatus = 0;
5481                 } else
5482                         return -EINVAL;
5483         }
5484
5485         return light_set_status(newstatus);
5486 }
5487
5488 static struct ibm_struct light_driver_data = {
5489         .name = "light",
5490         .read = light_read,
5491         .write = light_write,
5492         .exit = light_exit,
5493 };
5494
5495 /*************************************************************************
5496  * CMOS subdriver
5497  */
5498
5499 /* sysfs cmos_command -------------------------------------------------- */
5500 static ssize_t cmos_command_store(struct device *dev,
5501                             struct device_attribute *attr,
5502                             const char *buf, size_t count)
5503 {
5504         unsigned long cmos_cmd;
5505         int res;
5506
5507         if (parse_strtoul(buf, 21, &cmos_cmd))
5508                 return -EINVAL;
5509
5510         res = issue_thinkpad_cmos_command(cmos_cmd);
5511         return (res) ? res : count;
5512 }
5513
5514 static DEVICE_ATTR_WO(cmos_command);
5515
5516 /* --------------------------------------------------------------------- */
5517
5518 static int __init cmos_init(struct ibm_init_struct *iibm)
5519 {
5520         int res;
5521
5522         vdbg_printk(TPACPI_DBG_INIT,
5523                 "initializing cmos commands subdriver\n");
5524
5525         TPACPI_ACPIHANDLE_INIT(cmos);
5526
5527         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
5528                 str_supported(cmos_handle != NULL));
5529
5530         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
5531         if (res)
5532                 return res;
5533
5534         return (cmos_handle) ? 0 : 1;
5535 }
5536
5537 static void cmos_exit(void)
5538 {
5539         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
5540 }
5541
5542 static int cmos_read(struct seq_file *m)
5543 {
5544         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
5545            R30, R31, T20-22, X20-21 */
5546         if (!cmos_handle)
5547                 seq_printf(m, "status:\t\tnot supported\n");
5548         else {
5549                 seq_printf(m, "status:\t\tsupported\n");
5550                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-21)\n");
5551         }
5552
5553         return 0;
5554 }
5555
5556 static int cmos_write(char *buf)
5557 {
5558         char *cmd;
5559         int cmos_cmd, res;
5560
5561         while ((cmd = next_cmd(&buf))) {
5562                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
5563                     cmos_cmd >= 0 && cmos_cmd <= 21) {
5564                         /* cmos_cmd set */
5565                 } else
5566                         return -EINVAL;
5567
5568                 res = issue_thinkpad_cmos_command(cmos_cmd);
5569                 if (res)
5570                         return res;
5571         }
5572
5573         return 0;
5574 }
5575
5576 static struct ibm_struct cmos_driver_data = {
5577         .name = "cmos",
5578         .read = cmos_read,
5579         .write = cmos_write,
5580         .exit = cmos_exit,
5581 };
5582
5583 /*************************************************************************
5584  * LED subdriver
5585  */
5586
5587 enum led_access_mode {
5588         TPACPI_LED_NONE = 0,
5589         TPACPI_LED_570, /* 570 */
5590         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5591         TPACPI_LED_NEW, /* all others */
5592 };
5593
5594 enum {  /* For TPACPI_LED_OLD */
5595         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
5596         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
5597         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
5598 };
5599
5600 static enum led_access_mode led_supported;
5601
5602 static acpi_handle led_handle;
5603
5604 #define TPACPI_LED_NUMLEDS 16
5605 static struct tpacpi_led_classdev *tpacpi_leds;
5606 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
5607 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
5608         /* there's a limit of 19 chars + NULL before 2.6.26 */
5609         "tpacpi::power",
5610         "tpacpi:orange:batt",
5611         "tpacpi:green:batt",
5612         "tpacpi::dock_active",
5613         "tpacpi::bay_active",
5614         "tpacpi::dock_batt",
5615         "tpacpi::unknown_led",
5616         "tpacpi::standby",
5617         "tpacpi::dock_status1",
5618         "tpacpi::dock_status2",
5619         "tpacpi::unknown_led2",
5620         "tpacpi::unknown_led3",
5621         "tpacpi::thinkvantage",
5622 };
5623 #define TPACPI_SAFE_LEDS        0x1081U
5624
5625 static inline bool tpacpi_is_led_restricted(const unsigned int led)
5626 {
5627 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5628         return false;
5629 #else
5630         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
5631 #endif
5632 }
5633
5634 static int led_get_status(const unsigned int led)
5635 {
5636         int status;
5637         enum led_status_t led_s;
5638
5639         switch (led_supported) {
5640         case TPACPI_LED_570:
5641                 if (!acpi_evalf(ec_handle,
5642                                 &status, "GLED", "dd", 1 << led))
5643                         return -EIO;
5644                 led_s = (status == 0) ?
5645                                 TPACPI_LED_OFF :
5646                                 ((status == 1) ?
5647                                         TPACPI_LED_ON :
5648                                         TPACPI_LED_BLINK);
5649                 tpacpi_led_state_cache[led] = led_s;
5650                 return led_s;
5651         default:
5652                 return -ENXIO;
5653         }
5654
5655         /* not reached */
5656 }
5657
5658 static int led_set_status(const unsigned int led,
5659                           const enum led_status_t ledstatus)
5660 {
5661         /* off, on, blink. Index is led_status_t */
5662         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
5663         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
5664
5665         int rc = 0;
5666
5667         switch (led_supported) {
5668         case TPACPI_LED_570:
5669                 /* 570 */
5670                 if (unlikely(led > 7))
5671                         return -EINVAL;
5672                 if (unlikely(tpacpi_is_led_restricted(led)))
5673                         return -EPERM;
5674                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5675                                 (1 << led), led_sled_arg1[ledstatus]))
5676                         rc = -EIO;
5677                 break;
5678         case TPACPI_LED_OLD:
5679                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
5680                 if (unlikely(led > 7))
5681                         return -EINVAL;
5682                 if (unlikely(tpacpi_is_led_restricted(led)))
5683                         return -EPERM;
5684                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
5685                 if (rc >= 0)
5686                         rc = ec_write(TPACPI_LED_EC_HLBL,
5687                                       (ledstatus == TPACPI_LED_BLINK) << led);
5688                 if (rc >= 0)
5689                         rc = ec_write(TPACPI_LED_EC_HLCL,
5690                                       (ledstatus != TPACPI_LED_OFF) << led);
5691                 break;
5692         case TPACPI_LED_NEW:
5693                 /* all others */
5694                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
5695                         return -EINVAL;
5696                 if (unlikely(tpacpi_is_led_restricted(led)))
5697                         return -EPERM;
5698                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5699                                 led, led_led_arg1[ledstatus]))
5700                         rc = -EIO;
5701                 break;
5702         default:
5703                 rc = -ENXIO;
5704         }
5705
5706         if (!rc)
5707                 tpacpi_led_state_cache[led] = ledstatus;
5708
5709         return rc;
5710 }
5711
5712 static int led_sysfs_set(struct led_classdev *led_cdev,
5713                         enum led_brightness brightness)
5714 {
5715         struct tpacpi_led_classdev *data = container_of(led_cdev,
5716                              struct tpacpi_led_classdev, led_classdev);
5717         enum led_status_t new_state;
5718
5719         if (brightness == LED_OFF)
5720                 new_state = TPACPI_LED_OFF;
5721         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
5722                 new_state = TPACPI_LED_ON;
5723         else
5724                 new_state = TPACPI_LED_BLINK;
5725
5726         return led_set_status(data->led, new_state);
5727 }
5728
5729 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
5730                         unsigned long *delay_on, unsigned long *delay_off)
5731 {
5732         struct tpacpi_led_classdev *data = container_of(led_cdev,
5733                              struct tpacpi_led_classdev, led_classdev);
5734
5735         /* Can we choose the flash rate? */
5736         if (*delay_on == 0 && *delay_off == 0) {
5737                 /* yes. set them to the hardware blink rate (1 Hz) */
5738                 *delay_on = 500; /* ms */
5739                 *delay_off = 500; /* ms */
5740         } else if ((*delay_on != 500) || (*delay_off != 500))
5741                 return -EINVAL;
5742
5743         return led_set_status(data->led, TPACPI_LED_BLINK);
5744 }
5745
5746 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5747 {
5748         int rc;
5749
5750         struct tpacpi_led_classdev *data = container_of(led_cdev,
5751                              struct tpacpi_led_classdev, led_classdev);
5752
5753         rc = led_get_status(data->led);
5754
5755         if (rc == TPACPI_LED_OFF || rc < 0)
5756                 rc = LED_OFF;   /* no error handling in led class :( */
5757         else
5758                 rc = LED_FULL;
5759
5760         return rc;
5761 }
5762
5763 static void led_exit(void)
5764 {
5765         unsigned int i;
5766
5767         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5768                 if (tpacpi_leds[i].led_classdev.name)
5769                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5770         }
5771
5772         kfree(tpacpi_leds);
5773 }
5774
5775 static int __init tpacpi_init_led(unsigned int led)
5776 {
5777         int rc;
5778
5779         tpacpi_leds[led].led = led;
5780
5781         /* LEDs with no name don't get registered */
5782         if (!tpacpi_led_names[led])
5783                 return 0;
5784
5785         tpacpi_leds[led].led_classdev.brightness_set_blocking = &led_sysfs_set;
5786         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5787         if (led_supported == TPACPI_LED_570)
5788                 tpacpi_leds[led].led_classdev.brightness_get =
5789                                                 &led_sysfs_get;
5790
5791         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5792
5793         rc = led_classdev_register(&tpacpi_pdev->dev,
5794                                 &tpacpi_leds[led].led_classdev);
5795         if (rc < 0)
5796                 tpacpi_leds[led].led_classdev.name = NULL;
5797
5798         return rc;
5799 }
5800
5801 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5802         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5803         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5804         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5805
5806         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5807         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5808         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5809         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5810         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5811         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5812         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5813         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5814
5815         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5816         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5817         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5818         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5819         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5820
5821         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5822         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5823         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5824         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5825
5826         /* (1) - may have excess leds enabled on MSB */
5827
5828         /* Defaults (order matters, keep last, don't reorder!) */
5829         { /* Lenovo */
5830           .vendor = PCI_VENDOR_ID_LENOVO,
5831           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5832           .quirks = 0x1fffU,
5833         },
5834         { /* IBM ThinkPads with no EC version string */
5835           .vendor = PCI_VENDOR_ID_IBM,
5836           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5837           .quirks = 0x00ffU,
5838         },
5839         { /* IBM ThinkPads with EC version string */
5840           .vendor = PCI_VENDOR_ID_IBM,
5841           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5842           .quirks = 0x00bfU,
5843         },
5844 };
5845
5846 #undef TPACPI_LEDQ_IBM
5847 #undef TPACPI_LEDQ_LNV
5848
5849 static enum led_access_mode __init led_init_detect_mode(void)
5850 {
5851         acpi_status status;
5852
5853         if (tpacpi_is_ibm()) {
5854                 /* 570 */
5855                 status = acpi_get_handle(ec_handle, "SLED", &led_handle);
5856                 if (ACPI_SUCCESS(status))
5857                         return TPACPI_LED_570;
5858
5859                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5860                 status = acpi_get_handle(ec_handle, "SYSL", &led_handle);
5861                 if (ACPI_SUCCESS(status))
5862                         return TPACPI_LED_OLD;
5863         }
5864
5865         /* most others */
5866         status = acpi_get_handle(ec_handle, "LED", &led_handle);
5867         if (ACPI_SUCCESS(status))
5868                 return TPACPI_LED_NEW;
5869
5870         /* R30, R31, and unknown firmwares */
5871         led_handle = NULL;
5872         return TPACPI_LED_NONE;
5873 }
5874
5875 static int __init led_init(struct ibm_init_struct *iibm)
5876 {
5877         unsigned int i;
5878         int rc;
5879         unsigned long useful_leds;
5880
5881         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5882
5883         led_supported = led_init_detect_mode();
5884
5885         if (led_supported != TPACPI_LED_NONE) {
5886                 useful_leds = tpacpi_check_quirks(led_useful_qtable,
5887                                 ARRAY_SIZE(led_useful_qtable));
5888
5889                 if (!useful_leds) {
5890                         led_handle = NULL;
5891                         led_supported = TPACPI_LED_NONE;
5892                 }
5893         }
5894
5895         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5896                 str_supported(led_supported), led_supported);
5897
5898         if (led_supported == TPACPI_LED_NONE)
5899                 return 1;
5900
5901         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5902                               GFP_KERNEL);
5903         if (!tpacpi_leds) {
5904                 pr_err("Out of memory for LED data\n");
5905                 return -ENOMEM;
5906         }
5907
5908         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5909                 tpacpi_leds[i].led = -1;
5910
5911                 if (!tpacpi_is_led_restricted(i) &&
5912                     test_bit(i, &useful_leds)) {
5913                         rc = tpacpi_init_led(i);
5914                         if (rc < 0) {
5915                                 led_exit();
5916                                 return rc;
5917                         }
5918                 }
5919         }
5920
5921 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5922         pr_notice("warning: userspace override of important firmware LEDs is enabled\n");
5923 #endif
5924         return 0;
5925 }
5926
5927 #define str_led_status(s) \
5928         ((s) == TPACPI_LED_OFF ? "off" : \
5929                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5930
5931 static int led_read(struct seq_file *m)
5932 {
5933         if (!led_supported) {
5934                 seq_printf(m, "status:\t\tnot supported\n");
5935                 return 0;
5936         }
5937         seq_printf(m, "status:\t\tsupported\n");
5938
5939         if (led_supported == TPACPI_LED_570) {
5940                 /* 570 */
5941                 int i, status;
5942                 for (i = 0; i < 8; i++) {
5943                         status = led_get_status(i);
5944                         if (status < 0)
5945                                 return -EIO;
5946                         seq_printf(m, "%d:\t\t%s\n",
5947                                        i, str_led_status(status));
5948                 }
5949         }
5950
5951         seq_printf(m, "commands:\t<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5952
5953         return 0;
5954 }
5955
5956 static int led_write(char *buf)
5957 {
5958         char *cmd;
5959         int led, rc;
5960         enum led_status_t s;
5961
5962         if (!led_supported)
5963                 return -ENODEV;
5964
5965         while ((cmd = next_cmd(&buf))) {
5966                 if (sscanf(cmd, "%d", &led) != 1)
5967                         return -EINVAL;
5968
5969                 if (led < 0 || led > (TPACPI_LED_NUMLEDS - 1) ||
5970                                 tpacpi_leds[led].led < 0)
5971                         return -ENODEV;
5972
5973                 if (strstr(cmd, "off")) {
5974                         s = TPACPI_LED_OFF;
5975                 } else if (strstr(cmd, "on")) {
5976                         s = TPACPI_LED_ON;
5977                 } else if (strstr(cmd, "blink")) {
5978                         s = TPACPI_LED_BLINK;
5979                 } else {
5980                         return -EINVAL;
5981                 }
5982
5983                 rc = led_set_status(led, s);
5984                 if (rc < 0)
5985                         return rc;
5986         }
5987
5988         return 0;
5989 }
5990
5991 static struct ibm_struct led_driver_data = {
5992         .name = "led",
5993         .read = led_read,
5994         .write = led_write,
5995         .exit = led_exit,
5996 };
5997
5998 /*************************************************************************
5999  * Beep subdriver
6000  */
6001
6002 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
6003
6004 #define TPACPI_BEEP_Q1 0x0001
6005
6006 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
6007         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
6008         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
6009 };
6010
6011 static int __init beep_init(struct ibm_init_struct *iibm)
6012 {
6013         unsigned long quirks;
6014
6015         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
6016
6017         TPACPI_ACPIHANDLE_INIT(beep);
6018
6019         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
6020                 str_supported(beep_handle != NULL));
6021
6022         quirks = tpacpi_check_quirks(beep_quirk_table,
6023                                      ARRAY_SIZE(beep_quirk_table));
6024
6025         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
6026
6027         return (beep_handle) ? 0 : 1;
6028 }
6029
6030 static int beep_read(struct seq_file *m)
6031 {
6032         if (!beep_handle)
6033                 seq_printf(m, "status:\t\tnot supported\n");
6034         else {
6035                 seq_printf(m, "status:\t\tsupported\n");
6036                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-17)\n");
6037         }
6038
6039         return 0;
6040 }
6041
6042 static int beep_write(char *buf)
6043 {
6044         char *cmd;
6045         int beep_cmd;
6046
6047         if (!beep_handle)
6048                 return -ENODEV;
6049
6050         while ((cmd = next_cmd(&buf))) {
6051                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
6052                     beep_cmd >= 0 && beep_cmd <= 17) {
6053                         /* beep_cmd set */
6054                 } else
6055                         return -EINVAL;
6056                 if (tp_features.beep_needs_two_args) {
6057                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
6058                                         beep_cmd, 0))
6059                                 return -EIO;
6060                 } else {
6061                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
6062                                         beep_cmd))
6063                                 return -EIO;
6064                 }
6065         }
6066
6067         return 0;
6068 }
6069
6070 static struct ibm_struct beep_driver_data = {
6071         .name = "beep",
6072         .read = beep_read,
6073         .write = beep_write,
6074 };
6075
6076 /*************************************************************************
6077  * Thermal subdriver
6078  */
6079
6080 enum thermal_access_mode {
6081         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
6082         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
6083         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
6084         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
6085         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
6086 };
6087
6088 enum { /* TPACPI_THERMAL_TPEC_* */
6089         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
6090         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
6091         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
6092
6093         TPACPI_THERMAL_SENSOR_NA = -128000, /* Sensor not available */
6094 };
6095
6096
6097 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
6098 struct ibm_thermal_sensors_struct {
6099         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
6100 };
6101
6102 static enum thermal_access_mode thermal_read_mode;
6103
6104 /* idx is zero-based */
6105 static int thermal_get_sensor(int idx, s32 *value)
6106 {
6107         int t;
6108         s8 tmp;
6109         char tmpi[5];
6110
6111         t = TP_EC_THERMAL_TMP0;
6112
6113         switch (thermal_read_mode) {
6114 #if TPACPI_MAX_THERMAL_SENSORS >= 16
6115         case TPACPI_THERMAL_TPEC_16:
6116                 if (idx >= 8 && idx <= 15) {
6117                         t = TP_EC_THERMAL_TMP8;
6118                         idx -= 8;
6119                 }
6120                 /* fallthrough */
6121 #endif
6122         case TPACPI_THERMAL_TPEC_8:
6123                 if (idx <= 7) {
6124                         if (!acpi_ec_read(t + idx, &tmp))
6125                                 return -EIO;
6126                         *value = tmp * 1000;
6127                         return 0;
6128                 }
6129                 break;
6130
6131         case TPACPI_THERMAL_ACPI_UPDT:
6132                 if (idx <= 7) {
6133                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
6134                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
6135                                 return -EIO;
6136                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
6137                                 return -EIO;
6138                         *value = (t - 2732) * 100;
6139                         return 0;
6140                 }
6141                 break;
6142
6143         case TPACPI_THERMAL_ACPI_TMP07:
6144                 if (idx <= 7) {
6145                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
6146                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
6147                                 return -EIO;
6148                         if (t > 127 || t < -127)
6149                                 t = TP_EC_THERMAL_TMP_NA;
6150                         *value = t * 1000;
6151                         return 0;
6152                 }
6153                 break;
6154
6155         case TPACPI_THERMAL_NONE:
6156         default:
6157                 return -ENOSYS;
6158         }
6159
6160         return -EINVAL;
6161 }
6162
6163 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
6164 {
6165         int res, i;
6166         int n;
6167
6168         n = 8;
6169         i = 0;
6170
6171         if (!s)
6172                 return -EINVAL;
6173
6174         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
6175                 n = 16;
6176
6177         for (i = 0 ; i < n; i++) {
6178                 res = thermal_get_sensor(i, &s->temp[i]);
6179                 if (res)
6180                         return res;
6181         }
6182
6183         return n;
6184 }
6185
6186 static void thermal_dump_all_sensors(void)
6187 {
6188         int n, i;
6189         struct ibm_thermal_sensors_struct t;
6190
6191         n = thermal_get_sensors(&t);
6192         if (n <= 0)
6193                 return;
6194
6195         pr_notice("temperatures (Celsius):");
6196
6197         for (i = 0; i < n; i++) {
6198                 if (t.temp[i] != TPACPI_THERMAL_SENSOR_NA)
6199                         pr_cont(" %d", (int)(t.temp[i] / 1000));
6200                 else
6201                         pr_cont(" N/A");
6202         }
6203
6204         pr_cont("\n");
6205 }
6206
6207 /* sysfs temp##_input -------------------------------------------------- */
6208
6209 static ssize_t thermal_temp_input_show(struct device *dev,
6210                            struct device_attribute *attr,
6211                            char *buf)
6212 {
6213         struct sensor_device_attribute *sensor_attr =
6214                                         to_sensor_dev_attr(attr);
6215         int idx = sensor_attr->index;
6216         s32 value;
6217         int res;
6218
6219         res = thermal_get_sensor(idx, &value);
6220         if (res)
6221                 return res;
6222         if (value == TPACPI_THERMAL_SENSOR_NA)
6223                 return -ENXIO;
6224
6225         return snprintf(buf, PAGE_SIZE, "%d\n", value);
6226 }
6227
6228 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
6229          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
6230                      thermal_temp_input_show, NULL, _idxB)
6231
6232 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
6233         THERMAL_SENSOR_ATTR_TEMP(1, 0),
6234         THERMAL_SENSOR_ATTR_TEMP(2, 1),
6235         THERMAL_SENSOR_ATTR_TEMP(3, 2),
6236         THERMAL_SENSOR_ATTR_TEMP(4, 3),
6237         THERMAL_SENSOR_ATTR_TEMP(5, 4),
6238         THERMAL_SENSOR_ATTR_TEMP(6, 5),
6239         THERMAL_SENSOR_ATTR_TEMP(7, 6),
6240         THERMAL_SENSOR_ATTR_TEMP(8, 7),
6241         THERMAL_SENSOR_ATTR_TEMP(9, 8),
6242         THERMAL_SENSOR_ATTR_TEMP(10, 9),
6243         THERMAL_SENSOR_ATTR_TEMP(11, 10),
6244         THERMAL_SENSOR_ATTR_TEMP(12, 11),
6245         THERMAL_SENSOR_ATTR_TEMP(13, 12),
6246         THERMAL_SENSOR_ATTR_TEMP(14, 13),
6247         THERMAL_SENSOR_ATTR_TEMP(15, 14),
6248         THERMAL_SENSOR_ATTR_TEMP(16, 15),
6249 };
6250
6251 #define THERMAL_ATTRS(X) \
6252         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
6253
6254 static struct attribute *thermal_temp_input_attr[] = {
6255         THERMAL_ATTRS(8),
6256         THERMAL_ATTRS(9),
6257         THERMAL_ATTRS(10),
6258         THERMAL_ATTRS(11),
6259         THERMAL_ATTRS(12),
6260         THERMAL_ATTRS(13),
6261         THERMAL_ATTRS(14),
6262         THERMAL_ATTRS(15),
6263         THERMAL_ATTRS(0),
6264         THERMAL_ATTRS(1),
6265         THERMAL_ATTRS(2),
6266         THERMAL_ATTRS(3),
6267         THERMAL_ATTRS(4),
6268         THERMAL_ATTRS(5),
6269         THERMAL_ATTRS(6),
6270         THERMAL_ATTRS(7),
6271         NULL
6272 };
6273
6274 static const struct attribute_group thermal_temp_input16_group = {
6275         .attrs = thermal_temp_input_attr
6276 };
6277
6278 static const struct attribute_group thermal_temp_input8_group = {
6279         .attrs = &thermal_temp_input_attr[8]
6280 };
6281
6282 #undef THERMAL_SENSOR_ATTR_TEMP
6283 #undef THERMAL_ATTRS
6284
6285 /* --------------------------------------------------------------------- */
6286
6287 static int __init thermal_init(struct ibm_init_struct *iibm)
6288 {
6289         u8 t, ta1, ta2;
6290         int i;
6291         int acpi_tmp7;
6292         int res;
6293
6294         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
6295
6296         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
6297
6298         if (thinkpad_id.ec_model) {
6299                 /*
6300                  * Direct EC access mode: sensors at registers
6301                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
6302                  * non-implemented, thermal sensors return 0x80 when
6303                  * not available
6304                  */
6305
6306                 ta1 = ta2 = 0;
6307                 for (i = 0; i < 8; i++) {
6308                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
6309                                 ta1 |= t;
6310                         } else {
6311                                 ta1 = 0;
6312                                 break;
6313                         }
6314                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
6315                                 ta2 |= t;
6316                         } else {
6317                                 ta1 = 0;
6318                                 break;
6319                         }
6320                 }
6321                 if (ta1 == 0) {
6322                         /* This is sheer paranoia, but we handle it anyway */
6323                         if (acpi_tmp7) {
6324                                 pr_err("ThinkPad ACPI EC access misbehaving, falling back to ACPI TMPx access mode\n");
6325                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
6326                         } else {
6327                                 pr_err("ThinkPad ACPI EC access misbehaving, disabling thermal sensors access\n");
6328                                 thermal_read_mode = TPACPI_THERMAL_NONE;
6329                         }
6330                 } else {
6331                         thermal_read_mode =
6332                             (ta2 != 0) ?
6333                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
6334                 }
6335         } else if (acpi_tmp7) {
6336                 if (tpacpi_is_ibm() &&
6337                     acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
6338                         /* 600e/x, 770e, 770x */
6339                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
6340                 } else {
6341                         /* IBM/LENOVO DSDT EC.TMPx access, max 8 sensors */
6342                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
6343                 }
6344         } else {
6345                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
6346                 thermal_read_mode = TPACPI_THERMAL_NONE;
6347         }
6348
6349         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
6350                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
6351                 thermal_read_mode);
6352
6353         switch (thermal_read_mode) {
6354         case TPACPI_THERMAL_TPEC_16:
6355                 res = sysfs_create_group(&tpacpi_hwmon->kobj,
6356                                 &thermal_temp_input16_group);
6357                 if (res)
6358                         return res;
6359                 break;
6360         case TPACPI_THERMAL_TPEC_8:
6361         case TPACPI_THERMAL_ACPI_TMP07:
6362         case TPACPI_THERMAL_ACPI_UPDT:
6363                 res = sysfs_create_group(&tpacpi_hwmon->kobj,
6364                                 &thermal_temp_input8_group);
6365                 if (res)
6366                         return res;
6367                 break;
6368         case TPACPI_THERMAL_NONE:
6369         default:
6370                 return 1;
6371         }
6372
6373         return 0;
6374 }
6375
6376 static void thermal_exit(void)
6377 {
6378         switch (thermal_read_mode) {
6379         case TPACPI_THERMAL_TPEC_16:
6380                 sysfs_remove_group(&tpacpi_hwmon->kobj,
6381                                    &thermal_temp_input16_group);
6382                 break;
6383         case TPACPI_THERMAL_TPEC_8:
6384         case TPACPI_THERMAL_ACPI_TMP07:
6385         case TPACPI_THERMAL_ACPI_UPDT:
6386                 sysfs_remove_group(&tpacpi_hwmon->kobj,
6387                                    &thermal_temp_input8_group);
6388                 break;
6389         case TPACPI_THERMAL_NONE:
6390         default:
6391                 break;
6392         }
6393 }
6394
6395 static int thermal_read(struct seq_file *m)
6396 {
6397         int n, i;
6398         struct ibm_thermal_sensors_struct t;
6399
6400         n = thermal_get_sensors(&t);
6401         if (unlikely(n < 0))
6402                 return n;
6403
6404         seq_printf(m, "temperatures:\t");
6405
6406         if (n > 0) {
6407                 for (i = 0; i < (n - 1); i++)
6408                         seq_printf(m, "%d ", t.temp[i] / 1000);
6409                 seq_printf(m, "%d\n", t.temp[i] / 1000);
6410         } else
6411                 seq_printf(m, "not supported\n");
6412
6413         return 0;
6414 }
6415
6416 static struct ibm_struct thermal_driver_data = {
6417         .name = "thermal",
6418         .read = thermal_read,
6419         .exit = thermal_exit,
6420 };
6421
6422 /*************************************************************************
6423  * Backlight/brightness subdriver
6424  */
6425
6426 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
6427
6428 /*
6429  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
6430  * CMOS NVRAM byte 0x5E, bits 0-3.
6431  *
6432  * EC HBRV (0x31) has the following layout
6433  *   Bit 7: unknown function
6434  *   Bit 6: unknown function
6435  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
6436  *   Bit 4: must be set to zero to avoid problems
6437  *   Bit 3-0: backlight brightness level
6438  *
6439  * brightness_get_raw returns status data in the HBRV layout
6440  *
6441  * WARNING: The X61 has been verified to use HBRV for something else, so
6442  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
6443  * testing on the very early *60 Lenovo models...
6444  */
6445
6446 enum {
6447         TP_EC_BACKLIGHT = 0x31,
6448
6449         /* TP_EC_BACKLIGHT bitmasks */
6450         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
6451         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
6452         TP_EC_BACKLIGHT_MAPSW = 0x20,
6453 };
6454
6455 enum tpacpi_brightness_access_mode {
6456         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
6457         TPACPI_BRGHT_MODE_EC,           /* EC control */
6458         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
6459         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
6460         TPACPI_BRGHT_MODE_MAX
6461 };
6462
6463 static struct backlight_device *ibm_backlight_device;
6464
6465 static enum tpacpi_brightness_access_mode brightness_mode =
6466                 TPACPI_BRGHT_MODE_MAX;
6467
6468 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
6469
6470 static struct mutex brightness_mutex;
6471
6472 /* NVRAM brightness access,
6473  * call with brightness_mutex held! */
6474 static unsigned int tpacpi_brightness_nvram_get(void)
6475 {
6476         u8 lnvram;
6477
6478         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
6479                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
6480                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
6481         lnvram &= bright_maxlvl;
6482
6483         return lnvram;
6484 }
6485
6486 static void tpacpi_brightness_checkpoint_nvram(void)
6487 {
6488         u8 lec = 0;
6489         u8 b_nvram;
6490
6491         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
6492                 return;
6493
6494         vdbg_printk(TPACPI_DBG_BRGHT,
6495                 "trying to checkpoint backlight level to NVRAM...\n");
6496
6497         if (mutex_lock_killable(&brightness_mutex) < 0)
6498                 return;
6499
6500         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6501                 goto unlock;
6502         lec &= TP_EC_BACKLIGHT_LVLMSK;
6503         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
6504
6505         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
6506                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
6507                 /* NVRAM needs update */
6508                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
6509                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
6510                 b_nvram |= lec;
6511                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
6512                 dbg_printk(TPACPI_DBG_BRGHT,
6513                            "updated NVRAM backlight level to %u (0x%02x)\n",
6514                            (unsigned int) lec, (unsigned int) b_nvram);
6515         } else
6516                 vdbg_printk(TPACPI_DBG_BRGHT,
6517                            "NVRAM backlight level already is %u (0x%02x)\n",
6518                            (unsigned int) lec, (unsigned int) b_nvram);
6519
6520 unlock:
6521         mutex_unlock(&brightness_mutex);
6522 }
6523
6524
6525 /* call with brightness_mutex held! */
6526 static int tpacpi_brightness_get_raw(int *status)
6527 {
6528         u8 lec = 0;
6529
6530         switch (brightness_mode) {
6531         case TPACPI_BRGHT_MODE_UCMS_STEP:
6532                 *status = tpacpi_brightness_nvram_get();
6533                 return 0;
6534         case TPACPI_BRGHT_MODE_EC:
6535         case TPACPI_BRGHT_MODE_ECNVRAM:
6536                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6537                         return -EIO;
6538                 *status = lec;
6539                 return 0;
6540         default:
6541                 return -ENXIO;
6542         }
6543 }
6544
6545 /* call with brightness_mutex held! */
6546 /* do NOT call with illegal backlight level value */
6547 static int tpacpi_brightness_set_ec(unsigned int value)
6548 {
6549         u8 lec = 0;
6550
6551         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6552                 return -EIO;
6553
6554         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
6555                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
6556                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
6557                 return -EIO;
6558
6559         return 0;
6560 }
6561
6562 /* call with brightness_mutex held! */
6563 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
6564 {
6565         int cmos_cmd, inc;
6566         unsigned int current_value, i;
6567
6568         current_value = tpacpi_brightness_nvram_get();
6569
6570         if (value == current_value)
6571                 return 0;
6572
6573         cmos_cmd = (value > current_value) ?
6574                         TP_CMOS_BRIGHTNESS_UP :
6575                         TP_CMOS_BRIGHTNESS_DOWN;
6576         inc = (value > current_value) ? 1 : -1;
6577
6578         for (i = current_value; i != value; i += inc)
6579                 if (issue_thinkpad_cmos_command(cmos_cmd))
6580                         return -EIO;
6581
6582         return 0;
6583 }
6584
6585 /* May return EINTR which can always be mapped to ERESTARTSYS */
6586 static int brightness_set(unsigned int value)
6587 {
6588         int res;
6589
6590         if (value > bright_maxlvl)
6591                 return -EINVAL;
6592
6593         vdbg_printk(TPACPI_DBG_BRGHT,
6594                         "set backlight level to %d\n", value);
6595
6596         res = mutex_lock_killable(&brightness_mutex);
6597         if (res < 0)
6598                 return res;
6599
6600         switch (brightness_mode) {
6601         case TPACPI_BRGHT_MODE_EC:
6602         case TPACPI_BRGHT_MODE_ECNVRAM:
6603                 res = tpacpi_brightness_set_ec(value);
6604                 break;
6605         case TPACPI_BRGHT_MODE_UCMS_STEP:
6606                 res = tpacpi_brightness_set_ucmsstep(value);
6607                 break;
6608         default:
6609                 res = -ENXIO;
6610         }
6611
6612         mutex_unlock(&brightness_mutex);
6613         return res;
6614 }
6615
6616 /* sysfs backlight class ----------------------------------------------- */
6617
6618 static int brightness_update_status(struct backlight_device *bd)
6619 {
6620         unsigned int level =
6621                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
6622                  bd->props.power == FB_BLANK_UNBLANK) ?
6623                                 bd->props.brightness : 0;
6624
6625         dbg_printk(TPACPI_DBG_BRGHT,
6626                         "backlight: attempt to set level to %d\n",
6627                         level);
6628
6629         /* it is the backlight class's job (caller) to handle
6630          * EINTR and other errors properly */
6631         return brightness_set(level);
6632 }
6633
6634 static int brightness_get(struct backlight_device *bd)
6635 {
6636         int status, res;
6637
6638         res = mutex_lock_killable(&brightness_mutex);
6639         if (res < 0)
6640                 return 0;
6641
6642         res = tpacpi_brightness_get_raw(&status);
6643
6644         mutex_unlock(&brightness_mutex);
6645
6646         if (res < 0)
6647                 return 0;
6648
6649         return status & TP_EC_BACKLIGHT_LVLMSK;
6650 }
6651
6652 static void tpacpi_brightness_notify_change(void)
6653 {
6654         backlight_force_update(ibm_backlight_device,
6655                                BACKLIGHT_UPDATE_HOTKEY);
6656 }
6657
6658 static const struct backlight_ops ibm_backlight_data = {
6659         .get_brightness = brightness_get,
6660         .update_status  = brightness_update_status,
6661 };
6662
6663 /* --------------------------------------------------------------------- */
6664
6665 /*
6666  * Call _BCL method of video device.  On some ThinkPads this will
6667  * switch the firmware to the ACPI brightness control mode.
6668  */
6669
6670 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
6671 {
6672         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
6673         union acpi_object *obj;
6674         struct acpi_device *device, *child;
6675         int rc;
6676
6677         if (acpi_bus_get_device(handle, &device))
6678                 return 0;
6679
6680         rc = 0;
6681         list_for_each_entry(child, &device->children, node) {
6682                 acpi_status status = acpi_evaluate_object(child->handle, "_BCL",
6683                                                           NULL, &buffer);
6684                 if (ACPI_FAILURE(status))
6685                         continue;
6686
6687                 obj = (union acpi_object *)buffer.pointer;
6688                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
6689                         pr_err("Unknown _BCL data, please report this to %s\n",
6690                                 TPACPI_MAIL);
6691                         rc = 0;
6692                 } else {
6693                         rc = obj->package.count;
6694                 }
6695                 break;
6696         }
6697
6698         kfree(buffer.pointer);
6699         return rc;
6700 }
6701
6702
6703 /*
6704  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
6705  */
6706 static unsigned int __init tpacpi_check_std_acpi_brightness_support(void)
6707 {
6708         acpi_handle video_device;
6709         int bcl_levels = 0;
6710
6711         tpacpi_acpi_handle_locate("video", NULL, &video_device);
6712         if (video_device)
6713                 bcl_levels = tpacpi_query_bcl_levels(video_device);
6714
6715         tp_features.bright_acpimode = (bcl_levels > 0);
6716
6717         return (bcl_levels > 2) ? (bcl_levels - 2) : 0;
6718 }
6719
6720 /*
6721  * These are only useful for models that have only one possibility
6722  * of GPU.  If the BIOS model handles both ATI and Intel, don't use
6723  * these quirks.
6724  */
6725 #define TPACPI_BRGHT_Q_NOEC     0x0001  /* Must NOT use EC HBRV */
6726 #define TPACPI_BRGHT_Q_EC       0x0002  /* Should or must use EC HBRV */
6727 #define TPACPI_BRGHT_Q_ASK      0x8000  /* Ask for user report */
6728
6729 static const struct tpacpi_quirk brightness_quirk_table[] __initconst = {
6730         /* Models with ATI GPUs known to require ECNVRAM mode */
6731         TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC),      /* T43/p ATI */
6732
6733         /* Models with ATI GPUs that can use ECNVRAM */
6734         TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC),      /* R50,51 T40-42 */
6735         TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6736         TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_EC),      /* R52 */
6737         TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6738
6739         /* Models with Intel Extreme Graphics 2 */
6740         TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC),    /* X40 */
6741         TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6742         TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6743
6744         /* Models with Intel GMA900 */
6745         TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC),    /* T43, R52 */
6746         TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC),    /* X41 */
6747         TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC),    /* X41 Tablet */
6748 };
6749
6750 /*
6751  * Returns < 0 for error, otherwise sets tp_features.bright_*
6752  * and bright_maxlvl.
6753  */
6754 static void __init tpacpi_detect_brightness_capabilities(void)
6755 {
6756         unsigned int b;
6757
6758         vdbg_printk(TPACPI_DBG_INIT,
6759                     "detecting firmware brightness interface capabilities\n");
6760
6761         /* we could run a quirks check here (same table used by
6762          * brightness_init) if needed */
6763
6764         /*
6765          * We always attempt to detect acpi support, so as to switch
6766          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
6767          * going to publish a backlight interface
6768          */
6769         b = tpacpi_check_std_acpi_brightness_support();
6770         switch (b) {
6771         case 16:
6772                 bright_maxlvl = 15;
6773                 break;
6774         case 8:
6775         case 0:
6776                 bright_maxlvl = 7;
6777                 break;
6778         default:
6779                 tp_features.bright_unkfw = 1;
6780                 bright_maxlvl = b - 1;
6781         }
6782         pr_debug("detected %u brightness levels\n", bright_maxlvl + 1);
6783 }
6784
6785 static int __init brightness_init(struct ibm_init_struct *iibm)
6786 {
6787         struct backlight_properties props;
6788         int b;
6789         unsigned long quirks;
6790
6791         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
6792
6793         mutex_init(&brightness_mutex);
6794
6795         quirks = tpacpi_check_quirks(brightness_quirk_table,
6796                                 ARRAY_SIZE(brightness_quirk_table));
6797
6798         /* tpacpi_detect_brightness_capabilities() must have run already */
6799
6800         /* if it is unknown, we don't handle it: it wouldn't be safe */
6801         if (tp_features.bright_unkfw)
6802                 return 1;
6803
6804         if (!brightness_enable) {
6805                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6806                            "brightness support disabled by module parameter\n");
6807                 return 1;
6808         }
6809
6810         if (acpi_video_get_backlight_type() != acpi_backlight_vendor) {
6811                 if (brightness_enable > 1) {
6812                         pr_info("Standard ACPI backlight interface available, not loading native one\n");
6813                         return 1;
6814                 } else if (brightness_enable == 1) {
6815                         pr_warn("Cannot enable backlight brightness support, ACPI is already handling it.  Refer to the acpi_backlight kernel parameter.\n");
6816                         return 1;
6817                 }
6818         } else if (tp_features.bright_acpimode && brightness_enable > 1) {
6819                 pr_notice("Standard ACPI backlight interface not available, thinkpad_acpi native brightness control enabled\n");
6820         }
6821
6822         /*
6823          * Check for module parameter bogosity, note that we
6824          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6825          * able to detect "unspecified"
6826          */
6827         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6828                 return -EINVAL;
6829
6830         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6831         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6832             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6833                 if (quirks & TPACPI_BRGHT_Q_EC)
6834                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6835                 else
6836                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6837
6838                 dbg_printk(TPACPI_DBG_BRGHT,
6839                            "driver auto-selected brightness_mode=%d\n",
6840                            brightness_mode);
6841         }
6842
6843         /* Safety */
6844         if (!tpacpi_is_ibm() &&
6845             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6846              brightness_mode == TPACPI_BRGHT_MODE_EC))
6847                 return -EINVAL;
6848
6849         if (tpacpi_brightness_get_raw(&b) < 0)
6850                 return 1;
6851
6852         memset(&props, 0, sizeof(struct backlight_properties));
6853         props.type = BACKLIGHT_PLATFORM;
6854         props.max_brightness = bright_maxlvl;
6855         props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6856         ibm_backlight_device = backlight_device_register(TPACPI_BACKLIGHT_DEV_NAME,
6857                                                          NULL, NULL,
6858                                                          &ibm_backlight_data,
6859                                                          &props);
6860         if (IS_ERR(ibm_backlight_device)) {
6861                 int rc = PTR_ERR(ibm_backlight_device);
6862                 ibm_backlight_device = NULL;
6863                 pr_err("Could not register backlight device\n");
6864                 return rc;
6865         }
6866         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6867                         "brightness is supported\n");
6868
6869         if (quirks & TPACPI_BRGHT_Q_ASK) {
6870                 pr_notice("brightness: will use unverified default: brightness_mode=%d\n",
6871                           brightness_mode);
6872                 pr_notice("brightness: please report to %s whether it works well or not on your ThinkPad\n",
6873                           TPACPI_MAIL);
6874         }
6875
6876         /* Added by mistake in early 2007.  Probably useless, but it could
6877          * be working around some unknown firmware problem where the value
6878          * read at startup doesn't match the real hardware state... so leave
6879          * it in place just in case */
6880         backlight_update_status(ibm_backlight_device);
6881
6882         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6883                     "brightness: registering brightness hotkeys as change notification\n");
6884         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
6885                                 | TP_ACPI_HKEY_BRGHTUP_MASK
6886                                 | TP_ACPI_HKEY_BRGHTDWN_MASK);
6887         return 0;
6888 }
6889
6890 static void brightness_suspend(void)
6891 {
6892         tpacpi_brightness_checkpoint_nvram();
6893 }
6894
6895 static void brightness_shutdown(void)
6896 {
6897         tpacpi_brightness_checkpoint_nvram();
6898 }
6899
6900 static void brightness_exit(void)
6901 {
6902         if (ibm_backlight_device) {
6903                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6904                             "calling backlight_device_unregister()\n");
6905                 backlight_device_unregister(ibm_backlight_device);
6906         }
6907
6908         tpacpi_brightness_checkpoint_nvram();
6909 }
6910
6911 static int brightness_read(struct seq_file *m)
6912 {
6913         int level;
6914
6915         level = brightness_get(NULL);
6916         if (level < 0) {
6917                 seq_printf(m, "level:\t\tunreadable\n");
6918         } else {
6919                 seq_printf(m, "level:\t\t%d\n", level);
6920                 seq_printf(m, "commands:\tup, down\n");
6921                 seq_printf(m, "commands:\tlevel <level> (<level> is 0-%d)\n",
6922                                bright_maxlvl);
6923         }
6924
6925         return 0;
6926 }
6927
6928 static int brightness_write(char *buf)
6929 {
6930         int level;
6931         int rc;
6932         char *cmd;
6933
6934         level = brightness_get(NULL);
6935         if (level < 0)
6936                 return level;
6937
6938         while ((cmd = next_cmd(&buf))) {
6939                 if (strlencmp(cmd, "up") == 0) {
6940                         if (level < bright_maxlvl)
6941                                 level++;
6942                 } else if (strlencmp(cmd, "down") == 0) {
6943                         if (level > 0)
6944                                 level--;
6945                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6946                            level >= 0 && level <= bright_maxlvl) {
6947                         /* new level set */
6948                 } else
6949                         return -EINVAL;
6950         }
6951
6952         tpacpi_disclose_usertask("procfs brightness",
6953                         "set level to %d\n", level);
6954
6955         /*
6956          * Now we know what the final level should be, so we try to set it.
6957          * Doing it this way makes the syscall restartable in case of EINTR
6958          */
6959         rc = brightness_set(level);
6960         if (!rc && ibm_backlight_device)
6961                 backlight_force_update(ibm_backlight_device,
6962                                         BACKLIGHT_UPDATE_SYSFS);
6963         return (rc == -EINTR) ? -ERESTARTSYS : rc;
6964 }
6965
6966 static struct ibm_struct brightness_driver_data = {
6967         .name = "brightness",
6968         .read = brightness_read,
6969         .write = brightness_write,
6970         .exit = brightness_exit,
6971         .suspend = brightness_suspend,
6972         .shutdown = brightness_shutdown,
6973 };
6974
6975 /*************************************************************************
6976  * Volume subdriver
6977  */
6978
6979 /*
6980  * IBM ThinkPads have a simple volume controller with MUTE gating.
6981  * Very early Lenovo ThinkPads follow the IBM ThinkPad spec.
6982  *
6983  * Since the *61 series (and probably also the later *60 series), Lenovo
6984  * ThinkPads only implement the MUTE gate.
6985  *
6986  * EC register 0x30
6987  *   Bit 6: MUTE (1 mutes sound)
6988  *   Bit 3-0: Volume
6989  *   Other bits should be zero as far as we know.
6990  *
6991  * This is also stored in CMOS NVRAM, byte 0x60, bit 6 (MUTE), and
6992  * bits 3-0 (volume).  Other bits in NVRAM may have other functions,
6993  * such as bit 7 which is used to detect repeated presses of MUTE,
6994  * and we leave them unchanged.
6995  *
6996  * On newer Lenovo ThinkPads, the EC can automatically change the volume
6997  * in response to user input.  Unfortunately, this rarely works well.
6998  * The laptop changes the state of its internal MUTE gate and, on some
6999  * models, sends KEY_MUTE, causing any user code that responds to the
7000  * mute button to get confused.  The hardware MUTE gate is also
7001  * unnecessary, since user code can handle the mute button without
7002  * kernel or EC help.
7003  *
7004  * To avoid confusing userspace, we simply disable all EC-based mute
7005  * and volume controls when possible.
7006  */
7007
7008 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
7009
7010 #define TPACPI_ALSA_DRVNAME  "ThinkPad EC"
7011 #define TPACPI_ALSA_SHRTNAME "ThinkPad Console Audio Control"
7012 #define TPACPI_ALSA_MIXERNAME TPACPI_ALSA_SHRTNAME
7013
7014 #if SNDRV_CARDS <= 32
7015 #define DEFAULT_ALSA_IDX                ~((1 << (SNDRV_CARDS - 3)) - 1)
7016 #else
7017 #define DEFAULT_ALSA_IDX                ~((1 << (32 - 3)) - 1)
7018 #endif
7019 static int alsa_index = DEFAULT_ALSA_IDX; /* last three slots */
7020 static char *alsa_id = "ThinkPadEC";
7021 static bool alsa_enable = SNDRV_DEFAULT_ENABLE1;
7022
7023 struct tpacpi_alsa_data {
7024         struct snd_card *card;
7025         struct snd_ctl_elem_id *ctl_mute_id;
7026         struct snd_ctl_elem_id *ctl_vol_id;
7027 };
7028
7029 static struct snd_card *alsa_card;
7030
7031 enum {
7032         TP_EC_AUDIO = 0x30,
7033
7034         /* TP_EC_AUDIO bits */
7035         TP_EC_AUDIO_MUTESW = 6,
7036
7037         /* TP_EC_AUDIO bitmasks */
7038         TP_EC_AUDIO_LVL_MSK = 0x0F,
7039         TP_EC_AUDIO_MUTESW_MSK = (1 << TP_EC_AUDIO_MUTESW),
7040
7041         /* Maximum volume */
7042         TP_EC_VOLUME_MAX = 14,
7043 };
7044
7045 enum tpacpi_volume_access_mode {
7046         TPACPI_VOL_MODE_AUTO = 0,       /* Not implemented yet */
7047         TPACPI_VOL_MODE_EC,             /* Pure EC control */
7048         TPACPI_VOL_MODE_UCMS_STEP,      /* UCMS step-based control: N/A */
7049         TPACPI_VOL_MODE_ECNVRAM,        /* EC control w/ NVRAM store */
7050         TPACPI_VOL_MODE_MAX
7051 };
7052
7053 enum tpacpi_volume_capabilities {
7054         TPACPI_VOL_CAP_AUTO = 0,        /* Use white/blacklist */
7055         TPACPI_VOL_CAP_VOLMUTE,         /* Output vol and mute */
7056         TPACPI_VOL_CAP_MUTEONLY,        /* Output mute only */
7057         TPACPI_VOL_CAP_MAX
7058 };
7059
7060 enum tpacpi_mute_btn_mode {
7061         TP_EC_MUTE_BTN_LATCH  = 0,      /* Mute mutes; up/down unmutes */
7062         /* We don't know what mode 1 is. */
7063         TP_EC_MUTE_BTN_NONE   = 2,      /* Mute and up/down are just keys */
7064         TP_EC_MUTE_BTN_TOGGLE = 3,      /* Mute toggles; up/down unmutes */
7065 };
7066
7067 static enum tpacpi_volume_access_mode volume_mode =
7068         TPACPI_VOL_MODE_MAX;
7069
7070 static enum tpacpi_volume_capabilities volume_capabilities;
7071 static bool volume_control_allowed;
7072 static bool software_mute_requested = true;
7073 static bool software_mute_active;
7074 static int software_mute_orig_mode;
7075
7076 /*
7077  * Used to syncronize writers to TP_EC_AUDIO and
7078  * TP_NVRAM_ADDR_MIXER, as we need to do read-modify-write
7079  */
7080 static struct mutex volume_mutex;
7081
7082 static void tpacpi_volume_checkpoint_nvram(void)
7083 {
7084         u8 lec = 0;
7085         u8 b_nvram;
7086         u8 ec_mask;
7087
7088         if (volume_mode != TPACPI_VOL_MODE_ECNVRAM)
7089                 return;
7090         if (!volume_control_allowed)
7091                 return;
7092         if (software_mute_active)
7093                 return;
7094
7095         vdbg_printk(TPACPI_DBG_MIXER,
7096                 "trying to checkpoint mixer state to NVRAM...\n");
7097
7098         if (tp_features.mixer_no_level_control)
7099                 ec_mask = TP_EC_AUDIO_MUTESW_MSK;
7100         else
7101                 ec_mask = TP_EC_AUDIO_MUTESW_MSK | TP_EC_AUDIO_LVL_MSK;
7102
7103         if (mutex_lock_killable(&volume_mutex) < 0)
7104                 return;
7105
7106         if (unlikely(!acpi_ec_read(TP_EC_AUDIO, &lec)))
7107                 goto unlock;
7108         lec &= ec_mask;
7109         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
7110
7111         if (lec != (b_nvram & ec_mask)) {
7112                 /* NVRAM needs update */
7113                 b_nvram &= ~ec_mask;
7114                 b_nvram |= lec;
7115                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_MIXER);
7116                 dbg_printk(TPACPI_DBG_MIXER,
7117                            "updated NVRAM mixer status to 0x%02x (0x%02x)\n",
7118                            (unsigned int) lec, (unsigned int) b_nvram);
7119         } else {
7120                 vdbg_printk(TPACPI_DBG_MIXER,
7121                            "NVRAM mixer status already is 0x%02x (0x%02x)\n",
7122                            (unsigned int) lec, (unsigned int) b_nvram);
7123         }
7124
7125 unlock:
7126         mutex_unlock(&volume_mutex);
7127 }
7128
7129 static int volume_get_status_ec(u8 *status)
7130 {
7131         u8 s;
7132
7133         if (!acpi_ec_read(TP_EC_AUDIO, &s))
7134                 return -EIO;
7135
7136         *status = s;
7137
7138         dbg_printk(TPACPI_DBG_MIXER, "status 0x%02x\n", s);
7139
7140         return 0;
7141 }
7142
7143 static int volume_get_status(u8 *status)
7144 {
7145         return volume_get_status_ec(status);
7146 }
7147
7148 static int volume_set_status_ec(const u8 status)
7149 {
7150         if (!acpi_ec_write(TP_EC_AUDIO, status))
7151                 return -EIO;
7152
7153         dbg_printk(TPACPI_DBG_MIXER, "set EC mixer to 0x%02x\n", status);
7154
7155         /*
7156          * On X200s, and possibly on others, it can take a while for
7157          * reads to become correct.
7158          */
7159         msleep(1);
7160
7161         return 0;
7162 }
7163
7164 static int volume_set_status(const u8 status)
7165 {
7166         return volume_set_status_ec(status);
7167 }
7168
7169 /* returns < 0 on error, 0 on no change, 1 on change */
7170 static int __volume_set_mute_ec(const bool mute)
7171 {
7172         int rc;
7173         u8 s, n;
7174
7175         if (mutex_lock_killable(&volume_mutex) < 0)
7176                 return -EINTR;
7177
7178         rc = volume_get_status_ec(&s);
7179         if (rc)
7180                 goto unlock;
7181
7182         n = (mute) ? s | TP_EC_AUDIO_MUTESW_MSK :
7183                      s & ~TP_EC_AUDIO_MUTESW_MSK;
7184
7185         if (n != s) {
7186                 rc = volume_set_status_ec(n);
7187                 if (!rc)
7188                         rc = 1;
7189         }
7190
7191 unlock:
7192         mutex_unlock(&volume_mutex);
7193         return rc;
7194 }
7195
7196 static int volume_alsa_set_mute(const bool mute)
7197 {
7198         dbg_printk(TPACPI_DBG_MIXER, "ALSA: trying to %smute\n",
7199                    (mute) ? "" : "un");
7200         return __volume_set_mute_ec(mute);
7201 }
7202
7203 static int volume_set_mute(const bool mute)
7204 {
7205         int rc;
7206
7207         dbg_printk(TPACPI_DBG_MIXER, "trying to %smute\n",
7208                    (mute) ? "" : "un");
7209
7210         rc = __volume_set_mute_ec(mute);
7211         return (rc < 0) ? rc : 0;
7212 }
7213
7214 /* returns < 0 on error, 0 on no change, 1 on change */
7215 static int __volume_set_volume_ec(const u8 vol)
7216 {
7217         int rc;
7218         u8 s, n;
7219
7220         if (vol > TP_EC_VOLUME_MAX)
7221                 return -EINVAL;
7222
7223         if (mutex_lock_killable(&volume_mutex) < 0)
7224                 return -EINTR;
7225
7226         rc = volume_get_status_ec(&s);
7227         if (rc)
7228                 goto unlock;
7229
7230         n = (s & ~TP_EC_AUDIO_LVL_MSK) | vol;
7231
7232         if (n != s) {
7233                 rc = volume_set_status_ec(n);
7234                 if (!rc)
7235                         rc = 1;
7236         }
7237
7238 unlock:
7239         mutex_unlock(&volume_mutex);
7240         return rc;
7241 }
7242
7243 static int volume_set_software_mute(bool startup)
7244 {
7245         int result;
7246
7247         if (!tpacpi_is_lenovo())
7248                 return -ENODEV;
7249
7250         if (startup) {
7251                 if (!acpi_evalf(ec_handle, &software_mute_orig_mode,
7252                                 "HAUM", "qd"))
7253                         return -EIO;
7254
7255                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7256                             "Initial HAUM setting was %d\n",
7257                             software_mute_orig_mode);
7258         }
7259
7260         if (!acpi_evalf(ec_handle, &result, "SAUM", "qdd",
7261                         (int)TP_EC_MUTE_BTN_NONE))
7262                 return -EIO;
7263
7264         if (result != TP_EC_MUTE_BTN_NONE)
7265                 pr_warn("Unexpected SAUM result %d\n",
7266                         result);
7267
7268         /*
7269          * In software mute mode, the standard codec controls take
7270          * precendence, so we unmute the ThinkPad HW switch at
7271          * startup.  Just on case there are SAUM-capable ThinkPads
7272          * with level controls, set max HW volume as well.
7273          */
7274         if (tp_features.mixer_no_level_control)
7275                 result = volume_set_mute(false);
7276         else
7277                 result = volume_set_status(TP_EC_VOLUME_MAX);
7278
7279         if (result != 0)
7280                 pr_warn("Failed to unmute the HW mute switch\n");
7281
7282         return 0;
7283 }
7284
7285 static void volume_exit_software_mute(void)
7286 {
7287         int r;
7288
7289         if (!acpi_evalf(ec_handle, &r, "SAUM", "qdd", software_mute_orig_mode)
7290             || r != software_mute_orig_mode)
7291                 pr_warn("Failed to restore mute mode\n");
7292 }
7293
7294 static int volume_alsa_set_volume(const u8 vol)
7295 {
7296         dbg_printk(TPACPI_DBG_MIXER,
7297                    "ALSA: trying to set volume level to %hu\n", vol);
7298         return __volume_set_volume_ec(vol);
7299 }
7300
7301 static void volume_alsa_notify_change(void)
7302 {
7303         struct tpacpi_alsa_data *d;
7304
7305         if (alsa_card && alsa_card->private_data) {
7306                 d = alsa_card->private_data;
7307                 if (d->ctl_mute_id)
7308                         snd_ctl_notify(alsa_card,
7309                                         SNDRV_CTL_EVENT_MASK_VALUE,
7310                                         d->ctl_mute_id);
7311                 if (d->ctl_vol_id)
7312                         snd_ctl_notify(alsa_card,
7313                                         SNDRV_CTL_EVENT_MASK_VALUE,
7314                                         d->ctl_vol_id);
7315         }
7316 }
7317
7318 static int volume_alsa_vol_info(struct snd_kcontrol *kcontrol,
7319                                 struct snd_ctl_elem_info *uinfo)
7320 {
7321         uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
7322         uinfo->count = 1;
7323         uinfo->value.integer.min = 0;
7324         uinfo->value.integer.max = TP_EC_VOLUME_MAX;
7325         return 0;
7326 }
7327
7328 static int volume_alsa_vol_get(struct snd_kcontrol *kcontrol,
7329                                 struct snd_ctl_elem_value *ucontrol)
7330 {
7331         u8 s;
7332         int rc;
7333
7334         rc = volume_get_status(&s);
7335         if (rc < 0)
7336                 return rc;
7337
7338         ucontrol->value.integer.value[0] = s & TP_EC_AUDIO_LVL_MSK;
7339         return 0;
7340 }
7341
7342 static int volume_alsa_vol_put(struct snd_kcontrol *kcontrol,
7343                                 struct snd_ctl_elem_value *ucontrol)
7344 {
7345         tpacpi_disclose_usertask("ALSA", "set volume to %ld\n",
7346                                  ucontrol->value.integer.value[0]);
7347         return volume_alsa_set_volume(ucontrol->value.integer.value[0]);
7348 }
7349
7350 #define volume_alsa_mute_info snd_ctl_boolean_mono_info
7351
7352 static int volume_alsa_mute_get(struct snd_kcontrol *kcontrol,
7353                                 struct snd_ctl_elem_value *ucontrol)
7354 {
7355         u8 s;
7356         int rc;
7357
7358         rc = volume_get_status(&s);
7359         if (rc < 0)
7360                 return rc;
7361
7362         ucontrol->value.integer.value[0] =
7363                                 (s & TP_EC_AUDIO_MUTESW_MSK) ? 0 : 1;
7364         return 0;
7365 }
7366
7367 static int volume_alsa_mute_put(struct snd_kcontrol *kcontrol,
7368                                 struct snd_ctl_elem_value *ucontrol)
7369 {
7370         tpacpi_disclose_usertask("ALSA", "%smute\n",
7371                                  ucontrol->value.integer.value[0] ?
7372                                         "un" : "");
7373         return volume_alsa_set_mute(!ucontrol->value.integer.value[0]);
7374 }
7375
7376 static struct snd_kcontrol_new volume_alsa_control_vol __initdata = {
7377         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
7378         .name = "Console Playback Volume",
7379         .index = 0,
7380         .access = SNDRV_CTL_ELEM_ACCESS_READ,
7381         .info = volume_alsa_vol_info,
7382         .get = volume_alsa_vol_get,
7383 };
7384
7385 static struct snd_kcontrol_new volume_alsa_control_mute __initdata = {
7386         .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
7387         .name = "Console Playback Switch",
7388         .index = 0,
7389         .access = SNDRV_CTL_ELEM_ACCESS_READ,
7390         .info = volume_alsa_mute_info,
7391         .get = volume_alsa_mute_get,
7392 };
7393
7394 static void volume_suspend(void)
7395 {
7396         tpacpi_volume_checkpoint_nvram();
7397 }
7398
7399 static void volume_resume(void)
7400 {
7401         if (software_mute_active) {
7402                 if (volume_set_software_mute(false) < 0)
7403                         pr_warn("Failed to restore software mute\n");
7404         } else {
7405                 volume_alsa_notify_change();
7406         }
7407 }
7408
7409 static void volume_shutdown(void)
7410 {
7411         tpacpi_volume_checkpoint_nvram();
7412 }
7413
7414 static void volume_exit(void)
7415 {
7416         if (alsa_card) {
7417                 snd_card_free(alsa_card);
7418                 alsa_card = NULL;
7419         }
7420
7421         tpacpi_volume_checkpoint_nvram();
7422
7423         if (software_mute_active)
7424                 volume_exit_software_mute();
7425 }
7426
7427 static int __init volume_create_alsa_mixer(void)
7428 {
7429         struct snd_card *card;
7430         struct tpacpi_alsa_data *data;
7431         struct snd_kcontrol *ctl_vol;
7432         struct snd_kcontrol *ctl_mute;
7433         int rc;
7434
7435         rc = snd_card_new(&tpacpi_pdev->dev,
7436                           alsa_index, alsa_id, THIS_MODULE,
7437                           sizeof(struct tpacpi_alsa_data), &card);
7438         if (rc < 0 || !card) {
7439                 pr_err("Failed to create ALSA card structures: %d\n", rc);
7440                 return 1;
7441         }
7442
7443         BUG_ON(!card->private_data);
7444         data = card->private_data;
7445         data->card = card;
7446
7447         strlcpy(card->driver, TPACPI_ALSA_DRVNAME,
7448                 sizeof(card->driver));
7449         strlcpy(card->shortname, TPACPI_ALSA_SHRTNAME,
7450                 sizeof(card->shortname));
7451         snprintf(card->mixername, sizeof(card->mixername), "ThinkPad EC %s",
7452                  (thinkpad_id.ec_version_str) ?
7453                         thinkpad_id.ec_version_str : "(unknown)");
7454         snprintf(card->longname, sizeof(card->longname),
7455                  "%s at EC reg 0x%02x, fw %s", card->shortname, TP_EC_AUDIO,
7456                  (thinkpad_id.ec_version_str) ?
7457                         thinkpad_id.ec_version_str : "unknown");
7458
7459         if (volume_control_allowed) {
7460                 volume_alsa_control_vol.put = volume_alsa_vol_put;
7461                 volume_alsa_control_vol.access =
7462                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
7463
7464                 volume_alsa_control_mute.put = volume_alsa_mute_put;
7465                 volume_alsa_control_mute.access =
7466                                 SNDRV_CTL_ELEM_ACCESS_READWRITE;
7467         }
7468
7469         if (!tp_features.mixer_no_level_control) {
7470                 ctl_vol = snd_ctl_new1(&volume_alsa_control_vol, NULL);
7471                 rc = snd_ctl_add(card, ctl_vol);
7472                 if (rc < 0) {
7473                         pr_err("Failed to create ALSA volume control: %d\n",
7474                                rc);
7475                         goto err_exit;
7476                 }
7477                 data->ctl_vol_id = &ctl_vol->id;
7478         }
7479
7480         ctl_mute = snd_ctl_new1(&volume_alsa_control_mute, NULL);
7481         rc = snd_ctl_add(card, ctl_mute);
7482         if (rc < 0) {
7483                 pr_err("Failed to create ALSA mute control: %d\n", rc);
7484                 goto err_exit;
7485         }
7486         data->ctl_mute_id = &ctl_mute->id;
7487
7488         rc = snd_card_register(card);
7489         if (rc < 0) {
7490                 pr_err("Failed to register ALSA card: %d\n", rc);
7491                 goto err_exit;
7492         }
7493
7494         alsa_card = card;
7495         return 0;
7496
7497 err_exit:
7498         snd_card_free(card);
7499         return 1;
7500 }
7501
7502 #define TPACPI_VOL_Q_MUTEONLY   0x0001  /* Mute-only control available */
7503 #define TPACPI_VOL_Q_LEVEL      0x0002  /* Volume control available */
7504
7505 static const struct tpacpi_quirk volume_quirk_table[] __initconst = {
7506         /* Whitelist volume level on all IBM by default */
7507         { .vendor = PCI_VENDOR_ID_IBM,
7508           .bios   = TPACPI_MATCH_ANY,
7509           .ec     = TPACPI_MATCH_ANY,
7510           .quirks = TPACPI_VOL_Q_LEVEL },
7511
7512         /* Lenovo models with volume control (needs confirmation) */
7513         TPACPI_QEC_LNV('7', 'C', TPACPI_VOL_Q_LEVEL), /* R60/i */
7514         TPACPI_QEC_LNV('7', 'E', TPACPI_VOL_Q_LEVEL), /* R60e/i */
7515         TPACPI_QEC_LNV('7', '9', TPACPI_VOL_Q_LEVEL), /* T60/p */
7516         TPACPI_QEC_LNV('7', 'B', TPACPI_VOL_Q_LEVEL), /* X60/s */
7517         TPACPI_QEC_LNV('7', 'J', TPACPI_VOL_Q_LEVEL), /* X60t */
7518         TPACPI_QEC_LNV('7', '7', TPACPI_VOL_Q_LEVEL), /* Z60 */
7519         TPACPI_QEC_LNV('7', 'F', TPACPI_VOL_Q_LEVEL), /* Z61 */
7520
7521         /* Whitelist mute-only on all Lenovo by default */
7522         { .vendor = PCI_VENDOR_ID_LENOVO,
7523           .bios   = TPACPI_MATCH_ANY,
7524           .ec     = TPACPI_MATCH_ANY,
7525           .quirks = TPACPI_VOL_Q_MUTEONLY }
7526 };
7527
7528 static int __init volume_init(struct ibm_init_struct *iibm)
7529 {
7530         unsigned long quirks;
7531         int rc;
7532
7533         vdbg_printk(TPACPI_DBG_INIT, "initializing volume subdriver\n");
7534
7535         mutex_init(&volume_mutex);
7536
7537         /*
7538          * Check for module parameter bogosity, note that we
7539          * init volume_mode to TPACPI_VOL_MODE_MAX in order to be
7540          * able to detect "unspecified"
7541          */
7542         if (volume_mode > TPACPI_VOL_MODE_MAX)
7543                 return -EINVAL;
7544
7545         if (volume_mode == TPACPI_VOL_MODE_UCMS_STEP) {
7546                 pr_err("UCMS step volume mode not implemented, please contact %s\n",
7547                        TPACPI_MAIL);
7548                 return 1;
7549         }
7550
7551         if (volume_capabilities >= TPACPI_VOL_CAP_MAX)
7552                 return -EINVAL;
7553
7554         /*
7555          * The ALSA mixer is our primary interface.
7556          * When disabled, don't install the subdriver at all
7557          */
7558         if (!alsa_enable) {
7559                 vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7560                             "ALSA mixer disabled by parameter, not loading volume subdriver...\n");
7561                 return 1;
7562         }
7563
7564         quirks = tpacpi_check_quirks(volume_quirk_table,
7565                                      ARRAY_SIZE(volume_quirk_table));
7566
7567         switch (volume_capabilities) {
7568         case TPACPI_VOL_CAP_AUTO:
7569                 if (quirks & TPACPI_VOL_Q_MUTEONLY)
7570                         tp_features.mixer_no_level_control = 1;
7571                 else if (quirks & TPACPI_VOL_Q_LEVEL)
7572                         tp_features.mixer_no_level_control = 0;
7573                 else
7574                         return 1; /* no mixer */
7575                 break;
7576         case TPACPI_VOL_CAP_VOLMUTE:
7577                 tp_features.mixer_no_level_control = 0;
7578                 break;
7579         case TPACPI_VOL_CAP_MUTEONLY:
7580                 tp_features.mixer_no_level_control = 1;
7581                 break;
7582         default:
7583                 return 1;
7584         }
7585
7586         if (volume_capabilities != TPACPI_VOL_CAP_AUTO)
7587                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7588                                 "using user-supplied volume_capabilities=%d\n",
7589                                 volume_capabilities);
7590
7591         if (volume_mode == TPACPI_VOL_MODE_AUTO ||
7592             volume_mode == TPACPI_VOL_MODE_MAX) {
7593                 volume_mode = TPACPI_VOL_MODE_ECNVRAM;
7594
7595                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7596                                 "driver auto-selected volume_mode=%d\n",
7597                                 volume_mode);
7598         } else {
7599                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7600                                 "using user-supplied volume_mode=%d\n",
7601                                 volume_mode);
7602         }
7603
7604         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7605                         "mute is supported, volume control is %s\n",
7606                         str_supported(!tp_features.mixer_no_level_control));
7607
7608         if (software_mute_requested && volume_set_software_mute(true) == 0) {
7609                 software_mute_active = true;
7610         } else {
7611                 rc = volume_create_alsa_mixer();
7612                 if (rc) {
7613                         pr_err("Could not create the ALSA mixer interface\n");
7614                         return rc;
7615                 }
7616
7617                 pr_info("Console audio control enabled, mode: %s\n",
7618                         (volume_control_allowed) ?
7619                                 "override (read/write)" :
7620                                 "monitor (read only)");
7621         }
7622
7623         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_MIXER,
7624                 "registering volume hotkeys as change notification\n");
7625         tpacpi_hotkey_driver_mask_set(hotkey_driver_mask
7626                         | TP_ACPI_HKEY_VOLUP_MASK
7627                         | TP_ACPI_HKEY_VOLDWN_MASK
7628                         | TP_ACPI_HKEY_MUTE_MASK);
7629
7630         return 0;
7631 }
7632
7633 static int volume_read(struct seq_file *m)
7634 {
7635         u8 status;
7636
7637         if (volume_get_status(&status) < 0) {
7638                 seq_printf(m, "level:\t\tunreadable\n");
7639         } else {
7640                 if (tp_features.mixer_no_level_control)
7641                         seq_printf(m, "level:\t\tunsupported\n");
7642                 else
7643                         seq_printf(m, "level:\t\t%d\n",
7644                                         status & TP_EC_AUDIO_LVL_MSK);
7645
7646                 seq_printf(m, "mute:\t\t%s\n",
7647                                 onoff(status, TP_EC_AUDIO_MUTESW));
7648
7649                 if (volume_control_allowed) {
7650                         seq_printf(m, "commands:\tunmute, mute\n");
7651                         if (!tp_features.mixer_no_level_control) {
7652                                 seq_printf(m, "commands:\tup, down\n");
7653                                 seq_printf(m, "commands:\tlevel <level> (<level> is 0-%d)\n",
7654                                               TP_EC_VOLUME_MAX);
7655                         }
7656                 }
7657         }
7658
7659         return 0;
7660 }
7661
7662 static int volume_write(char *buf)
7663 {
7664         u8 s;
7665         u8 new_level, new_mute;
7666         int l;
7667         char *cmd;
7668         int rc;
7669
7670         /*
7671          * We do allow volume control at driver startup, so that the
7672          * user can set initial state through the volume=... parameter hack.
7673          */
7674         if (!volume_control_allowed && tpacpi_lifecycle != TPACPI_LIFE_INIT) {
7675                 if (unlikely(!tp_warned.volume_ctrl_forbidden)) {
7676                         tp_warned.volume_ctrl_forbidden = 1;
7677                         pr_notice("Console audio control in monitor mode, changes are not allowed\n");
7678                         pr_notice("Use the volume_control=1 module parameter to enable volume control\n");
7679                 }
7680                 return -EPERM;
7681         }
7682
7683         rc = volume_get_status(&s);
7684         if (rc < 0)
7685                 return rc;
7686
7687         new_level = s & TP_EC_AUDIO_LVL_MSK;
7688         new_mute  = s & TP_EC_AUDIO_MUTESW_MSK;
7689
7690         while ((cmd = next_cmd(&buf))) {
7691                 if (!tp_features.mixer_no_level_control) {
7692                         if (strlencmp(cmd, "up") == 0) {
7693                                 if (new_mute)
7694                                         new_mute = 0;
7695                                 else if (new_level < TP_EC_VOLUME_MAX)
7696                                         new_level++;
7697                                 continue;
7698                         } else if (strlencmp(cmd, "down") == 0) {
7699                                 if (new_mute)
7700                                         new_mute = 0;
7701                                 else if (new_level > 0)
7702                                         new_level--;
7703                                 continue;
7704                         } else if (sscanf(cmd, "level %u", &l) == 1 &&
7705                                    l >= 0 && l <= TP_EC_VOLUME_MAX) {
7706                                         new_level = l;
7707                                 continue;
7708                         }
7709                 }
7710                 if (strlencmp(cmd, "mute") == 0)
7711                         new_mute = TP_EC_AUDIO_MUTESW_MSK;
7712                 else if (strlencmp(cmd, "unmute") == 0)
7713                         new_mute = 0;
7714                 else
7715                         return -EINVAL;
7716         }
7717
7718         if (tp_features.mixer_no_level_control) {
7719                 tpacpi_disclose_usertask("procfs volume", "%smute\n",
7720                                         new_mute ? "" : "un");
7721                 rc = volume_set_mute(!!new_mute);
7722         } else {
7723                 tpacpi_disclose_usertask("procfs volume",
7724                                         "%smute and set level to %d\n",
7725                                         new_mute ? "" : "un", new_level);
7726                 rc = volume_set_status(new_mute | new_level);
7727         }
7728         volume_alsa_notify_change();
7729
7730         return (rc == -EINTR) ? -ERESTARTSYS : rc;
7731 }
7732
7733 static struct ibm_struct volume_driver_data = {
7734         .name = "volume",
7735         .read = volume_read,
7736         .write = volume_write,
7737         .exit = volume_exit,
7738         .suspend = volume_suspend,
7739         .resume = volume_resume,
7740         .shutdown = volume_shutdown,
7741 };
7742
7743 #else /* !CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7744
7745 #define alsa_card NULL
7746
7747 static inline void volume_alsa_notify_change(void)
7748 {
7749 }
7750
7751 static int __init volume_init(struct ibm_init_struct *iibm)
7752 {
7753         pr_info("volume: disabled as there is no ALSA support in this kernel\n");
7754
7755         return 1;
7756 }
7757
7758 static struct ibm_struct volume_driver_data = {
7759         .name = "volume",
7760 };
7761
7762 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
7763
7764 /*************************************************************************
7765  * Fan subdriver
7766  */
7767
7768 /*
7769  * FAN ACCESS MODES
7770  *
7771  * TPACPI_FAN_RD_ACPI_GFAN:
7772  *      ACPI GFAN method: returns fan level
7773  *
7774  *      see TPACPI_FAN_WR_ACPI_SFAN
7775  *      EC 0x2f (HFSP) not available if GFAN exists
7776  *
7777  * TPACPI_FAN_WR_ACPI_SFAN:
7778  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
7779  *
7780  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
7781  *      it for writing.
7782  *
7783  * TPACPI_FAN_WR_TPEC:
7784  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
7785  *      Supported on almost all ThinkPads
7786  *
7787  *      Fan speed changes of any sort (including those caused by the
7788  *      disengaged mode) are usually done slowly by the firmware as the
7789  *      maximum amount of fan duty cycle change per second seems to be
7790  *      limited.
7791  *
7792  *      Reading is not available if GFAN exists.
7793  *      Writing is not available if SFAN exists.
7794  *
7795  *      Bits
7796  *       7      automatic mode engaged;
7797  *              (default operation mode of the ThinkPad)
7798  *              fan level is ignored in this mode.
7799  *       6      full speed mode (takes precedence over bit 7);
7800  *              not available on all thinkpads.  May disable
7801  *              the tachometer while the fan controller ramps up
7802  *              the speed (which can take up to a few *minutes*).
7803  *              Speeds up fan to 100% duty-cycle, which is far above
7804  *              the standard RPM levels.  It is not impossible that
7805  *              it could cause hardware damage.
7806  *      5-3     unused in some models.  Extra bits for fan level
7807  *              in others, but still useless as all values above
7808  *              7 map to the same speed as level 7 in these models.
7809  *      2-0     fan level (0..7 usually)
7810  *                      0x00 = stop
7811  *                      0x07 = max (set when temperatures critical)
7812  *              Some ThinkPads may have other levels, see
7813  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
7814  *
7815  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
7816  *      boot. Apparently the EC does not initialize it, so unless ACPI DSDT
7817  *      does so, its initial value is meaningless (0x07).
7818  *
7819  *      For firmware bugs, refer to:
7820  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7821  *
7822  *      ----
7823  *
7824  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
7825  *      Main fan tachometer reading (in RPM)
7826  *
7827  *      This register is present on all ThinkPads with a new-style EC, and
7828  *      it is known not to be present on the A21m/e, and T22, as there is
7829  *      something else in offset 0x84 according to the ACPI DSDT.  Other
7830  *      ThinkPads from this same time period (and earlier) probably lack the
7831  *      tachometer as well.
7832  *
7833  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
7834  *      was never fixed by IBM to report the EC firmware version string
7835  *      probably support the tachometer (like the early X models), so
7836  *      detecting it is quite hard.  We need more data to know for sure.
7837  *
7838  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
7839  *      might result.
7840  *
7841  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
7842  *      mode.
7843  *
7844  *      For firmware bugs, refer to:
7845  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
7846  *
7847  *      ----
7848  *
7849  *      ThinkPad EC register 0x31 bit 0 (only on select models)
7850  *
7851  *      When bit 0 of EC register 0x31 is zero, the tachometer registers
7852  *      show the speed of the main fan.  When bit 0 of EC register 0x31
7853  *      is one, the tachometer registers show the speed of the auxiliary
7854  *      fan.
7855  *
7856  *      Fan control seems to affect both fans, regardless of the state
7857  *      of this bit.
7858  *
7859  *      So far, only the firmware for the X60/X61 non-tablet versions
7860  *      seem to support this (firmware TP-7M).
7861  *
7862  * TPACPI_FAN_WR_ACPI_FANS:
7863  *      ThinkPad X31, X40, X41.  Not available in the X60.
7864  *
7865  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
7866  *      high speed.  ACPI DSDT seems to map these three speeds to levels
7867  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
7868  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
7869  *
7870  *      The speeds are stored on handles
7871  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
7872  *
7873  *      There are three default speed sets, accessible as handles:
7874  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
7875  *
7876  *      ACPI DSDT switches which set is in use depending on various
7877  *      factors.
7878  *
7879  *      TPACPI_FAN_WR_TPEC is also available and should be used to
7880  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
7881  *      but the ACPI tables just mention level 7.
7882  */
7883
7884 enum {                                  /* Fan control constants */
7885         fan_status_offset = 0x2f,       /* EC register 0x2f */
7886         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
7887                                          * 0x84 must be read before 0x85 */
7888         fan_select_offset = 0x31,       /* EC register 0x31 (Firmware 7M)
7889                                            bit 0 selects which fan is active */
7890
7891         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
7892         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
7893
7894         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
7895 };
7896
7897 enum fan_status_access_mode {
7898         TPACPI_FAN_NONE = 0,            /* No fan status or control */
7899         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
7900         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
7901 };
7902
7903 enum fan_control_access_mode {
7904         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
7905         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
7906         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
7907         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
7908 };
7909
7910 enum fan_control_commands {
7911         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
7912         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
7913         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
7914                                                  * and also watchdog cmd */
7915 };
7916
7917 static bool fan_control_allowed;
7918
7919 static enum fan_status_access_mode fan_status_access_mode;
7920 static enum fan_control_access_mode fan_control_access_mode;
7921 static enum fan_control_commands fan_control_commands;
7922
7923 static u8 fan_control_initial_status;
7924 static u8 fan_control_desired_level;
7925 static u8 fan_control_resume_level;
7926 static int fan_watchdog_maxinterval;
7927
7928 static struct mutex fan_mutex;
7929
7930 static void fan_watchdog_fire(struct work_struct *ignored);
7931 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
7932
7933 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
7934 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
7935            "\\FSPD",            /* 600e/x, 770e, 770x */
7936            );                   /* all others */
7937 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
7938            "JFNS",              /* 770x-JL */
7939            );                   /* all others */
7940
7941 /*
7942  * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the
7943  * HFSP register at boot, so it contains 0x07 but the Thinkpad could
7944  * be in auto mode (0x80).
7945  *
7946  * This is corrected by any write to HFSP either by the driver, or
7947  * by the firmware.
7948  *
7949  * We assume 0x07 really means auto mode while this quirk is active,
7950  * as this is far more likely than the ThinkPad being in level 7,
7951  * which is only used by the firmware during thermal emergencies.
7952  *
7953  * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52),
7954  * TP-70 (T43, R52), which are known to be buggy.
7955  */
7956
7957 static void fan_quirk1_setup(void)
7958 {
7959         if (fan_control_initial_status == 0x07) {
7960                 pr_notice("fan_init: initial fan status is unknown, assuming it is in auto mode\n");
7961                 tp_features.fan_ctrl_status_undef = 1;
7962         }
7963 }
7964
7965 static void fan_quirk1_handle(u8 *fan_status)
7966 {
7967         if (unlikely(tp_features.fan_ctrl_status_undef)) {
7968                 if (*fan_status != fan_control_initial_status) {
7969                         /* something changed the HFSP regisnter since
7970                          * driver init time, so it is not undefined
7971                          * anymore */
7972                         tp_features.fan_ctrl_status_undef = 0;
7973                 } else {
7974                         /* Return most likely status. In fact, it
7975                          * might be the only possible status */
7976                         *fan_status = TP_EC_FAN_AUTO;
7977                 }
7978         }
7979 }
7980
7981 /* Select main fan on X60/X61, NOOP on others */
7982 static bool fan_select_fan1(void)
7983 {
7984         if (tp_features.second_fan) {
7985                 u8 val;
7986
7987                 if (ec_read(fan_select_offset, &val) < 0)
7988                         return false;
7989                 val &= 0xFEU;
7990                 if (ec_write(fan_select_offset, val) < 0)
7991                         return false;
7992         }
7993         return true;
7994 }
7995
7996 /* Select secondary fan on X60/X61 */
7997 static bool fan_select_fan2(void)
7998 {
7999         u8 val;
8000
8001         if (!tp_features.second_fan)
8002                 return false;
8003
8004         if (ec_read(fan_select_offset, &val) < 0)
8005                 return false;
8006         val |= 0x01U;
8007         if (ec_write(fan_select_offset, val) < 0)
8008                 return false;
8009
8010         return true;
8011 }
8012
8013 /*
8014  * Call with fan_mutex held
8015  */
8016 static void fan_update_desired_level(u8 status)
8017 {
8018         if ((status &
8019              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
8020                 if (status > 7)
8021                         fan_control_desired_level = 7;
8022                 else
8023                         fan_control_desired_level = status;
8024         }
8025 }
8026
8027 static int fan_get_status(u8 *status)
8028 {
8029         u8 s;
8030
8031         /* TODO:
8032          * Add TPACPI_FAN_RD_ACPI_FANS ? */
8033
8034         switch (fan_status_access_mode) {
8035         case TPACPI_FAN_RD_ACPI_GFAN: {
8036                 /* 570, 600e/x, 770e, 770x */
8037                 int res;
8038
8039                 if (unlikely(!acpi_evalf(gfan_handle, &res, NULL, "d")))
8040                         return -EIO;
8041
8042                 if (likely(status))
8043                         *status = res & 0x07;
8044
8045                 break;
8046         }
8047         case TPACPI_FAN_RD_TPEC:
8048                 /* all except 570, 600e/x, 770e, 770x */
8049                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
8050                         return -EIO;
8051
8052                 if (likely(status)) {
8053                         *status = s;
8054                         fan_quirk1_handle(status);
8055                 }
8056
8057                 break;
8058
8059         default:
8060                 return -ENXIO;
8061         }
8062
8063         return 0;
8064 }
8065
8066 static int fan_get_status_safe(u8 *status)
8067 {
8068         int rc;
8069         u8 s;
8070
8071         if (mutex_lock_killable(&fan_mutex))
8072                 return -ERESTARTSYS;
8073         rc = fan_get_status(&s);
8074         if (!rc)
8075                 fan_update_desired_level(s);
8076         mutex_unlock(&fan_mutex);
8077
8078         if (rc)
8079                 return rc;
8080         if (status)
8081                 *status = s;
8082
8083         return 0;
8084 }
8085
8086 static int fan_get_speed(unsigned int *speed)
8087 {
8088         u8 hi, lo;
8089
8090         switch (fan_status_access_mode) {
8091         case TPACPI_FAN_RD_TPEC:
8092                 /* all except 570, 600e/x, 770e, 770x */
8093                 if (unlikely(!fan_select_fan1()))
8094                         return -EIO;
8095                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
8096                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
8097                         return -EIO;
8098
8099                 if (likely(speed))
8100                         *speed = (hi << 8) | lo;
8101
8102                 break;
8103
8104         default:
8105                 return -ENXIO;
8106         }
8107
8108         return 0;
8109 }
8110
8111 static int fan2_get_speed(unsigned int *speed)
8112 {
8113         u8 hi, lo;
8114         bool rc;
8115
8116         switch (fan_status_access_mode) {
8117         case TPACPI_FAN_RD_TPEC:
8118                 /* all except 570, 600e/x, 770e, 770x */
8119                 if (unlikely(!fan_select_fan2()))
8120                         return -EIO;
8121                 rc = !acpi_ec_read(fan_rpm_offset, &lo) ||
8122                              !acpi_ec_read(fan_rpm_offset + 1, &hi);
8123                 fan_select_fan1(); /* play it safe */
8124                 if (rc)
8125                         return -EIO;
8126
8127                 if (likely(speed))
8128                         *speed = (hi << 8) | lo;
8129
8130                 break;
8131
8132         default:
8133                 return -ENXIO;
8134         }
8135
8136         return 0;
8137 }
8138
8139 static int fan_set_level(int level)
8140 {
8141         if (!fan_control_allowed)
8142                 return -EPERM;
8143
8144         switch (fan_control_access_mode) {
8145         case TPACPI_FAN_WR_ACPI_SFAN:
8146                 if (level >= 0 && level <= 7) {
8147                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
8148                                 return -EIO;
8149                 } else
8150                         return -EINVAL;
8151                 break;
8152
8153         case TPACPI_FAN_WR_ACPI_FANS:
8154         case TPACPI_FAN_WR_TPEC:
8155                 if (!(level & TP_EC_FAN_AUTO) &&
8156                     !(level & TP_EC_FAN_FULLSPEED) &&
8157                     ((level < 0) || (level > 7)))
8158                         return -EINVAL;
8159
8160                 /* safety net should the EC not support AUTO
8161                  * or FULLSPEED mode bits and just ignore them */
8162                 if (level & TP_EC_FAN_FULLSPEED)
8163                         level |= 7;     /* safety min speed 7 */
8164                 else if (level & TP_EC_FAN_AUTO)
8165                         level |= 4;     /* safety min speed 4 */
8166
8167                 if (!acpi_ec_write(fan_status_offset, level))
8168                         return -EIO;
8169                 else
8170                         tp_features.fan_ctrl_status_undef = 0;
8171                 break;
8172
8173         default:
8174                 return -ENXIO;
8175         }
8176
8177         vdbg_printk(TPACPI_DBG_FAN,
8178                 "fan control: set fan control register to 0x%02x\n", level);
8179         return 0;
8180 }
8181
8182 static int fan_set_level_safe(int level)
8183 {
8184         int rc;
8185
8186         if (!fan_control_allowed)
8187                 return -EPERM;
8188
8189         if (mutex_lock_killable(&fan_mutex))
8190                 return -ERESTARTSYS;
8191
8192         if (level == TPACPI_FAN_LAST_LEVEL)
8193                 level = fan_control_desired_level;
8194
8195         rc = fan_set_level(level);
8196         if (!rc)
8197                 fan_update_desired_level(level);
8198
8199         mutex_unlock(&fan_mutex);
8200         return rc;
8201 }
8202
8203 static int fan_set_enable(void)
8204 {
8205         u8 s;
8206         int rc;
8207
8208         if (!fan_control_allowed)
8209                 return -EPERM;
8210
8211         if (mutex_lock_killable(&fan_mutex))
8212                 return -ERESTARTSYS;
8213
8214         switch (fan_control_access_mode) {
8215         case TPACPI_FAN_WR_ACPI_FANS:
8216         case TPACPI_FAN_WR_TPEC:
8217                 rc = fan_get_status(&s);
8218                 if (rc < 0)
8219                         break;
8220
8221                 /* Don't go out of emergency fan mode */
8222                 if (s != 7) {
8223                         s &= 0x07;
8224                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
8225                 }
8226
8227                 if (!acpi_ec_write(fan_status_offset, s))
8228                         rc = -EIO;
8229                 else {
8230                         tp_features.fan_ctrl_status_undef = 0;
8231                         rc = 0;
8232                 }
8233                 break;
8234
8235         case TPACPI_FAN_WR_ACPI_SFAN:
8236                 rc = fan_get_status(&s);
8237                 if (rc < 0)
8238                         break;
8239
8240                 s &= 0x07;
8241
8242                 /* Set fan to at least level 4 */
8243                 s |= 4;
8244
8245                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
8246                         rc = -EIO;
8247                 else
8248                         rc = 0;
8249                 break;
8250
8251         default:
8252                 rc = -ENXIO;
8253         }
8254
8255         mutex_unlock(&fan_mutex);
8256
8257         if (!rc)
8258                 vdbg_printk(TPACPI_DBG_FAN,
8259                         "fan control: set fan control register to 0x%02x\n",
8260                         s);
8261         return rc;
8262 }
8263
8264 static int fan_set_disable(void)
8265 {
8266         int rc;
8267
8268         if (!fan_control_allowed)
8269                 return -EPERM;
8270
8271         if (mutex_lock_killable(&fan_mutex))
8272                 return -ERESTARTSYS;
8273
8274         rc = 0;
8275         switch (fan_control_access_mode) {
8276         case TPACPI_FAN_WR_ACPI_FANS:
8277         case TPACPI_FAN_WR_TPEC:
8278                 if (!acpi_ec_write(fan_status_offset, 0x00))
8279                         rc = -EIO;
8280                 else {
8281                         fan_control_desired_level = 0;
8282                         tp_features.fan_ctrl_status_undef = 0;
8283                 }
8284                 break;
8285
8286         case TPACPI_FAN_WR_ACPI_SFAN:
8287                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
8288                         rc = -EIO;
8289                 else
8290                         fan_control_desired_level = 0;
8291                 break;
8292
8293         default:
8294                 rc = -ENXIO;
8295         }
8296
8297         if (!rc)
8298                 vdbg_printk(TPACPI_DBG_FAN,
8299                         "fan control: set fan control register to 0\n");
8300
8301         mutex_unlock(&fan_mutex);
8302         return rc;
8303 }
8304
8305 static int fan_set_speed(int speed)
8306 {
8307         int rc;
8308
8309         if (!fan_control_allowed)
8310                 return -EPERM;
8311
8312         if (mutex_lock_killable(&fan_mutex))
8313                 return -ERESTARTSYS;
8314
8315         rc = 0;
8316         switch (fan_control_access_mode) {
8317         case TPACPI_FAN_WR_ACPI_FANS:
8318                 if (speed >= 0 && speed <= 65535) {
8319                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
8320                                         speed, speed, speed))
8321                                 rc = -EIO;
8322                 } else
8323                         rc = -EINVAL;
8324                 break;
8325
8326         default:
8327                 rc = -ENXIO;
8328         }
8329
8330         mutex_unlock(&fan_mutex);
8331         return rc;
8332 }
8333
8334 static void fan_watchdog_reset(void)
8335 {
8336         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
8337                 return;
8338
8339         if (fan_watchdog_maxinterval > 0 &&
8340             tpacpi_lifecycle != TPACPI_LIFE_EXITING)
8341                 mod_delayed_work(tpacpi_wq, &fan_watchdog_task,
8342                         msecs_to_jiffies(fan_watchdog_maxinterval * 1000));
8343         else
8344                 cancel_delayed_work(&fan_watchdog_task);
8345 }
8346
8347 static void fan_watchdog_fire(struct work_struct *ignored)
8348 {
8349         int rc;
8350
8351         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
8352                 return;
8353
8354         pr_notice("fan watchdog: enabling fan\n");
8355         rc = fan_set_enable();
8356         if (rc < 0) {
8357                 pr_err("fan watchdog: error %d while enabling fan, will try again later...\n",
8358                        rc);
8359                 /* reschedule for later */
8360                 fan_watchdog_reset();
8361         }
8362 }
8363
8364 /*
8365  * SYSFS fan layout: hwmon compatible (device)
8366  *
8367  * pwm*_enable:
8368  *      0: "disengaged" mode
8369  *      1: manual mode
8370  *      2: native EC "auto" mode (recommended, hardware default)
8371  *
8372  * pwm*: set speed in manual mode, ignored otherwise.
8373  *      0 is level 0; 255 is level 7. Intermediate points done with linear
8374  *      interpolation.
8375  *
8376  * fan*_input: tachometer reading, RPM
8377  *
8378  *
8379  * SYSFS fan layout: extensions
8380  *
8381  * fan_watchdog (driver):
8382  *      fan watchdog interval in seconds, 0 disables (default), max 120
8383  */
8384
8385 /* sysfs fan pwm1_enable ----------------------------------------------- */
8386 static ssize_t fan_pwm1_enable_show(struct device *dev,
8387                                     struct device_attribute *attr,
8388                                     char *buf)
8389 {
8390         int res, mode;
8391         u8 status;
8392
8393         res = fan_get_status_safe(&status);
8394         if (res)
8395                 return res;
8396
8397         if (status & TP_EC_FAN_FULLSPEED) {
8398                 mode = 0;
8399         } else if (status & TP_EC_FAN_AUTO) {
8400                 mode = 2;
8401         } else
8402                 mode = 1;
8403
8404         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
8405 }
8406
8407 static ssize_t fan_pwm1_enable_store(struct device *dev,
8408                                      struct device_attribute *attr,
8409                                      const char *buf, size_t count)
8410 {
8411         unsigned long t;
8412         int res, level;
8413
8414         if (parse_strtoul(buf, 2, &t))
8415                 return -EINVAL;
8416
8417         tpacpi_disclose_usertask("hwmon pwm1_enable",
8418                         "set fan mode to %lu\n", t);
8419
8420         switch (t) {
8421         case 0:
8422                 level = TP_EC_FAN_FULLSPEED;
8423                 break;
8424         case 1:
8425                 level = TPACPI_FAN_LAST_LEVEL;
8426                 break;
8427         case 2:
8428                 level = TP_EC_FAN_AUTO;
8429                 break;
8430         case 3:
8431                 /* reserved for software-controlled auto mode */
8432                 return -ENOSYS;
8433         default:
8434                 return -EINVAL;
8435         }
8436
8437         res = fan_set_level_safe(level);
8438         if (res == -ENXIO)
8439                 return -EINVAL;
8440         else if (res < 0)
8441                 return res;
8442
8443         fan_watchdog_reset();
8444
8445         return count;
8446 }
8447
8448 static DEVICE_ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
8449                    fan_pwm1_enable_show, fan_pwm1_enable_store);
8450
8451 /* sysfs fan pwm1 ------------------------------------------------------ */
8452 static ssize_t fan_pwm1_show(struct device *dev,
8453                              struct device_attribute *attr,
8454                              char *buf)
8455 {
8456         int res;
8457         u8 status;
8458
8459         res = fan_get_status_safe(&status);
8460         if (res)
8461                 return res;
8462
8463         if ((status &
8464              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
8465                 status = fan_control_desired_level;
8466
8467         if (status > 7)
8468                 status = 7;
8469
8470         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
8471 }
8472
8473 static ssize_t fan_pwm1_store(struct device *dev,
8474                               struct device_attribute *attr,
8475                               const char *buf, size_t count)
8476 {
8477         unsigned long s;
8478         int rc;
8479         u8 status, newlevel;
8480
8481         if (parse_strtoul(buf, 255, &s))
8482                 return -EINVAL;
8483
8484         tpacpi_disclose_usertask("hwmon pwm1",
8485                         "set fan speed to %lu\n", s);
8486
8487         /* scale down from 0-255 to 0-7 */
8488         newlevel = (s >> 5) & 0x07;
8489
8490         if (mutex_lock_killable(&fan_mutex))
8491                 return -ERESTARTSYS;
8492
8493         rc = fan_get_status(&status);
8494         if (!rc && (status &
8495                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
8496                 rc = fan_set_level(newlevel);
8497                 if (rc == -ENXIO)
8498                         rc = -EINVAL;
8499                 else if (!rc) {
8500                         fan_update_desired_level(newlevel);
8501                         fan_watchdog_reset();
8502                 }
8503         }
8504
8505         mutex_unlock(&fan_mutex);
8506         return (rc) ? rc : count;
8507 }
8508
8509 static DEVICE_ATTR(pwm1, S_IWUSR | S_IRUGO, fan_pwm1_show, fan_pwm1_store);
8510
8511 /* sysfs fan fan1_input ------------------------------------------------ */
8512 static ssize_t fan_fan1_input_show(struct device *dev,
8513                            struct device_attribute *attr,
8514                            char *buf)
8515 {
8516         int res;
8517         unsigned int speed;
8518
8519         res = fan_get_speed(&speed);
8520         if (res < 0)
8521                 return res;
8522
8523         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
8524 }
8525
8526 static DEVICE_ATTR(fan1_input, S_IRUGO, fan_fan1_input_show, NULL);
8527
8528 /* sysfs fan fan2_input ------------------------------------------------ */
8529 static ssize_t fan_fan2_input_show(struct device *dev,
8530                            struct device_attribute *attr,
8531                            char *buf)
8532 {
8533         int res;
8534         unsigned int speed;
8535
8536         res = fan2_get_speed(&speed);
8537         if (res < 0)
8538                 return res;
8539
8540         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
8541 }
8542
8543 static DEVICE_ATTR(fan2_input, S_IRUGO, fan_fan2_input_show, NULL);
8544
8545 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
8546 static ssize_t fan_watchdog_show(struct device_driver *drv, char *buf)
8547 {
8548         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
8549 }
8550
8551 static ssize_t fan_watchdog_store(struct device_driver *drv, const char *buf,
8552                                   size_t count)
8553 {
8554         unsigned long t;
8555
8556         if (parse_strtoul(buf, 120, &t))
8557                 return -EINVAL;
8558
8559         if (!fan_control_allowed)
8560                 return -EPERM;
8561
8562         fan_watchdog_maxinterval = t;
8563         fan_watchdog_reset();
8564
8565         tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t);
8566
8567         return count;
8568 }
8569 static DRIVER_ATTR_RW(fan_watchdog);
8570
8571 /* --------------------------------------------------------------------- */
8572 static struct attribute *fan_attributes[] = {
8573         &dev_attr_pwm1_enable.attr, &dev_attr_pwm1.attr,
8574         &dev_attr_fan1_input.attr,
8575         NULL, /* for fan2_input */
8576         NULL
8577 };
8578
8579 static const struct attribute_group fan_attr_group = {
8580         .attrs = fan_attributes,
8581 };
8582
8583 #define TPACPI_FAN_Q1   0x0001          /* Unitialized HFSP */
8584 #define TPACPI_FAN_2FAN 0x0002          /* EC 0x31 bit 0 selects fan2 */
8585
8586 #define TPACPI_FAN_QI(__id1, __id2, __quirks)   \
8587         { .vendor = PCI_VENDOR_ID_IBM,          \
8588           .bios = TPACPI_MATCH_ANY,             \
8589           .ec = TPID(__id1, __id2),             \
8590           .quirks = __quirks }
8591
8592 #define TPACPI_FAN_QL(__id1, __id2, __quirks)   \
8593         { .vendor = PCI_VENDOR_ID_LENOVO,       \
8594           .bios = TPACPI_MATCH_ANY,             \
8595           .ec = TPID(__id1, __id2),             \
8596           .quirks = __quirks }
8597
8598 static const struct tpacpi_quirk fan_quirk_table[] __initconst = {
8599         TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1),
8600         TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1),
8601         TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1),
8602         TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1),
8603         TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN),
8604 };
8605
8606 #undef TPACPI_FAN_QL
8607 #undef TPACPI_FAN_QI
8608
8609 static int __init fan_init(struct ibm_init_struct *iibm)
8610 {
8611         int rc;
8612         unsigned long quirks;
8613
8614         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8615                         "initializing fan subdriver\n");
8616
8617         mutex_init(&fan_mutex);
8618         fan_status_access_mode = TPACPI_FAN_NONE;
8619         fan_control_access_mode = TPACPI_FAN_WR_NONE;
8620         fan_control_commands = 0;
8621         fan_watchdog_maxinterval = 0;
8622         tp_features.fan_ctrl_status_undef = 0;
8623         tp_features.second_fan = 0;
8624         fan_control_desired_level = 7;
8625
8626         if (tpacpi_is_ibm()) {
8627                 TPACPI_ACPIHANDLE_INIT(fans);
8628                 TPACPI_ACPIHANDLE_INIT(gfan);
8629                 TPACPI_ACPIHANDLE_INIT(sfan);
8630         }
8631
8632         quirks = tpacpi_check_quirks(fan_quirk_table,
8633                                      ARRAY_SIZE(fan_quirk_table));
8634
8635         if (gfan_handle) {
8636                 /* 570, 600e/x, 770e, 770x */
8637                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
8638         } else {
8639                 /* all other ThinkPads: note that even old-style
8640                  * ThinkPad ECs supports the fan control register */
8641                 if (likely(acpi_ec_read(fan_status_offset,
8642                                         &fan_control_initial_status))) {
8643                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
8644                         if (quirks & TPACPI_FAN_Q1)
8645                                 fan_quirk1_setup();
8646                         if (quirks & TPACPI_FAN_2FAN) {
8647                                 tp_features.second_fan = 1;
8648                                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8649                                         "secondary fan support enabled\n");
8650                         }
8651                 } else {
8652                         pr_err("ThinkPad ACPI EC access misbehaving, fan status and control unavailable\n");
8653                         return 1;
8654                 }
8655         }
8656
8657         if (sfan_handle) {
8658                 /* 570, 770x-JL */
8659                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
8660                 fan_control_commands |=
8661                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
8662         } else {
8663                 if (!gfan_handle) {
8664                         /* gfan without sfan means no fan control */
8665                         /* all other models implement TP EC 0x2f control */
8666
8667                         if (fans_handle) {
8668                                 /* X31, X40, X41 */
8669                                 fan_control_access_mode =
8670                                     TPACPI_FAN_WR_ACPI_FANS;
8671                                 fan_control_commands |=
8672                                     TPACPI_FAN_CMD_SPEED |
8673                                     TPACPI_FAN_CMD_LEVEL |
8674                                     TPACPI_FAN_CMD_ENABLE;
8675                         } else {
8676                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
8677                                 fan_control_commands |=
8678                                     TPACPI_FAN_CMD_LEVEL |
8679                                     TPACPI_FAN_CMD_ENABLE;
8680                         }
8681                 }
8682         }
8683
8684         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8685                 "fan is %s, modes %d, %d\n",
8686                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
8687                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
8688                 fan_status_access_mode, fan_control_access_mode);
8689
8690         /* fan control master switch */
8691         if (!fan_control_allowed) {
8692                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
8693                 fan_control_commands = 0;
8694                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
8695                            "fan control features disabled by parameter\n");
8696         }
8697
8698         /* update fan_control_desired_level */
8699         if (fan_status_access_mode != TPACPI_FAN_NONE)
8700                 fan_get_status_safe(NULL);
8701
8702         if (fan_status_access_mode != TPACPI_FAN_NONE ||
8703             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
8704                 if (tp_features.second_fan) {
8705                         /* attach second fan tachometer */
8706                         fan_attributes[ARRAY_SIZE(fan_attributes)-2] =
8707                                         &dev_attr_fan2_input.attr;
8708                 }
8709                 rc = sysfs_create_group(&tpacpi_hwmon->kobj,
8710                                          &fan_attr_group);
8711                 if (rc < 0)
8712                         return rc;
8713
8714                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
8715                                         &driver_attr_fan_watchdog);
8716                 if (rc < 0) {
8717                         sysfs_remove_group(&tpacpi_hwmon->kobj,
8718                                         &fan_attr_group);
8719                         return rc;
8720                 }
8721                 return 0;
8722         } else
8723                 return 1;
8724 }
8725
8726 static void fan_exit(void)
8727 {
8728         vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN,
8729                     "cancelling any pending fan watchdog tasks\n");
8730
8731         /* FIXME: can we really do this unconditionally? */
8732         sysfs_remove_group(&tpacpi_hwmon->kobj, &fan_attr_group);
8733         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
8734                            &driver_attr_fan_watchdog);
8735
8736         cancel_delayed_work(&fan_watchdog_task);
8737         flush_workqueue(tpacpi_wq);
8738 }
8739
8740 static void fan_suspend(void)
8741 {
8742         int rc;
8743
8744         if (!fan_control_allowed)
8745                 return;
8746
8747         /* Store fan status in cache */
8748         fan_control_resume_level = 0;
8749         rc = fan_get_status_safe(&fan_control_resume_level);
8750         if (rc < 0)
8751                 pr_notice("failed to read fan level for later restore during resume: %d\n",
8752                           rc);
8753
8754         /* if it is undefined, don't attempt to restore it.
8755          * KEEP THIS LAST */
8756         if (tp_features.fan_ctrl_status_undef)
8757                 fan_control_resume_level = 0;
8758 }
8759
8760 static void fan_resume(void)
8761 {
8762         u8 current_level = 7;
8763         bool do_set = false;
8764         int rc;
8765
8766         /* DSDT *always* updates status on resume */
8767         tp_features.fan_ctrl_status_undef = 0;
8768
8769         if (!fan_control_allowed ||
8770             !fan_control_resume_level ||
8771             (fan_get_status_safe(&current_level) < 0))
8772                 return;
8773
8774         switch (fan_control_access_mode) {
8775         case TPACPI_FAN_WR_ACPI_SFAN:
8776                 /* never decrease fan level */
8777                 do_set = (fan_control_resume_level > current_level);
8778                 break;
8779         case TPACPI_FAN_WR_ACPI_FANS:
8780         case TPACPI_FAN_WR_TPEC:
8781                 /* never decrease fan level, scale is:
8782                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
8783                  *
8784                  * We expect the firmware to set either 7 or AUTO, but we
8785                  * handle FULLSPEED out of paranoia.
8786                  *
8787                  * So, we can safely only restore FULLSPEED or 7, anything
8788                  * else could slow the fan.  Restoring AUTO is useless, at
8789                  * best that's exactly what the DSDT already set (it is the
8790                  * slower it uses).
8791                  *
8792                  * Always keep in mind that the DSDT *will* have set the
8793                  * fans to what the vendor supposes is the best level.  We
8794                  * muck with it only to speed the fan up.
8795                  */
8796                 if (fan_control_resume_level != 7 &&
8797                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
8798                         return;
8799                 else
8800                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
8801                                  (current_level != fan_control_resume_level);
8802                 break;
8803         default:
8804                 return;
8805         }
8806         if (do_set) {
8807                 pr_notice("restoring fan level to 0x%02x\n",
8808                           fan_control_resume_level);
8809                 rc = fan_set_level_safe(fan_control_resume_level);
8810                 if (rc < 0)
8811                         pr_notice("failed to restore fan level: %d\n", rc);
8812         }
8813 }
8814
8815 static int fan_read(struct seq_file *m)
8816 {
8817         int rc;
8818         u8 status;
8819         unsigned int speed = 0;
8820
8821         switch (fan_status_access_mode) {
8822         case TPACPI_FAN_RD_ACPI_GFAN:
8823                 /* 570, 600e/x, 770e, 770x */
8824                 rc = fan_get_status_safe(&status);
8825                 if (rc < 0)
8826                         return rc;
8827
8828                 seq_printf(m, "status:\t\t%s\n"
8829                                "level:\t\t%d\n",
8830                                (status != 0) ? "enabled" : "disabled", status);
8831                 break;
8832
8833         case TPACPI_FAN_RD_TPEC:
8834                 /* all except 570, 600e/x, 770e, 770x */
8835                 rc = fan_get_status_safe(&status);
8836                 if (rc < 0)
8837                         return rc;
8838
8839                 seq_printf(m, "status:\t\t%s\n",
8840                                (status != 0) ? "enabled" : "disabled");
8841
8842                 rc = fan_get_speed(&speed);
8843                 if (rc < 0)
8844                         return rc;
8845
8846                 seq_printf(m, "speed:\t\t%d\n", speed);
8847
8848                 if (status & TP_EC_FAN_FULLSPEED)
8849                         /* Disengaged mode takes precedence */
8850                         seq_printf(m, "level:\t\tdisengaged\n");
8851                 else if (status & TP_EC_FAN_AUTO)
8852                         seq_printf(m, "level:\t\tauto\n");
8853                 else
8854                         seq_printf(m, "level:\t\t%d\n", status);
8855                 break;
8856
8857         case TPACPI_FAN_NONE:
8858         default:
8859                 seq_printf(m, "status:\t\tnot supported\n");
8860         }
8861
8862         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
8863                 seq_printf(m, "commands:\tlevel <level>");
8864
8865                 switch (fan_control_access_mode) {
8866                 case TPACPI_FAN_WR_ACPI_SFAN:
8867                         seq_printf(m, " (<level> is 0-7)\n");
8868                         break;
8869
8870                 default:
8871                         seq_printf(m, " (<level> is 0-7, auto, disengaged, full-speed)\n");
8872                         break;
8873                 }
8874         }
8875
8876         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
8877                 seq_printf(m, "commands:\tenable, disable\n"
8878                                "commands:\twatchdog <timeout> (<timeout> is 0 (off), 1-120 (seconds))\n");
8879
8880         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
8881                 seq_printf(m, "commands:\tspeed <speed> (<speed> is 0-65535)\n");
8882
8883         return 0;
8884 }
8885
8886 static int fan_write_cmd_level(const char *cmd, int *rc)
8887 {
8888         int level;
8889
8890         if (strlencmp(cmd, "level auto") == 0)
8891                 level = TP_EC_FAN_AUTO;
8892         else if ((strlencmp(cmd, "level disengaged") == 0) |
8893                         (strlencmp(cmd, "level full-speed") == 0))
8894                 level = TP_EC_FAN_FULLSPEED;
8895         else if (sscanf(cmd, "level %d", &level) != 1)
8896                 return 0;
8897
8898         *rc = fan_set_level_safe(level);
8899         if (*rc == -ENXIO)
8900                 pr_err("level command accepted for unsupported access mode %d\n",
8901                        fan_control_access_mode);
8902         else if (!*rc)
8903                 tpacpi_disclose_usertask("procfs fan",
8904                         "set level to %d\n", level);
8905
8906         return 1;
8907 }
8908
8909 static int fan_write_cmd_enable(const char *cmd, int *rc)
8910 {
8911         if (strlencmp(cmd, "enable") != 0)
8912                 return 0;
8913
8914         *rc = fan_set_enable();
8915         if (*rc == -ENXIO)
8916                 pr_err("enable command accepted for unsupported access mode %d\n",
8917                        fan_control_access_mode);
8918         else if (!*rc)
8919                 tpacpi_disclose_usertask("procfs fan", "enable\n");
8920
8921         return 1;
8922 }
8923
8924 static int fan_write_cmd_disable(const char *cmd, int *rc)
8925 {
8926         if (strlencmp(cmd, "disable") != 0)
8927                 return 0;
8928
8929         *rc = fan_set_disable();
8930         if (*rc == -ENXIO)
8931                 pr_err("disable command accepted for unsupported access mode %d\n",
8932                        fan_control_access_mode);
8933         else if (!*rc)
8934                 tpacpi_disclose_usertask("procfs fan", "disable\n");
8935
8936         return 1;
8937 }
8938
8939 static int fan_write_cmd_speed(const char *cmd, int *rc)
8940 {
8941         int speed;
8942
8943         /* TODO:
8944          * Support speed <low> <medium> <high> ? */
8945
8946         if (sscanf(cmd, "speed %d", &speed) != 1)
8947                 return 0;
8948
8949         *rc = fan_set_speed(speed);
8950         if (*rc == -ENXIO)
8951                 pr_err("speed command accepted for unsupported access mode %d\n",
8952                        fan_control_access_mode);
8953         else if (!*rc)
8954                 tpacpi_disclose_usertask("procfs fan",
8955                         "set speed to %d\n", speed);
8956
8957         return 1;
8958 }
8959
8960 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
8961 {
8962         int interval;
8963
8964         if (sscanf(cmd, "watchdog %d", &interval) != 1)
8965                 return 0;
8966
8967         if (interval < 0 || interval > 120)
8968                 *rc = -EINVAL;
8969         else {
8970                 fan_watchdog_maxinterval = interval;
8971                 tpacpi_disclose_usertask("procfs fan",
8972                         "set watchdog timer to %d\n",
8973                         interval);
8974         }
8975
8976         return 1;
8977 }
8978
8979 static int fan_write(char *buf)
8980 {
8981         char *cmd;
8982         int rc = 0;
8983
8984         while (!rc && (cmd = next_cmd(&buf))) {
8985                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
8986                       fan_write_cmd_level(cmd, &rc)) &&
8987                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
8988                       (fan_write_cmd_enable(cmd, &rc) ||
8989                        fan_write_cmd_disable(cmd, &rc) ||
8990                        fan_write_cmd_watchdog(cmd, &rc))) &&
8991                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
8992                       fan_write_cmd_speed(cmd, &rc))
8993                     )
8994                         rc = -EINVAL;
8995                 else if (!rc)
8996                         fan_watchdog_reset();
8997         }
8998
8999         return rc;
9000 }
9001
9002 static struct ibm_struct fan_driver_data = {
9003         .name = "fan",
9004         .read = fan_read,
9005         .write = fan_write,
9006         .exit = fan_exit,
9007         .suspend = fan_suspend,
9008         .resume = fan_resume,
9009 };
9010
9011 /*************************************************************************
9012  * Mute LED subdriver
9013  */
9014
9015
9016 struct tp_led_table {
9017         acpi_string name;
9018         int on_value;
9019         int off_value;
9020         int state;
9021 };
9022
9023 static struct tp_led_table led_tables[] = {
9024         [TPACPI_LED_MUTE] = {
9025                 .name = "SSMS",
9026                 .on_value = 1,
9027                 .off_value = 0,
9028         },
9029         [TPACPI_LED_MICMUTE] = {
9030                 .name = "MMTS",
9031                 .on_value = 2,
9032                 .off_value = 0,
9033         },
9034 };
9035
9036 static int mute_led_on_off(struct tp_led_table *t, bool state)
9037 {
9038         acpi_handle temp;
9039         int output;
9040
9041         if (ACPI_FAILURE(acpi_get_handle(hkey_handle, t->name, &temp))) {
9042                 pr_warn("Thinkpad ACPI has no %s interface.\n", t->name);
9043                 return -EIO;
9044         }
9045
9046         if (!acpi_evalf(hkey_handle, &output, t->name, "dd",
9047                         state ? t->on_value : t->off_value))
9048                 return -EIO;
9049
9050         t->state = state;
9051         return state;
9052 }
9053
9054 int tpacpi_led_set(int whichled, bool on)
9055 {
9056         struct tp_led_table *t;
9057
9058         if (whichled < 0 || whichled >= TPACPI_LED_MAX)
9059                 return -EINVAL;
9060
9061         t = &led_tables[whichled];
9062         if (t->state < 0 || t->state == on)
9063                 return t->state;
9064         return mute_led_on_off(t, on);
9065 }
9066 EXPORT_SYMBOL_GPL(tpacpi_led_set);
9067
9068 static int mute_led_init(struct ibm_init_struct *iibm)
9069 {
9070         acpi_handle temp;
9071         int i;
9072
9073         for (i = 0; i < TPACPI_LED_MAX; i++) {
9074                 struct tp_led_table *t = &led_tables[i];
9075                 if (ACPI_SUCCESS(acpi_get_handle(hkey_handle, t->name, &temp)))
9076                         mute_led_on_off(t, false);
9077                 else
9078                         t->state = -ENODEV;
9079         }
9080         return 0;
9081 }
9082
9083 static void mute_led_exit(void)
9084 {
9085         int i;
9086
9087         for (i = 0; i < TPACPI_LED_MAX; i++)
9088                 tpacpi_led_set(i, false);
9089 }
9090
9091 static void mute_led_resume(void)
9092 {
9093         int i;
9094
9095         for (i = 0; i < TPACPI_LED_MAX; i++) {
9096                 struct tp_led_table *t = &led_tables[i];
9097                 if (t->state >= 0)
9098                         mute_led_on_off(t, t->state);
9099         }
9100 }
9101
9102 static struct ibm_struct mute_led_driver_data = {
9103         .name = "mute_led",
9104         .exit = mute_led_exit,
9105         .resume = mute_led_resume,
9106 };
9107
9108 /****************************************************************************
9109  ****************************************************************************
9110  *
9111  * Infrastructure
9112  *
9113  ****************************************************************************
9114  ****************************************************************************/
9115
9116 /*
9117  * HKEY event callout for other subdrivers go here
9118  * (yes, it is ugly, but it is quick, safe, and gets the job done
9119  */
9120 static void tpacpi_driver_event(const unsigned int hkey_event)
9121 {
9122         if (ibm_backlight_device) {
9123                 switch (hkey_event) {
9124                 case TP_HKEY_EV_BRGHT_UP:
9125                 case TP_HKEY_EV_BRGHT_DOWN:
9126                         tpacpi_brightness_notify_change();
9127                 }
9128         }
9129         if (alsa_card) {
9130                 switch (hkey_event) {
9131                 case TP_HKEY_EV_VOL_UP:
9132                 case TP_HKEY_EV_VOL_DOWN:
9133                 case TP_HKEY_EV_VOL_MUTE:
9134                         volume_alsa_notify_change();
9135                 }
9136         }
9137         if (tp_features.kbdlight && hkey_event == TP_HKEY_EV_KBD_LIGHT) {
9138                 enum led_brightness brightness;
9139
9140                 mutex_lock(&kbdlight_mutex);
9141
9142                 /*
9143                  * Check the brightness actually changed, setting the brightness
9144                  * through kbdlight_set_level() also triggers this event.
9145                  */
9146                 brightness = kbdlight_sysfs_get(NULL);
9147                 if (kbdlight_brightness != brightness) {
9148                         kbdlight_brightness = brightness;
9149                         led_classdev_notify_brightness_hw_changed(
9150                                 &tpacpi_led_kbdlight.led_classdev, brightness);
9151                 }
9152
9153                 mutex_unlock(&kbdlight_mutex);
9154         }
9155 }
9156
9157 static void hotkey_driver_event(const unsigned int scancode)
9158 {
9159         tpacpi_driver_event(TP_HKEY_EV_HOTKEY_BASE + scancode);
9160 }
9161
9162 /* --------------------------------------------------------------------- */
9163
9164 /* /proc support */
9165 static struct proc_dir_entry *proc_dir;
9166
9167 /*
9168  * Module and infrastructure proble, init and exit handling
9169  */
9170
9171 static bool force_load;
9172
9173 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
9174 static const char * __init str_supported(int is_supported)
9175 {
9176         static char text_unsupported[] __initdata = "not supported";
9177
9178         return (is_supported) ? &text_unsupported[4] : &text_unsupported[0];
9179 }
9180 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
9181
9182 static void ibm_exit(struct ibm_struct *ibm)
9183 {
9184         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
9185
9186         list_del_init(&ibm->all_drivers);
9187
9188         if (ibm->flags.acpi_notify_installed) {
9189                 dbg_printk(TPACPI_DBG_EXIT,
9190                         "%s: acpi_remove_notify_handler\n", ibm->name);
9191                 BUG_ON(!ibm->acpi);
9192                 acpi_remove_notify_handler(*ibm->acpi->handle,
9193                                            ibm->acpi->type,
9194                                            dispatch_acpi_notify);
9195                 ibm->flags.acpi_notify_installed = 0;
9196         }
9197
9198         if (ibm->flags.proc_created) {
9199                 dbg_printk(TPACPI_DBG_EXIT,
9200                         "%s: remove_proc_entry\n", ibm->name);
9201                 remove_proc_entry(ibm->name, proc_dir);
9202                 ibm->flags.proc_created = 0;
9203         }
9204
9205         if (ibm->flags.acpi_driver_registered) {
9206                 dbg_printk(TPACPI_DBG_EXIT,
9207                         "%s: acpi_bus_unregister_driver\n", ibm->name);
9208                 BUG_ON(!ibm->acpi);
9209                 acpi_bus_unregister_driver(ibm->acpi->driver);
9210                 kfree(ibm->acpi->driver);
9211                 ibm->acpi->driver = NULL;
9212                 ibm->flags.acpi_driver_registered = 0;
9213         }
9214
9215         if (ibm->flags.init_called && ibm->exit) {
9216                 ibm->exit();
9217                 ibm->flags.init_called = 0;
9218         }
9219
9220         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
9221 }
9222
9223 static int __init ibm_init(struct ibm_init_struct *iibm)
9224 {
9225         int ret;
9226         struct ibm_struct *ibm = iibm->data;
9227         struct proc_dir_entry *entry;
9228
9229         BUG_ON(ibm == NULL);
9230
9231         INIT_LIST_HEAD(&ibm->all_drivers);
9232
9233         if (ibm->flags.experimental && !experimental)
9234                 return 0;
9235
9236         dbg_printk(TPACPI_DBG_INIT,
9237                 "probing for %s\n", ibm->name);
9238
9239         if (iibm->init) {
9240                 ret = iibm->init(iibm);
9241                 if (ret > 0)
9242                         return 0;       /* probe failed */
9243                 if (ret)
9244                         return ret;
9245
9246                 ibm->flags.init_called = 1;
9247         }
9248
9249         if (ibm->acpi) {
9250                 if (ibm->acpi->hid) {
9251                         ret = register_tpacpi_subdriver(ibm);
9252                         if (ret)
9253                                 goto err_out;
9254                 }
9255
9256                 if (ibm->acpi->notify) {
9257                         ret = setup_acpi_notify(ibm);
9258                         if (ret == -ENODEV) {
9259                                 pr_notice("disabling subdriver %s\n",
9260                                           ibm->name);
9261                                 ret = 0;
9262                                 goto err_out;
9263                         }
9264                         if (ret < 0)
9265                                 goto err_out;
9266                 }
9267         }
9268
9269         dbg_printk(TPACPI_DBG_INIT,
9270                 "%s installed\n", ibm->name);
9271
9272         if (ibm->read) {
9273                 umode_t mode = iibm->base_procfs_mode;
9274
9275                 if (!mode)
9276                         mode = S_IRUGO;
9277                 if (ibm->write)
9278                         mode |= S_IWUSR;
9279                 entry = proc_create_data(ibm->name, mode, proc_dir,
9280                                          &dispatch_proc_fops, ibm);
9281                 if (!entry) {
9282                         pr_err("unable to create proc entry %s\n", ibm->name);
9283                         ret = -ENODEV;
9284                         goto err_out;
9285                 }
9286                 ibm->flags.proc_created = 1;
9287         }
9288
9289         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
9290
9291         return 0;
9292
9293 err_out:
9294         dbg_printk(TPACPI_DBG_INIT,
9295                 "%s: at error exit path with result %d\n",
9296                 ibm->name, ret);
9297
9298         ibm_exit(ibm);
9299         return (ret < 0) ? ret : 0;
9300 }
9301
9302 /* Probing */
9303
9304 static bool __pure __init tpacpi_is_fw_digit(const char c)
9305 {
9306         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z');
9307 }
9308
9309 static bool __pure __init tpacpi_is_valid_fw_id(const char * const s,
9310                                                 const char t)
9311 {
9312         /*
9313          * Most models: xxyTkkWW (#.##c)
9314          * Ancient 570/600 and -SL lacks (#.##c)
9315          */
9316         if (s && strlen(s) >= 8 &&
9317                 tpacpi_is_fw_digit(s[0]) &&
9318                 tpacpi_is_fw_digit(s[1]) &&
9319                 s[2] == t &&
9320                 (s[3] == 'T' || s[3] == 'N') &&
9321                 tpacpi_is_fw_digit(s[4]) &&
9322                 tpacpi_is_fw_digit(s[5]))
9323                 return true;
9324
9325         /* New models: xxxyTkkW (#.##c); T550 and some others */
9326         return s && strlen(s) >= 8 &&
9327                 tpacpi_is_fw_digit(s[0]) &&
9328                 tpacpi_is_fw_digit(s[1]) &&
9329                 tpacpi_is_fw_digit(s[2]) &&
9330                 s[3] == t &&
9331                 (s[4] == 'T' || s[4] == 'N') &&
9332                 tpacpi_is_fw_digit(s[5]) &&
9333                 tpacpi_is_fw_digit(s[6]);
9334 }
9335
9336 /* returns 0 - probe ok, or < 0 - probe error.
9337  * Probe ok doesn't mean thinkpad found.
9338  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
9339 static int __must_check __init get_thinkpad_model_data(
9340                                                 struct thinkpad_id_data *tp)
9341 {
9342         const struct dmi_device *dev = NULL;
9343         char ec_fw_string[18];
9344         char const *s;
9345
9346         if (!tp)
9347                 return -EINVAL;
9348
9349         memset(tp, 0, sizeof(*tp));
9350
9351         if (dmi_name_in_vendors("IBM"))
9352                 tp->vendor = PCI_VENDOR_ID_IBM;
9353         else if (dmi_name_in_vendors("LENOVO"))
9354                 tp->vendor = PCI_VENDOR_ID_LENOVO;
9355         else
9356                 return 0;
9357
9358         s = dmi_get_system_info(DMI_BIOS_VERSION);
9359         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
9360         if (s && !tp->bios_version_str)
9361                 return -ENOMEM;
9362
9363         /* Really ancient ThinkPad 240X will fail this, which is fine */
9364         if (!(tpacpi_is_valid_fw_id(tp->bios_version_str, 'E') ||
9365               tpacpi_is_valid_fw_id(tp->bios_version_str, 'C')))
9366                 return 0;
9367
9368         tp->bios_model = tp->bios_version_str[0]
9369                          | (tp->bios_version_str[1] << 8);
9370         tp->bios_release = (tp->bios_version_str[4] << 8)
9371                          | tp->bios_version_str[5];
9372
9373         /*
9374          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
9375          * X32 or newer, all Z series;  Some models must have an
9376          * up-to-date BIOS or they will not be detected.
9377          *
9378          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
9379          */
9380         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
9381                 if (sscanf(dev->name,
9382                            "IBM ThinkPad Embedded Controller -[%17c",
9383                            ec_fw_string) == 1) {
9384                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
9385                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
9386
9387                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
9388                         if (!tp->ec_version_str)
9389                                 return -ENOMEM;
9390
9391                         if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) {
9392                                 tp->ec_model = ec_fw_string[0]
9393                                                 | (ec_fw_string[1] << 8);
9394                                 tp->ec_release = (ec_fw_string[4] << 8)
9395                                                 | ec_fw_string[5];
9396                         } else {
9397                                 pr_notice("ThinkPad firmware release %s doesn't match the known patterns\n",
9398                                           ec_fw_string);
9399                                 pr_notice("please report this to %s\n",
9400                                           TPACPI_MAIL);
9401                         }
9402                         break;
9403                 }
9404         }
9405
9406         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
9407         if (s && !(strncasecmp(s, "ThinkPad", 8) && strncasecmp(s, "Lenovo", 6))) {
9408                 tp->model_str = kstrdup(s, GFP_KERNEL);
9409                 if (!tp->model_str)
9410                         return -ENOMEM;
9411         } else {
9412                 s = dmi_get_system_info(DMI_BIOS_VENDOR);
9413                 if (s && !(strncasecmp(s, "Lenovo", 6))) {
9414                         tp->model_str = kstrdup(s, GFP_KERNEL);
9415                         if (!tp->model_str)
9416                                 return -ENOMEM;
9417                 }
9418         }
9419
9420         s = dmi_get_system_info(DMI_PRODUCT_NAME);
9421         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
9422         if (s && !tp->nummodel_str)
9423                 return -ENOMEM;
9424
9425         return 0;
9426 }
9427
9428 static int __init probe_for_thinkpad(void)
9429 {
9430         int is_thinkpad;
9431
9432         if (acpi_disabled)
9433                 return -ENODEV;
9434
9435         /* It would be dangerous to run the driver in this case */
9436         if (!tpacpi_is_ibm() && !tpacpi_is_lenovo())
9437                 return -ENODEV;
9438
9439         /*
9440          * Non-ancient models have better DMI tagging, but very old models
9441          * don't.  tpacpi_is_fw_known() is a cheat to help in that case.
9442          */
9443         is_thinkpad = (thinkpad_id.model_str != NULL) ||
9444                       (thinkpad_id.ec_model != 0) ||
9445                       tpacpi_is_fw_known();
9446
9447         /* The EC handler is required */
9448         tpacpi_acpi_handle_locate("ec", TPACPI_ACPI_EC_HID, &ec_handle);
9449         if (!ec_handle) {
9450                 if (is_thinkpad)
9451                         pr_err("Not yet supported ThinkPad detected!\n");
9452                 return -ENODEV;
9453         }
9454
9455         if (!is_thinkpad && !force_load)
9456                 return -ENODEV;
9457
9458         return 0;
9459 }
9460
9461 static void __init thinkpad_acpi_init_banner(void)
9462 {
9463         pr_info("%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
9464         pr_info("%s\n", TPACPI_URL);
9465
9466         pr_info("ThinkPad BIOS %s, EC %s\n",
9467                 (thinkpad_id.bios_version_str) ?
9468                         thinkpad_id.bios_version_str : "unknown",
9469                 (thinkpad_id.ec_version_str) ?
9470                         thinkpad_id.ec_version_str : "unknown");
9471
9472         BUG_ON(!thinkpad_id.vendor);
9473
9474         if (thinkpad_id.model_str)
9475                 pr_info("%s %s, model %s\n",
9476                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
9477                                 "IBM" : ((thinkpad_id.vendor ==
9478                                                 PCI_VENDOR_ID_LENOVO) ?
9479                                         "Lenovo" : "Unknown vendor"),
9480                         thinkpad_id.model_str,
9481                         (thinkpad_id.nummodel_str) ?
9482                                 thinkpad_id.nummodel_str : "unknown");
9483 }
9484
9485 /* Module init, exit, parameters */
9486
9487 static struct ibm_init_struct ibms_init[] __initdata = {
9488         {
9489                 .data = &thinkpad_acpi_driver_data,
9490         },
9491         {
9492                 .init = hotkey_init,
9493                 .data = &hotkey_driver_data,
9494         },
9495         {
9496                 .init = bluetooth_init,
9497                 .data = &bluetooth_driver_data,
9498         },
9499         {
9500                 .init = wan_init,
9501                 .data = &wan_driver_data,
9502         },
9503         {
9504                 .init = uwb_init,
9505                 .data = &uwb_driver_data,
9506         },
9507 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
9508         {
9509                 .init = video_init,
9510                 .base_procfs_mode = S_IRUSR,
9511                 .data = &video_driver_data,
9512         },
9513 #endif
9514         {
9515                 .init = kbdlight_init,
9516                 .data = &kbdlight_driver_data,
9517         },
9518         {
9519                 .init = light_init,
9520                 .data = &light_driver_data,
9521         },
9522         {
9523                 .init = cmos_init,
9524                 .data = &cmos_driver_data,
9525         },
9526         {
9527                 .init = led_init,
9528                 .data = &led_driver_data,
9529         },
9530         {
9531                 .init = beep_init,
9532                 .data = &beep_driver_data,
9533         },
9534         {
9535                 .init = thermal_init,
9536                 .data = &thermal_driver_data,
9537         },
9538         {
9539                 .init = brightness_init,
9540                 .data = &brightness_driver_data,
9541         },
9542         {
9543                 .init = volume_init,
9544                 .data = &volume_driver_data,
9545         },
9546         {
9547                 .init = fan_init,
9548                 .data = &fan_driver_data,
9549         },
9550         {
9551                 .init = mute_led_init,
9552                 .data = &mute_led_driver_data,
9553         },
9554 };
9555
9556 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
9557 {
9558         unsigned int i;
9559         struct ibm_struct *ibm;
9560
9561         if (!kp || !kp->name || !val)
9562                 return -EINVAL;
9563
9564         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
9565                 ibm = ibms_init[i].data;
9566                 WARN_ON(ibm == NULL);
9567
9568                 if (!ibm || !ibm->name)
9569                         continue;
9570
9571                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
9572                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
9573                                 return -ENOSPC;
9574                         strcpy(ibms_init[i].param, val);
9575                         strcat(ibms_init[i].param, ",");
9576                         return 0;
9577                 }
9578         }
9579
9580         return -EINVAL;
9581 }
9582
9583 module_param(experimental, int, 0444);
9584 MODULE_PARM_DESC(experimental,
9585                  "Enables experimental features when non-zero");
9586
9587 module_param_named(debug, dbg_level, uint, 0);
9588 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
9589
9590 module_param(force_load, bool, 0444);
9591 MODULE_PARM_DESC(force_load,
9592                  "Attempts to load the driver even on a mis-identified ThinkPad when true");
9593
9594 module_param_named(fan_control, fan_control_allowed, bool, 0444);
9595 MODULE_PARM_DESC(fan_control,
9596                  "Enables setting fan parameters features when true");
9597
9598 module_param_named(brightness_mode, brightness_mode, uint, 0444);
9599 MODULE_PARM_DESC(brightness_mode,
9600                  "Selects brightness control strategy: 0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM");
9601
9602 module_param(brightness_enable, uint, 0444);
9603 MODULE_PARM_DESC(brightness_enable,
9604                  "Enables backlight control when 1, disables when 0");
9605
9606 #ifdef CONFIG_THINKPAD_ACPI_ALSA_SUPPORT
9607 module_param_named(volume_mode, volume_mode, uint, 0444);
9608 MODULE_PARM_DESC(volume_mode,
9609                  "Selects volume control strategy: 0=auto, 1=EC, 2=N/A, 3=EC+NVRAM");
9610
9611 module_param_named(volume_capabilities, volume_capabilities, uint, 0444);
9612 MODULE_PARM_DESC(volume_capabilities,
9613                  "Selects the mixer capabilites: 0=auto, 1=volume and mute, 2=mute only");
9614
9615 module_param_named(volume_control, volume_control_allowed, bool, 0444);
9616 MODULE_PARM_DESC(volume_control,
9617                  "Enables software override for the console audio control when true");
9618
9619 module_param_named(software_mute, software_mute_requested, bool, 0444);
9620 MODULE_PARM_DESC(software_mute,
9621                  "Request full software mute control");
9622
9623 /* ALSA module API parameters */
9624 module_param_named(index, alsa_index, int, 0444);
9625 MODULE_PARM_DESC(index, "ALSA index for the ACPI EC Mixer");
9626 module_param_named(id, alsa_id, charp, 0444);
9627 MODULE_PARM_DESC(id, "ALSA id for the ACPI EC Mixer");
9628 module_param_named(enable, alsa_enable, bool, 0444);
9629 MODULE_PARM_DESC(enable, "Enable the ALSA interface for the ACPI EC Mixer");
9630 #endif /* CONFIG_THINKPAD_ACPI_ALSA_SUPPORT */
9631
9632 /* The module parameter can't be read back, that's why 0 is used here */
9633 #define TPACPI_PARAM(feature) \
9634         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
9635         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command at module load, see documentation")
9636
9637 TPACPI_PARAM(hotkey);
9638 TPACPI_PARAM(bluetooth);
9639 TPACPI_PARAM(video);
9640 TPACPI_PARAM(light);
9641 TPACPI_PARAM(cmos);
9642 TPACPI_PARAM(led);
9643 TPACPI_PARAM(beep);
9644 TPACPI_PARAM(brightness);
9645 TPACPI_PARAM(volume);
9646 TPACPI_PARAM(fan);
9647
9648 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
9649 module_param(dbg_wlswemul, uint, 0444);
9650 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
9651 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
9652 MODULE_PARM_DESC(wlsw_state,
9653                  "Initial state of the emulated WLSW switch");
9654
9655 module_param(dbg_bluetoothemul, uint, 0444);
9656 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
9657 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
9658 MODULE_PARM_DESC(bluetooth_state,
9659                  "Initial state of the emulated bluetooth switch");
9660
9661 module_param(dbg_wwanemul, uint, 0444);
9662 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
9663 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
9664 MODULE_PARM_DESC(wwan_state,
9665                  "Initial state of the emulated WWAN switch");
9666
9667 module_param(dbg_uwbemul, uint, 0444);
9668 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
9669 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
9670 MODULE_PARM_DESC(uwb_state,
9671                  "Initial state of the emulated UWB switch");
9672 #endif
9673
9674 static void thinkpad_acpi_module_exit(void)
9675 {
9676         struct ibm_struct *ibm, *itmp;
9677
9678         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
9679
9680         list_for_each_entry_safe_reverse(ibm, itmp,
9681                                          &tpacpi_all_drivers,
9682                                          all_drivers) {
9683                 ibm_exit(ibm);
9684         }
9685
9686         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
9687
9688         if (tpacpi_inputdev) {
9689                 if (tp_features.input_device_registered)
9690                         input_unregister_device(tpacpi_inputdev);
9691                 else
9692                         input_free_device(tpacpi_inputdev);
9693                 kfree(hotkey_keycode_map);
9694         }
9695
9696         if (tpacpi_hwmon)
9697                 hwmon_device_unregister(tpacpi_hwmon);
9698
9699         if (tpacpi_sensors_pdev)
9700                 platform_device_unregister(tpacpi_sensors_pdev);
9701         if (tpacpi_pdev)
9702                 platform_device_unregister(tpacpi_pdev);
9703
9704         if (tp_features.sensors_pdrv_attrs_registered)
9705                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
9706         if (tp_features.platform_drv_attrs_registered)
9707                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
9708
9709         if (tp_features.sensors_pdrv_registered)
9710                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
9711
9712         if (tp_features.platform_drv_registered)
9713                 platform_driver_unregister(&tpacpi_pdriver);
9714
9715         if (proc_dir)
9716                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
9717
9718         if (tpacpi_wq)
9719                 destroy_workqueue(tpacpi_wq);
9720
9721         kfree(thinkpad_id.bios_version_str);
9722         kfree(thinkpad_id.ec_version_str);
9723         kfree(thinkpad_id.model_str);
9724         kfree(thinkpad_id.nummodel_str);
9725 }
9726
9727
9728 static int __init thinkpad_acpi_module_init(void)
9729 {
9730         int ret, i;
9731
9732         tpacpi_lifecycle = TPACPI_LIFE_INIT;
9733
9734         /* Driver-level probe */
9735
9736         ret = get_thinkpad_model_data(&thinkpad_id);
9737         if (ret) {
9738                 pr_err("unable to get DMI data: %d\n", ret);
9739                 thinkpad_acpi_module_exit();
9740                 return ret;
9741         }
9742         ret = probe_for_thinkpad();
9743         if (ret) {
9744                 thinkpad_acpi_module_exit();
9745                 return ret;
9746         }
9747
9748         /* Driver initialization */
9749
9750         thinkpad_acpi_init_banner();
9751         tpacpi_check_outdated_fw();
9752
9753         TPACPI_ACPIHANDLE_INIT(ecrd);
9754         TPACPI_ACPIHANDLE_INIT(ecwr);
9755
9756         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
9757         if (!tpacpi_wq) {
9758                 thinkpad_acpi_module_exit();
9759                 return -ENOMEM;
9760         }
9761
9762         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
9763         if (!proc_dir) {
9764                 pr_err("unable to create proc dir " TPACPI_PROC_DIR "\n");
9765                 thinkpad_acpi_module_exit();
9766                 return -ENODEV;
9767         }
9768
9769         ret = platform_driver_register(&tpacpi_pdriver);
9770         if (ret) {
9771                 pr_err("unable to register main platform driver\n");
9772                 thinkpad_acpi_module_exit();
9773                 return ret;
9774         }
9775         tp_features.platform_drv_registered = 1;
9776
9777         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
9778         if (ret) {
9779                 pr_err("unable to register hwmon platform driver\n");
9780                 thinkpad_acpi_module_exit();
9781                 return ret;
9782         }
9783         tp_features.sensors_pdrv_registered = 1;
9784
9785         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
9786         if (!ret) {
9787                 tp_features.platform_drv_attrs_registered = 1;
9788                 ret = tpacpi_create_driver_attributes(
9789                                         &tpacpi_hwmon_pdriver.driver);
9790         }
9791         if (ret) {
9792                 pr_err("unable to create sysfs driver attributes\n");
9793                 thinkpad_acpi_module_exit();
9794                 return ret;
9795         }
9796         tp_features.sensors_pdrv_attrs_registered = 1;
9797
9798
9799         /* Device initialization */
9800         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
9801                                                         NULL, 0);
9802         if (IS_ERR(tpacpi_pdev)) {
9803                 ret = PTR_ERR(tpacpi_pdev);
9804                 tpacpi_pdev = NULL;
9805                 pr_err("unable to register platform device\n");
9806                 thinkpad_acpi_module_exit();
9807                 return ret;
9808         }
9809         tpacpi_sensors_pdev = platform_device_register_simple(
9810                                                 TPACPI_HWMON_DRVR_NAME,
9811                                                 -1, NULL, 0);
9812         if (IS_ERR(tpacpi_sensors_pdev)) {
9813                 ret = PTR_ERR(tpacpi_sensors_pdev);
9814                 tpacpi_sensors_pdev = NULL;
9815                 pr_err("unable to register hwmon platform device\n");
9816                 thinkpad_acpi_module_exit();
9817                 return ret;
9818         }
9819         tp_features.sensors_pdev_attrs_registered = 1;
9820         tpacpi_hwmon = hwmon_device_register_with_groups(
9821                 &tpacpi_sensors_pdev->dev, TPACPI_NAME, NULL, NULL);
9822
9823         if (IS_ERR(tpacpi_hwmon)) {
9824                 ret = PTR_ERR(tpacpi_hwmon);
9825                 tpacpi_hwmon = NULL;
9826                 pr_err("unable to register hwmon device\n");
9827                 thinkpad_acpi_module_exit();
9828                 return ret;
9829         }
9830         mutex_init(&tpacpi_inputdev_send_mutex);
9831         tpacpi_inputdev = input_allocate_device();
9832         if (!tpacpi_inputdev) {
9833                 thinkpad_acpi_module_exit();
9834                 return -ENOMEM;
9835         } else {
9836                 /* Prepare input device, but don't register */
9837                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
9838                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
9839                 tpacpi_inputdev->id.bustype = BUS_HOST;
9840                 tpacpi_inputdev->id.vendor = thinkpad_id.vendor;
9841                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
9842                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
9843                 tpacpi_inputdev->dev.parent = &tpacpi_pdev->dev;
9844         }
9845
9846         /* Init subdriver dependencies */
9847         tpacpi_detect_brightness_capabilities();
9848
9849         /* Init subdrivers */
9850         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
9851                 ret = ibm_init(&ibms_init[i]);
9852                 if (ret >= 0 && *ibms_init[i].param)
9853                         ret = ibms_init[i].data->write(ibms_init[i].param);
9854                 if (ret < 0) {
9855                         thinkpad_acpi_module_exit();
9856                         return ret;
9857                 }
9858         }
9859
9860         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
9861
9862         ret = input_register_device(tpacpi_inputdev);
9863         if (ret < 0) {
9864                 pr_err("unable to register input device\n");
9865                 thinkpad_acpi_module_exit();
9866                 return ret;
9867         } else {
9868                 tp_features.input_device_registered = 1;
9869         }
9870
9871         return 0;
9872 }
9873
9874 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
9875
9876 /*
9877  * This will autoload the driver in almost every ThinkPad
9878  * in widespread use.
9879  *
9880  * Only _VERY_ old models, like the 240, 240x and 570 lack
9881  * the HKEY event interface.
9882  */
9883 MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids);
9884
9885 /*
9886  * DMI matching for module autoloading
9887  *
9888  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
9889  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
9890  *
9891  * Only models listed in thinkwiki will be supported, so add yours
9892  * if it is not there yet.
9893  */
9894 #define IBM_BIOS_MODULE_ALIAS(__type) \
9895         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*")
9896
9897 /* Ancient thinkpad BIOSes have to be identified by
9898  * BIOS type or model number, and there are far less
9899  * BIOS types than model numbers... */
9900 IBM_BIOS_MODULE_ALIAS("I[MU]");         /* 570, 570e */
9901
9902 MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>");
9903 MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>");
9904 MODULE_DESCRIPTION(TPACPI_DESC);
9905 MODULE_VERSION(TPACPI_VERSION);
9906 MODULE_LICENSE("GPL");
9907
9908 module_init(thinkpad_acpi_module_init);
9909 module_exit(thinkpad_acpi_module_exit);