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