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