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