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