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