thinkpad-acpi: make driver events work in NVRAM poll mode
[linux-2.6.git] / drivers / platform / x86 / thinkpad_acpi.c
1 /*
2  *  thinkpad_acpi.c - ThinkPad ACPI Extras
3  *
4  *
5  *  Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net>
6  *  Copyright (C) 2006-2009 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  *  02110-1301, USA.
22  */
23
24 #define TPACPI_VERSION "0.24"
25 #define TPACPI_SYSFS_VERSION 0x020700
26
27 /*
28  *  Changelog:
29  *  2007-10-20          changelog trimmed down
30  *
31  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
32  *                      drivers/misc.
33  *
34  *  2006-11-22  0.13    new maintainer
35  *                      changelog now lives in git commit history, and will
36  *                      not be updated further in-file.
37  *
38  *  2005-03-17  0.11    support for 600e, 770x
39  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
40  *
41  *  2005-01-16  0.9     use MODULE_VERSION
42  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
43  *                      fix parameter passing on module loading
44  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
45  *                          thanks to Jim Radford <radford@blackbean.org>
46  *  2004-11-08  0.8     fix init error case, don't return from a macro
47  *                          thanks to Chris Wright <chrisw@osdl.org>
48  */
49
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/init.h>
53 #include <linux/types.h>
54 #include <linux/string.h>
55 #include <linux/list.h>
56 #include <linux/mutex.h>
57 #include <linux/sched.h>
58 #include <linux/kthread.h>
59 #include <linux/freezer.h>
60 #include <linux/delay.h>
61
62 #include <linux/nvram.h>
63 #include <linux/proc_fs.h>
64 #include <linux/seq_file.h>
65 #include <linux/sysfs.h>
66 #include <linux/backlight.h>
67 #include <linux/fb.h>
68 #include <linux/platform_device.h>
69 #include <linux/hwmon.h>
70 #include <linux/hwmon-sysfs.h>
71 #include <linux/input.h>
72 #include <linux/leds.h>
73 #include <linux/rfkill.h>
74 #include <asm/uaccess.h>
75
76 #include <linux/dmi.h>
77 #include <linux/jiffies.h>
78 #include <linux/workqueue.h>
79
80 #include <sound/core.h>
81 #include <sound/control.h>
82 #include <sound/initval.h>
83
84 #include <acpi/acpi_drivers.h>
85
86 #include <linux/pci_ids.h>
87
88
89 /* ThinkPad CMOS commands */
90 #define TP_CMOS_VOLUME_DOWN     0
91 #define TP_CMOS_VOLUME_UP       1
92 #define TP_CMOS_VOLUME_MUTE     2
93 #define TP_CMOS_BRIGHTNESS_UP   4
94 #define TP_CMOS_BRIGHTNESS_DOWN 5
95 #define TP_CMOS_THINKLIGHT_ON   12
96 #define TP_CMOS_THINKLIGHT_OFF  13
97
98 /* NVRAM Addresses */
99 enum tp_nvram_addr {
100         TP_NVRAM_ADDR_HK2               = 0x57,
101         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
102         TP_NVRAM_ADDR_VIDEO             = 0x59,
103         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
104         TP_NVRAM_ADDR_MIXER             = 0x60,
105 };
106
107 /* NVRAM bit masks */
108 enum {
109         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
110         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
111         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
112         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
113         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
114         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
115         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
116         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
117         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
118         TP_NVRAM_MASK_MUTE              = 0x40,
119         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
120         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
121         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
122 };
123
124 /* ACPI HIDs */
125 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
126
127 /* Input IDs */
128 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
129 #define TPACPI_HKEY_INPUT_VERSION       0x4101
130
131 /* ACPI \WGSV commands */
132 enum {
133         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
134         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
135         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
136         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
137 };
138
139 /* TP_ACPI_WGSV_GET_STATE bits */
140 enum {
141         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
142         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
143         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
144         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
145         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
146         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
147         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
148         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
149         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
150         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
151 };
152
153 /* HKEY events */
154 enum tpacpi_hkey_event_t {
155         /* Hotkey-related */
156         TP_HKEY_EV_HOTKEY_BASE          = 0x1001, /* first hotkey (FN+F1) */
157         TP_HKEY_EV_BRGHT_UP             = 0x1010, /* Brightness up */
158         TP_HKEY_EV_BRGHT_DOWN           = 0x1011, /* Brightness down */
159         TP_HKEY_EV_VOL_UP               = 0x1015, /* Volume up or unmute */
160         TP_HKEY_EV_VOL_DOWN             = 0x1016, /* Volume down or unmute */
161         TP_HKEY_EV_VOL_MUTE             = 0x1017, /* Mixer output mute */
162
163         /* Reasons for waking up from S3/S4 */
164         TP_HKEY_EV_WKUP_S3_UNDOCK       = 0x2304, /* undock requested, S3 */
165         TP_HKEY_EV_WKUP_S4_UNDOCK       = 0x2404, /* undock requested, S4 */
166         TP_HKEY_EV_WKUP_S3_BAYEJ        = 0x2305, /* bay ejection req, S3 */
167         TP_HKEY_EV_WKUP_S4_BAYEJ        = 0x2405, /* bay ejection req, S4 */
168         TP_HKEY_EV_WKUP_S3_BATLOW       = 0x2313, /* battery empty, S3 */
169         TP_HKEY_EV_WKUP_S4_BATLOW       = 0x2413, /* battery empty, S4 */
170
171         /* Auto-sleep after eject request */
172         TP_HKEY_EV_BAYEJ_ACK            = 0x3003, /* bay ejection complete */
173         TP_HKEY_EV_UNDOCK_ACK           = 0x4003, /* undock complete */
174
175         /* Misc bay events */
176         TP_HKEY_EV_OPTDRV_EJ            = 0x3006, /* opt. drive tray ejected */
177
178         /* User-interface events */
179         TP_HKEY_EV_LID_CLOSE            = 0x5001, /* laptop lid closed */
180         TP_HKEY_EV_LID_OPEN             = 0x5002, /* laptop lid opened */
181         TP_HKEY_EV_TABLET_TABLET        = 0x5009, /* tablet swivel up */
182         TP_HKEY_EV_TABLET_NOTEBOOK      = 0x500a, /* tablet swivel down */
183         TP_HKEY_EV_PEN_INSERTED         = 0x500b, /* tablet pen inserted */
184         TP_HKEY_EV_PEN_REMOVED          = 0x500c, /* tablet pen removed */
185         TP_HKEY_EV_BRGHT_CHANGED        = 0x5010, /* backlight control event */
186
187         /* Thermal events */
188         TP_HKEY_EV_ALARM_BAT_HOT        = 0x6011, /* battery too hot */
189         TP_HKEY_EV_ALARM_BAT_XHOT       = 0x6012, /* battery critically hot */
190         TP_HKEY_EV_ALARM_SENSOR_HOT     = 0x6021, /* sensor too hot */
191         TP_HKEY_EV_ALARM_SENSOR_XHOT    = 0x6022, /* sensor critically hot */
192         TP_HKEY_EV_THM_TABLE_CHANGED    = 0x6030, /* thermal table changed */
193
194         /* Misc */
195         TP_HKEY_EV_RFKILL_CHANGED       = 0x7000, /* rfkill switch changed */
196 };
197
198 /****************************************************************************
199  * Main driver
200  */
201
202 #define TPACPI_NAME "thinkpad"
203 #define TPACPI_DESC "ThinkPad ACPI Extras"
204 #define TPACPI_FILE TPACPI_NAME "_acpi"
205 #define TPACPI_URL "http://ibm-acpi.sf.net/"
206 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
207
208 #define TPACPI_PROC_DIR "ibm"
209 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
210 #define TPACPI_DRVR_NAME TPACPI_FILE
211 #define TPACPI_DRVR_SHORTNAME "tpacpi"
212 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
213
214 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
215 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
216
217 #define TPACPI_MAX_ACPI_ARGS 3
218
219 /* printk headers */
220 #define TPACPI_LOG TPACPI_FILE ": "
221 #define TPACPI_EMERG    KERN_EMERG      TPACPI_LOG
222 #define TPACPI_ALERT    KERN_ALERT      TPACPI_LOG
223 #define TPACPI_CRIT     KERN_CRIT       TPACPI_LOG
224 #define TPACPI_ERR      KERN_ERR        TPACPI_LOG
225 #define TPACPI_WARN     KERN_WARNING    TPACPI_LOG
226 #define TPACPI_NOTICE   KERN_NOTICE     TPACPI_LOG
227 #define TPACPI_INFO     KERN_INFO       TPACPI_LOG
228 #define TPACPI_DEBUG    KERN_DEBUG      TPACPI_LOG
229
230 /* Debugging printk groups */
231 #define TPACPI_DBG_ALL          0xffff
232 #define TPACPI_DBG_DISCLOSETASK 0x8000
233 #define TPACPI_DBG_INIT         0x0001
234 #define TPACPI_DBG_EXIT         0x0002
235 #define TPACPI_DBG_RFKILL       0x0004
236 #define TPACPI_DBG_HKEY         0x0008
237 #define TPACPI_DBG_FAN          0x0010
238 #define TPACPI_DBG_BRGHT        0x0020
239 #define TPACPI_DBG_MIXER        0x0040
240
241 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off")
242 #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled")
243 #define strlencmp(a, b) (strncmp((a), (b), strlen(b)))
244
245
246 /****************************************************************************
247  * Driver-wide structs and misc. variables
248  */
249
250 struct ibm_struct;
251
252 struct tp_acpi_drv_struct {
253         const struct acpi_device_id *hid;
254         struct acpi_driver *driver;
255
256         void (*notify) (struct ibm_struct *, u32);
257         acpi_handle *handle;
258         u32 type;
259         struct acpi_device *device;
260 };
261
262 struct ibm_struct {
263         char *name;
264
265         int (*read) (struct seq_file *);
266         int (*write) (char *);
267         void (*exit) (void);
268         void (*resume) (void);
269         void (*suspend) (pm_message_t state);
270         void (*shutdown) (void);
271
272         struct list_head all_drivers;
273
274         struct tp_acpi_drv_struct *acpi;
275
276         struct {
277                 u8 acpi_driver_registered:1;
278                 u8 acpi_notify_installed:1;
279                 u8 proc_created:1;
280                 u8 init_called:1;
281                 u8 experimental:1;
282         } flags;
283 };
284
285 struct ibm_init_struct {
286         char param[32];
287
288         int (*init) (struct ibm_init_struct *);
289         struct ibm_struct *data;
290 };
291
292 static struct {
293         u32 bluetooth:1;
294         u32 hotkey:1;
295         u32 hotkey_mask:1;
296         u32 hotkey_wlsw:1;
297         u32 hotkey_tablet:1;
298         u32 light:1;
299         u32 light_status:1;
300         u32 bright_16levels:1;
301         u32 bright_acpimode:1;
302         u32 wan:1;
303         u32 uwb:1;
304         u32 fan_ctrl_status_undef:1;
305         u32 second_fan:1;
306         u32 beep_needs_two_args:1;
307         u32 mixer_no_level_control:1;
308         u32 input_device_registered:1;
309         u32 platform_drv_registered:1;
310         u32 platform_drv_attrs_registered:1;
311         u32 sensors_pdrv_registered:1;
312         u32 sensors_pdrv_attrs_registered:1;
313         u32 sensors_pdev_attrs_registered:1;
314         u32 hotkey_poll_active:1;
315 } tp_features;
316
317 static struct {
318         u16 hotkey_mask_ff:1;
319         u16 volume_ctrl_forbidden:1;
320 } tp_warned;
321
322 struct thinkpad_id_data {
323         unsigned int vendor;    /* ThinkPad vendor:
324                                  * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */
325
326         char *bios_version_str; /* Something like 1ZET51WW (1.03z) */
327         char *ec_version_str;   /* Something like 1ZHT51WW-1.04a */
328
329         u16 bios_model;         /* 1Y = 0x5931, 0 = unknown */
330         u16 ec_model;
331         u16 bios_release;       /* 1ZETK1WW = 0x314b, 0 = unknown */
332         u16 ec_release;
333
334         char *model_str;        /* ThinkPad T43 */
335         char *nummodel_str;     /* 9384A9C for a 9384-A9C model */
336 };
337 static struct thinkpad_id_data thinkpad_id;
338
339 static enum {
340         TPACPI_LIFE_INIT = 0,
341         TPACPI_LIFE_RUNNING,
342         TPACPI_LIFE_EXITING,
343 } tpacpi_lifecycle;
344
345 static int experimental;
346 static u32 dbg_level;
347
348 static struct workqueue_struct *tpacpi_wq;
349
350 enum led_status_t {
351         TPACPI_LED_OFF = 0,
352         TPACPI_LED_ON,
353         TPACPI_LED_BLINK,
354 };
355
356 /* Special LED class that can defer work */
357 struct tpacpi_led_classdev {
358         struct led_classdev led_classdev;
359         struct work_struct work;
360         enum led_status_t new_state;
361         unsigned int led;
362 };
363
364 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
365 static int dbg_wlswemul;
366 static int tpacpi_wlsw_emulstate;
367 static int dbg_bluetoothemul;
368 static int tpacpi_bluetooth_emulstate;
369 static int dbg_wwanemul;
370 static int tpacpi_wwan_emulstate;
371 static int dbg_uwbemul;
372 static int tpacpi_uwb_emulstate;
373 #endif
374
375
376 /*************************************************************************
377  *  Debugging helpers
378  */
379
380 #define dbg_printk(a_dbg_level, format, arg...) \
381         do { if (dbg_level & (a_dbg_level)) \
382                 printk(TPACPI_DEBUG "%s: " format, __func__ , ## arg); \
383         } while (0)
384
385 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
386 #define vdbg_printk dbg_printk
387 static const char *str_supported(int is_supported);
388 #else
389 #define vdbg_printk(a_dbg_level, format, arg...) \
390         do { } while (0)
391 #endif
392
393 static void tpacpi_log_usertask(const char * const what)
394 {
395         printk(TPACPI_DEBUG "%s: access by process with PID %d\n",
396                 what, task_tgid_vnr(current));
397 }
398
399 #define tpacpi_disclose_usertask(what, format, arg...) \
400         do { \
401                 if (unlikely( \
402                     (dbg_level & TPACPI_DBG_DISCLOSETASK) && \
403                     (tpacpi_lifecycle == TPACPI_LIFE_RUNNING))) { \
404                         printk(TPACPI_DEBUG "%s: PID %d: " format, \
405                                 what, task_tgid_vnr(current), ## arg); \
406                 } \
407         } while (0)
408
409 /*
410  * Quirk handling helpers
411  *
412  * ThinkPad IDs and versions seen in the field so far
413  * are two-characters from the set [0-9A-Z], i.e. base 36.
414  *
415  * We use values well outside that range as specials.
416  */
417
418 #define TPACPI_MATCH_ANY                0xffffU
419 #define TPACPI_MATCH_UNKNOWN            0U
420
421 /* TPID('1', 'Y') == 0x5931 */
422 #define TPID(__c1, __c2) (((__c2) << 8) | (__c1))
423
424 #define TPACPI_Q_IBM(__id1, __id2, __quirk)     \
425         { .vendor = PCI_VENDOR_ID_IBM,          \
426           .bios = TPID(__id1, __id2),           \
427           .ec = TPACPI_MATCH_ANY,               \
428           .quirks = (__quirk) }
429
430 #define TPACPI_Q_LNV(__id1, __id2, __quirk)     \
431         { .vendor = PCI_VENDOR_ID_LENOVO,       \
432           .bios = TPID(__id1, __id2),           \
433           .ec = TPACPI_MATCH_ANY,               \
434           .quirks = (__quirk) }
435
436 #define TPACPI_QEC_LNV(__id1, __id2, __quirk)   \
437         { .vendor = PCI_VENDOR_ID_LENOVO,       \
438           .bios = TPACPI_MATCH_ANY,             \
439           .ec = TPID(__id1, __id2),             \
440           .quirks = (__quirk) }
441
442 struct tpacpi_quirk {
443         unsigned int vendor;
444         u16 bios;
445         u16 ec;
446         unsigned long quirks;
447 };
448
449 /**
450  * tpacpi_check_quirks() - search BIOS/EC version on a list
451  * @qlist:              array of &struct tpacpi_quirk
452  * @qlist_size:         number of elements in @qlist
453  *
454  * Iterates over a quirks list until one is found that matches the
455  * ThinkPad's vendor, BIOS and EC model.
456  *
457  * Returns 0 if nothing matches, otherwise returns the quirks field of
458  * the matching &struct tpacpi_quirk entry.
459  *
460  * The match criteria is: vendor, ec and bios much match.
461  */
462 static unsigned long __init tpacpi_check_quirks(
463                         const struct tpacpi_quirk *qlist,
464                         unsigned int qlist_size)
465 {
466         while (qlist_size) {
467                 if ((qlist->vendor == thinkpad_id.vendor ||
468                                 qlist->vendor == TPACPI_MATCH_ANY) &&
469                     (qlist->bios == thinkpad_id.bios_model ||
470                                 qlist->bios == TPACPI_MATCH_ANY) &&
471                     (qlist->ec == thinkpad_id.ec_model ||
472                                 qlist->ec == TPACPI_MATCH_ANY))
473                         return qlist->quirks;
474
475                 qlist_size--;
476                 qlist++;
477         }
478         return 0;
479 }
480
481
482 /****************************************************************************
483  ****************************************************************************
484  *
485  * ACPI Helpers and device model
486  *
487  ****************************************************************************
488  ****************************************************************************/
489
490 /*************************************************************************
491  * ACPI basic handles
492  */
493
494 static acpi_handle root_handle;
495
496 #define TPACPI_HANDLE(object, parent, paths...)                 \
497         static acpi_handle  object##_handle;                    \
498         static acpi_handle *object##_parent = &parent##_handle; \
499         static char        *object##_path;                      \
500         static char        *object##_paths[] = { paths }
501
502 TPACPI_HANDLE(ec, root, "\\_SB.PCI0.ISA.EC0",   /* 240, 240x */
503            "\\_SB.PCI.ISA.EC",  /* 570 */
504            "\\_SB.PCI0.ISA0.EC0",       /* 600e/x, 770e, 770x */
505            "\\_SB.PCI0.ISA.EC", /* A21e, A2xm/p, T20-22, X20-21 */
506            "\\_SB.PCI0.AD4S.EC0",       /* i1400, R30 */
507            "\\_SB.PCI0.ICH3.EC0",       /* R31 */
508            "\\_SB.PCI0.LPC.EC", /* all others */
509            );
510
511 TPACPI_HANDLE(ecrd, ec, "ECRD");        /* 570 */
512 TPACPI_HANDLE(ecwr, ec, "ECWR");        /* 570 */
513
514 TPACPI_HANDLE(cmos, root, "\\UCMS",     /* R50, R50e, R50p, R51, */
515                                         /* T4x, X31, X40 */
516            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
517            "\\CMS",             /* R40, R40e */
518            );                   /* all others */
519
520 TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY",   /* 600e/x, 770e, 770x */
521            "^HKEY",             /* R30, R31 */
522            "HKEY",              /* all others */
523            );                   /* 570 */
524
525 TPACPI_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA",   /* 570 */
526            "\\_SB.PCI0.AGP0.VID0",      /* 600e/x, 770x */
527            "\\_SB.PCI0.VID0",   /* 770e */
528            "\\_SB.PCI0.VID",    /* A21e, G4x, R50e, X30, X40 */
529            "\\_SB.PCI0.AGP.VID",        /* all others */
530            );                           /* R30, R31 */
531
532
533 /*************************************************************************
534  * ACPI helpers
535  */
536
537 static int acpi_evalf(acpi_handle handle,
538                       void *res, char *method, char *fmt, ...)
539 {
540         char *fmt0 = fmt;
541         struct acpi_object_list params;
542         union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS];
543         struct acpi_buffer result, *resultp;
544         union acpi_object out_obj;
545         acpi_status status;
546         va_list ap;
547         char res_type;
548         int success;
549         int quiet;
550
551         if (!*fmt) {
552                 printk(TPACPI_ERR "acpi_evalf() called with empty format\n");
553                 return 0;
554         }
555
556         if (*fmt == 'q') {
557                 quiet = 1;
558                 fmt++;
559         } else
560                 quiet = 0;
561
562         res_type = *(fmt++);
563
564         params.count = 0;
565         params.pointer = &in_objs[0];
566
567         va_start(ap, fmt);
568         while (*fmt) {
569                 char c = *(fmt++);
570                 switch (c) {
571                 case 'd':       /* int */
572                         in_objs[params.count].integer.value = va_arg(ap, int);
573                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
574                         break;
575                         /* add more types as needed */
576                 default:
577                         printk(TPACPI_ERR "acpi_evalf() called "
578                                "with invalid format character '%c'\n", c);
579                         return 0;
580                 }
581         }
582         va_end(ap);
583
584         if (res_type != 'v') {
585                 result.length = sizeof(out_obj);
586                 result.pointer = &out_obj;
587                 resultp = &result;
588         } else
589                 resultp = NULL;
590
591         status = acpi_evaluate_object(handle, method, &params, resultp);
592
593         switch (res_type) {
594         case 'd':               /* int */
595                 if (res)
596                         *(int *)res = out_obj.integer.value;
597                 success = status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER;
598                 break;
599         case 'v':               /* void */
600                 success = status == AE_OK;
601                 break;
602                 /* add more types as needed */
603         default:
604                 printk(TPACPI_ERR "acpi_evalf() called "
605                        "with invalid format character '%c'\n", res_type);
606                 return 0;
607         }
608
609         if (!success && !quiet)
610                 printk(TPACPI_ERR "acpi_evalf(%s, %s, ...) failed: %d\n",
611                        method, fmt0, status);
612
613         return success;
614 }
615
616 static int acpi_ec_read(int i, u8 *p)
617 {
618         int v;
619
620         if (ecrd_handle) {
621                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
622                         return 0;
623                 *p = v;
624         } else {
625                 if (ec_read(i, p) < 0)
626                         return 0;
627         }
628
629         return 1;
630 }
631
632 static int acpi_ec_write(int i, u8 v)
633 {
634         if (ecwr_handle) {
635                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
636                         return 0;
637         } else {
638                 if (ec_write(i, v) < 0)
639                         return 0;
640         }
641
642         return 1;
643 }
644
645 static int issue_thinkpad_cmos_command(int cmos_cmd)
646 {
647         if (!cmos_handle)
648                 return -ENXIO;
649
650         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
651                 return -EIO;
652
653         return 0;
654 }
655
656 /*************************************************************************
657  * ACPI device model
658  */
659
660 #define TPACPI_ACPIHANDLE_INIT(object) \
661         drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \
662                 object##_paths, ARRAY_SIZE(object##_paths), &object##_path)
663
664 static void drv_acpi_handle_init(char *name,
665                            acpi_handle *handle, acpi_handle parent,
666                            char **paths, int num_paths, char **path)
667 {
668         int i;
669         acpi_status status;
670
671         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
672                 name);
673
674         for (i = 0; i < num_paths; i++) {
675                 status = acpi_get_handle(parent, paths[i], handle);
676                 if (ACPI_SUCCESS(status)) {
677                         *path = paths[i];
678                         dbg_printk(TPACPI_DBG_INIT,
679                                    "Found ACPI handle %s for %s\n",
680                                    *path, name);
681                         return;
682                 }
683         }
684
685         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
686                     name);
687         *handle = NULL;
688 }
689
690 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
691 {
692         struct ibm_struct *ibm = data;
693
694         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
695                 return;
696
697         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
698                 return;
699
700         ibm->acpi->notify(ibm, event);
701 }
702
703 static int __init setup_acpi_notify(struct ibm_struct *ibm)
704 {
705         acpi_status status;
706         int rc;
707
708         BUG_ON(!ibm->acpi);
709
710         if (!*ibm->acpi->handle)
711                 return 0;
712
713         vdbg_printk(TPACPI_DBG_INIT,
714                 "setting up ACPI notify for %s\n", ibm->name);
715
716         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
717         if (rc < 0) {
718                 printk(TPACPI_ERR "acpi_bus_get_device(%s) failed: %d\n",
719                         ibm->name, rc);
720                 return -ENODEV;
721         }
722
723         ibm->acpi->device->driver_data = ibm;
724         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
725                 TPACPI_ACPI_EVENT_PREFIX,
726                 ibm->name);
727
728         status = acpi_install_notify_handler(*ibm->acpi->handle,
729                         ibm->acpi->type, dispatch_acpi_notify, ibm);
730         if (ACPI_FAILURE(status)) {
731                 if (status == AE_ALREADY_EXISTS) {
732                         printk(TPACPI_NOTICE
733                                "another device driver is already "
734                                "handling %s events\n", ibm->name);
735                 } else {
736                         printk(TPACPI_ERR
737                                "acpi_install_notify_handler(%s) failed: %d\n",
738                                ibm->name, status);
739                 }
740                 return -ENODEV;
741         }
742         ibm->flags.acpi_notify_installed = 1;
743         return 0;
744 }
745
746 static int __init tpacpi_device_add(struct acpi_device *device)
747 {
748         return 0;
749 }
750
751 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
752 {
753         int rc;
754
755         dbg_printk(TPACPI_DBG_INIT,
756                 "registering %s as an ACPI driver\n", ibm->name);
757
758         BUG_ON(!ibm->acpi);
759
760         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
761         if (!ibm->acpi->driver) {
762                 printk(TPACPI_ERR
763                        "failed to allocate memory for ibm->acpi->driver\n");
764                 return -ENOMEM;
765         }
766
767         sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name);
768         ibm->acpi->driver->ids = ibm->acpi->hid;
769
770         ibm->acpi->driver->ops.add = &tpacpi_device_add;
771
772         rc = acpi_bus_register_driver(ibm->acpi->driver);
773         if (rc < 0) {
774                 printk(TPACPI_ERR "acpi_bus_register_driver(%s) failed: %d\n",
775                        ibm->name, rc);
776                 kfree(ibm->acpi->driver);
777                 ibm->acpi->driver = NULL;
778         } else if (!rc)
779                 ibm->flags.acpi_driver_registered = 1;
780
781         return rc;
782 }
783
784
785 /****************************************************************************
786  ****************************************************************************
787  *
788  * Procfs Helpers
789  *
790  ****************************************************************************
791  ****************************************************************************/
792
793 static int dispatch_proc_show(struct seq_file *m, void *v)
794 {
795         struct ibm_struct *ibm = m->private;
796
797         if (!ibm || !ibm->read)
798                 return -EINVAL;
799         return ibm->read(m);
800 }
801
802 static int dispatch_proc_open(struct inode *inode, struct file *file)
803 {
804         return single_open(file, dispatch_proc_show, PDE(inode)->data);
805 }
806
807 static ssize_t dispatch_proc_write(struct file *file,
808                         const char __user *userbuf,
809                         size_t count, loff_t *pos)
810 {
811         struct ibm_struct *ibm = PDE(file->f_path.dentry->d_inode)->data;
812         char *kernbuf;
813         int ret;
814
815         if (!ibm || !ibm->write)
816                 return -EINVAL;
817         if (count > PAGE_SIZE - 2)
818                 return -EINVAL;
819
820         kernbuf = kmalloc(count + 2, GFP_KERNEL);
821         if (!kernbuf)
822                 return -ENOMEM;
823
824         if (copy_from_user(kernbuf, userbuf, count)) {
825                 kfree(kernbuf);
826                 return -EFAULT;
827         }
828
829         kernbuf[count] = 0;
830         strcat(kernbuf, ",");
831         ret = ibm->write(kernbuf);
832         if (ret == 0)
833                 ret = count;
834
835         kfree(kernbuf);
836
837         return ret;
838 }
839
840 static const struct file_operations dispatch_proc_fops = {
841         .owner          = THIS_MODULE,
842         .open           = dispatch_proc_open,
843         .read           = seq_read,
844         .llseek         = seq_lseek,
845         .release        = single_release,
846         .write          = dispatch_proc_write,
847 };
848
849 static char *next_cmd(char **cmds)
850 {
851         char *start = *cmds;
852         char *end;
853
854         while ((end = strchr(start, ',')) && end == start)
855                 start = end + 1;
856
857         if (!end)
858                 return NULL;
859
860         *end = 0;
861         *cmds = end + 1;
862         return start;
863 }
864
865
866 /****************************************************************************
867  ****************************************************************************
868  *
869  * Device model: input, hwmon and platform
870  *
871  ****************************************************************************
872  ****************************************************************************/
873
874 static struct platform_device *tpacpi_pdev;
875 static struct platform_device *tpacpi_sensors_pdev;
876 static struct device *tpacpi_hwmon;
877 static struct input_dev *tpacpi_inputdev;
878 static struct mutex tpacpi_inputdev_send_mutex;
879 static LIST_HEAD(tpacpi_all_drivers);
880
881 static int tpacpi_suspend_handler(struct platform_device *pdev,
882                                   pm_message_t state)
883 {
884         struct ibm_struct *ibm, *itmp;
885
886         list_for_each_entry_safe(ibm, itmp,
887                                  &tpacpi_all_drivers,
888                                  all_drivers) {
889                 if (ibm->suspend)
890                         (ibm->suspend)(state);
891         }
892
893         return 0;
894 }
895
896 static int tpacpi_resume_handler(struct platform_device *pdev)
897 {
898         struct ibm_struct *ibm, *itmp;
899
900         list_for_each_entry_safe(ibm, itmp,
901                                  &tpacpi_all_drivers,
902                                  all_drivers) {
903                 if (ibm->resume)
904                         (ibm->resume)();
905         }
906
907         return 0;
908 }
909
910 static void tpacpi_shutdown_handler(struct platform_device *pdev)
911 {
912         struct ibm_struct *ibm, *itmp;
913
914         list_for_each_entry_safe(ibm, itmp,
915                                  &tpacpi_all_drivers,
916                                  all_drivers) {
917                 if (ibm->shutdown)
918                         (ibm->shutdown)();
919         }
920 }
921
922 static struct platform_driver tpacpi_pdriver = {
923         .driver = {
924                 .name = TPACPI_DRVR_NAME,
925                 .owner = THIS_MODULE,
926         },
927         .suspend = tpacpi_suspend_handler,
928         .resume = tpacpi_resume_handler,
929         .shutdown = tpacpi_shutdown_handler,
930 };
931
932 static struct platform_driver tpacpi_hwmon_pdriver = {
933         .driver = {
934                 .name = TPACPI_HWMON_DRVR_NAME,
935                 .owner = THIS_MODULE,
936         },
937 };
938
939 /*************************************************************************
940  * sysfs support helpers
941  */
942
943 struct attribute_set {
944         unsigned int members, max_members;
945         struct attribute_group group;
946 };
947
948 struct attribute_set_obj {
949         struct attribute_set s;
950         struct attribute *a;
951 } __attribute__((packed));
952
953 static struct attribute_set *create_attr_set(unsigned int max_members,
954                                                 const char *name)
955 {
956         struct attribute_set_obj *sobj;
957
958         if (max_members == 0)
959                 return NULL;
960
961         /* Allocates space for implicit NULL at the end too */
962         sobj = kzalloc(sizeof(struct attribute_set_obj) +
963                     max_members * sizeof(struct attribute *),
964                     GFP_KERNEL);
965         if (!sobj)
966                 return NULL;
967         sobj->s.max_members = max_members;
968         sobj->s.group.attrs = &sobj->a;
969         sobj->s.group.name = name;
970
971         return &sobj->s;
972 }
973
974 #define destroy_attr_set(_set) \
975         kfree(_set);
976
977 /* not multi-threaded safe, use it in a single thread per set */
978 static int add_to_attr_set(struct attribute_set *s, struct attribute *attr)
979 {
980         if (!s || !attr)
981                 return -EINVAL;
982
983         if (s->members >= s->max_members)
984                 return -ENOMEM;
985
986         s->group.attrs[s->members] = attr;
987         s->members++;
988
989         return 0;
990 }
991
992 static int add_many_to_attr_set(struct attribute_set *s,
993                         struct attribute **attr,
994                         unsigned int count)
995 {
996         int i, res;
997
998         for (i = 0; i < count; i++) {
999                 res = add_to_attr_set(s, attr[i]);
1000                 if (res)
1001                         return res;
1002         }
1003
1004         return 0;
1005 }
1006
1007 static void delete_attr_set(struct attribute_set *s, struct kobject *kobj)
1008 {
1009         sysfs_remove_group(kobj, &s->group);
1010         destroy_attr_set(s);
1011 }
1012
1013 #define register_attr_set_with_sysfs(_attr_set, _kobj) \
1014         sysfs_create_group(_kobj, &_attr_set->group)
1015
1016 static int parse_strtoul(const char *buf,
1017                 unsigned long max, unsigned long *value)
1018 {
1019         char *endp;
1020
1021         *value = simple_strtoul(skip_spaces(buf), &endp, 0);
1022         endp = skip_spaces(endp);
1023         if (*endp || *value > max)
1024                 return -EINVAL;
1025
1026         return 0;
1027 }
1028
1029 static void tpacpi_disable_brightness_delay(void)
1030 {
1031         if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0))
1032                 printk(TPACPI_NOTICE
1033                         "ACPI backlight control delay disabled\n");
1034 }
1035
1036 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
1037 {
1038         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
1039         union acpi_object *obj;
1040         int rc;
1041
1042         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
1043                 obj = (union acpi_object *)buffer.pointer;
1044                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
1045                         printk(TPACPI_ERR "Unknown _BCL data, "
1046                                "please report this to %s\n", TPACPI_MAIL);
1047                         rc = 0;
1048                 } else {
1049                         rc = obj->package.count;
1050                 }
1051         } else {
1052                 return 0;
1053         }
1054
1055         kfree(buffer.pointer);
1056         return rc;
1057 }
1058
1059 static acpi_status __init tpacpi_acpi_walk_find_bcl(acpi_handle handle,
1060                                         u32 lvl, void *context, void **rv)
1061 {
1062         char name[ACPI_PATH_SEGMENT_LENGTH];
1063         struct acpi_buffer buffer = { sizeof(name), &name };
1064
1065         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
1066             !strncmp("_BCL", name, sizeof(name) - 1)) {
1067                 BUG_ON(!rv || !*rv);
1068                 **(int **)rv = tpacpi_query_bcl_levels(handle);
1069                 return AE_CTRL_TERMINATE;
1070         } else {
1071                 return AE_OK;
1072         }
1073 }
1074
1075 /*
1076  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
1077  */
1078 static int __init tpacpi_check_std_acpi_brightness_support(void)
1079 {
1080         int status;
1081         int bcl_levels = 0;
1082         void *bcl_ptr = &bcl_levels;
1083
1084         if (!vid_handle) {
1085                 TPACPI_ACPIHANDLE_INIT(vid);
1086         }
1087         if (!vid_handle)
1088                 return 0;
1089
1090         /*
1091          * Search for a _BCL method, and execute it.  This is safe on all
1092          * ThinkPads, and as a side-effect, _BCL will place a Lenovo Vista
1093          * BIOS in ACPI backlight control mode.  We do NOT have to care
1094          * about calling the _BCL method in an enabled video device, any
1095          * will do for our purposes.
1096          */
1097
1098         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
1099                                      tpacpi_acpi_walk_find_bcl, NULL, NULL,
1100                                      &bcl_ptr);
1101
1102         if (ACPI_SUCCESS(status) && bcl_levels > 2) {
1103                 tp_features.bright_acpimode = 1;
1104                 return (bcl_levels - 2);
1105         }
1106
1107         return 0;
1108 }
1109
1110 static void printk_deprecated_attribute(const char * const what,
1111                                         const char * const details)
1112 {
1113         tpacpi_log_usertask("deprecated sysfs attribute");
1114         printk(TPACPI_WARN "WARNING: sysfs attribute %s is deprecated and "
1115                 "will be removed. %s\n",
1116                 what, details);
1117 }
1118
1119 /*************************************************************************
1120  * rfkill and radio control support helpers
1121  */
1122
1123 /*
1124  * ThinkPad-ACPI firmware handling model:
1125  *
1126  * WLSW (master wireless switch) is event-driven, and is common to all
1127  * firmware-controlled radios.  It cannot be controlled, just monitored,
1128  * as expected.  It overrides all radio state in firmware
1129  *
1130  * The kernel, a masked-off hotkey, and WLSW can change the radio state
1131  * (TODO: verify how WLSW interacts with the returned radio state).
1132  *
1133  * The only time there are shadow radio state changes, is when
1134  * masked-off hotkeys are used.
1135  */
1136
1137 /*
1138  * Internal driver API for radio state:
1139  *
1140  * int: < 0 = error, otherwise enum tpacpi_rfkill_state
1141  * bool: true means radio blocked (off)
1142  */
1143 enum tpacpi_rfkill_state {
1144         TPACPI_RFK_RADIO_OFF = 0,
1145         TPACPI_RFK_RADIO_ON
1146 };
1147
1148 /* rfkill switches */
1149 enum tpacpi_rfk_id {
1150         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
1151         TPACPI_RFK_WWAN_SW_ID,
1152         TPACPI_RFK_UWB_SW_ID,
1153         TPACPI_RFK_SW_MAX
1154 };
1155
1156 static const char *tpacpi_rfkill_names[] = {
1157         [TPACPI_RFK_BLUETOOTH_SW_ID] = "bluetooth",
1158         [TPACPI_RFK_WWAN_SW_ID] = "wwan",
1159         [TPACPI_RFK_UWB_SW_ID] = "uwb",
1160         [TPACPI_RFK_SW_MAX] = NULL
1161 };
1162
1163 /* ThinkPad-ACPI rfkill subdriver */
1164 struct tpacpi_rfk {
1165         struct rfkill *rfkill;
1166         enum tpacpi_rfk_id id;
1167         const struct tpacpi_rfk_ops *ops;
1168 };
1169
1170 struct tpacpi_rfk_ops {
1171         /* firmware interface */
1172         int (*get_status)(void);
1173         int (*set_status)(const enum tpacpi_rfkill_state);
1174 };
1175
1176 static struct tpacpi_rfk *tpacpi_rfkill_switches[TPACPI_RFK_SW_MAX];
1177
1178 /* Query FW and update rfkill sw state for a given rfkill switch */
1179 static int tpacpi_rfk_update_swstate(const struct tpacpi_rfk *tp_rfk)
1180 {
1181         int status;
1182
1183         if (!tp_rfk)
1184                 return -ENODEV;
1185
1186         status = (tp_rfk->ops->get_status)();
1187         if (status < 0)
1188                 return status;
1189
1190         rfkill_set_sw_state(tp_rfk->rfkill,
1191                             (status == TPACPI_RFK_RADIO_OFF));
1192
1193         return status;
1194 }
1195
1196 /* Query FW and update rfkill sw state for all rfkill switches */
1197 static void tpacpi_rfk_update_swstate_all(void)
1198 {
1199         unsigned int i;
1200
1201         for (i = 0; i < TPACPI_RFK_SW_MAX; i++)
1202                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[i]);
1203 }
1204
1205 /*
1206  * Sync the HW-blocking state of all rfkill switches,
1207  * do notice it causes the rfkill core to schedule uevents
1208  */
1209 static void tpacpi_rfk_update_hwblock_state(bool blocked)
1210 {
1211         unsigned int i;
1212         struct tpacpi_rfk *tp_rfk;
1213
1214         for (i = 0; i < TPACPI_RFK_SW_MAX; i++) {
1215                 tp_rfk = tpacpi_rfkill_switches[i];
1216                 if (tp_rfk) {
1217                         if (rfkill_set_hw_state(tp_rfk->rfkill,
1218                                                 blocked)) {
1219                                 /* ignore -- we track sw block */
1220                         }
1221                 }
1222         }
1223 }
1224
1225 /* Call to get the WLSW state from the firmware */
1226 static int hotkey_get_wlsw(void);
1227
1228 /* Call to query WLSW state and update all rfkill switches */
1229 static bool tpacpi_rfk_check_hwblock_state(void)
1230 {
1231         int res = hotkey_get_wlsw();
1232         int hw_blocked;
1233
1234         /* When unknown or unsupported, we have to assume it is unblocked */
1235         if (res < 0)
1236                 return false;
1237
1238         hw_blocked = (res == TPACPI_RFK_RADIO_OFF);
1239         tpacpi_rfk_update_hwblock_state(hw_blocked);
1240
1241         return hw_blocked;
1242 }
1243
1244 static int tpacpi_rfk_hook_set_block(void *data, bool blocked)
1245 {
1246         struct tpacpi_rfk *tp_rfk = data;
1247         int res;
1248
1249         dbg_printk(TPACPI_DBG_RFKILL,
1250                    "request to change radio state to %s\n",
1251                    blocked ? "blocked" : "unblocked");
1252
1253         /* try to set radio state */
1254         res = (tp_rfk->ops->set_status)(blocked ?
1255                                 TPACPI_RFK_RADIO_OFF : TPACPI_RFK_RADIO_ON);
1256
1257         /* and update the rfkill core with whatever the FW really did */
1258         tpacpi_rfk_update_swstate(tp_rfk);
1259
1260         return (res < 0) ? res : 0;
1261 }
1262
1263 static const struct rfkill_ops tpacpi_rfk_rfkill_ops = {
1264         .set_block = tpacpi_rfk_hook_set_block,
1265 };
1266
1267 static int __init tpacpi_new_rfkill(const enum tpacpi_rfk_id id,
1268                         const struct tpacpi_rfk_ops *tp_rfkops,
1269                         const enum rfkill_type rfktype,
1270                         const char *name,
1271                         const bool set_default)
1272 {
1273         struct tpacpi_rfk *atp_rfk;
1274         int res;
1275         bool sw_state = false;
1276         bool hw_state;
1277         int sw_status;
1278
1279         BUG_ON(id >= TPACPI_RFK_SW_MAX || tpacpi_rfkill_switches[id]);
1280
1281         atp_rfk = kzalloc(sizeof(struct tpacpi_rfk), GFP_KERNEL);
1282         if (atp_rfk)
1283                 atp_rfk->rfkill = rfkill_alloc(name,
1284                                                 &tpacpi_pdev->dev,
1285                                                 rfktype,
1286                                                 &tpacpi_rfk_rfkill_ops,
1287                                                 atp_rfk);
1288         if (!atp_rfk || !atp_rfk->rfkill) {
1289                 printk(TPACPI_ERR
1290                         "failed to allocate memory for rfkill class\n");
1291                 kfree(atp_rfk);
1292                 return -ENOMEM;
1293         }
1294
1295         atp_rfk->id = id;
1296         atp_rfk->ops = tp_rfkops;
1297
1298         sw_status = (tp_rfkops->get_status)();
1299         if (sw_status < 0) {
1300                 printk(TPACPI_ERR
1301                         "failed to read initial state for %s, error %d\n",
1302                         name, sw_status);
1303         } else {
1304                 sw_state = (sw_status == TPACPI_RFK_RADIO_OFF);
1305                 if (set_default) {
1306                         /* try to keep the initial state, since we ask the
1307                          * firmware to preserve it across S5 in NVRAM */
1308                         rfkill_init_sw_state(atp_rfk->rfkill, sw_state);
1309                 }
1310         }
1311         hw_state = tpacpi_rfk_check_hwblock_state();
1312         rfkill_set_hw_state(atp_rfk->rfkill, hw_state);
1313
1314         res = rfkill_register(atp_rfk->rfkill);
1315         if (res < 0) {
1316                 printk(TPACPI_ERR
1317                         "failed to register %s rfkill switch: %d\n",
1318                         name, res);
1319                 rfkill_destroy(atp_rfk->rfkill);
1320                 kfree(atp_rfk);
1321                 return res;
1322         }
1323
1324         tpacpi_rfkill_switches[id] = atp_rfk;
1325
1326         printk(TPACPI_INFO "rfkill switch %s: radio is %sblocked\n",
1327                 name, (sw_state || hw_state) ? "" : "un");
1328         return 0;
1329 }
1330
1331 static void tpacpi_destroy_rfkill(const enum tpacpi_rfk_id id)
1332 {
1333         struct tpacpi_rfk *tp_rfk;
1334
1335         BUG_ON(id >= TPACPI_RFK_SW_MAX);
1336
1337         tp_rfk = tpacpi_rfkill_switches[id];
1338         if (tp_rfk) {
1339                 rfkill_unregister(tp_rfk->rfkill);
1340                 rfkill_destroy(tp_rfk->rfkill);
1341                 tpacpi_rfkill_switches[id] = NULL;
1342                 kfree(tp_rfk);
1343         }
1344 }
1345
1346 static void printk_deprecated_rfkill_attribute(const char * const what)
1347 {
1348         printk_deprecated_attribute(what,
1349                         "Please switch to generic rfkill before year 2010");
1350 }
1351
1352 /* sysfs <radio> enable ------------------------------------------------ */
1353 static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id,
1354                                             struct device_attribute *attr,
1355                                             char *buf)
1356 {
1357         int status;
1358
1359         printk_deprecated_rfkill_attribute(attr->attr.name);
1360
1361         /* This is in the ABI... */
1362         if (tpacpi_rfk_check_hwblock_state()) {
1363                 status = TPACPI_RFK_RADIO_OFF;
1364         } else {
1365                 status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1366                 if (status < 0)
1367                         return status;
1368         }
1369
1370         return snprintf(buf, PAGE_SIZE, "%d\n",
1371                         (status == TPACPI_RFK_RADIO_ON) ? 1 : 0);
1372 }
1373
1374 static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id,
1375                             struct device_attribute *attr,
1376                             const char *buf, size_t count)
1377 {
1378         unsigned long t;
1379         int res;
1380
1381         printk_deprecated_rfkill_attribute(attr->attr.name);
1382
1383         if (parse_strtoul(buf, 1, &t))
1384                 return -EINVAL;
1385
1386         tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t);
1387
1388         /* This is in the ABI... */
1389         if (tpacpi_rfk_check_hwblock_state() && !!t)
1390                 return -EPERM;
1391
1392         res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ?
1393                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF);
1394         tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1395
1396         return (res < 0) ? res : count;
1397 }
1398
1399 /* procfs -------------------------------------------------------------- */
1400 static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, struct seq_file *m)
1401 {
1402         if (id >= TPACPI_RFK_SW_MAX)
1403                 seq_printf(m, "status:\t\tnot supported\n");
1404         else {
1405                 int status;
1406
1407                 /* This is in the ABI... */
1408                 if (tpacpi_rfk_check_hwblock_state()) {
1409                         status = TPACPI_RFK_RADIO_OFF;
1410                 } else {
1411                         status = tpacpi_rfk_update_swstate(
1412                                                 tpacpi_rfkill_switches[id]);
1413                         if (status < 0)
1414                                 return status;
1415                 }
1416
1417                 seq_printf(m, "status:\t\t%s\n",
1418                                 (status == TPACPI_RFK_RADIO_ON) ?
1419                                         "enabled" : "disabled");
1420                 seq_printf(m, "commands:\tenable, disable\n");
1421         }
1422
1423         return 0;
1424 }
1425
1426 static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf)
1427 {
1428         char *cmd;
1429         int status = -1;
1430         int res = 0;
1431
1432         if (id >= TPACPI_RFK_SW_MAX)
1433                 return -ENODEV;
1434
1435         while ((cmd = next_cmd(&buf))) {
1436                 if (strlencmp(cmd, "enable") == 0)
1437                         status = TPACPI_RFK_RADIO_ON;
1438                 else if (strlencmp(cmd, "disable") == 0)
1439                         status = TPACPI_RFK_RADIO_OFF;
1440                 else
1441                         return -EINVAL;
1442         }
1443
1444         if (status != -1) {
1445                 tpacpi_disclose_usertask("procfs", "attempt to %s %s\n",
1446                                 (status == TPACPI_RFK_RADIO_ON) ?
1447                                                 "enable" : "disable",
1448                                 tpacpi_rfkill_names[id]);
1449                 res = (tpacpi_rfkill_switches[id]->ops->set_status)(status);
1450                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1451         }
1452
1453         return res;
1454 }
1455
1456 /*************************************************************************
1457  * thinkpad-acpi driver attributes
1458  */
1459
1460 /* interface_version --------------------------------------------------- */
1461 static ssize_t tpacpi_driver_interface_version_show(
1462                                 struct device_driver *drv,
1463                                 char *buf)
1464 {
1465         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
1466 }
1467
1468 static DRIVER_ATTR(interface_version, S_IRUGO,
1469                 tpacpi_driver_interface_version_show, NULL);
1470
1471 /* debug_level --------------------------------------------------------- */
1472 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
1473                                                 char *buf)
1474 {
1475         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
1476 }
1477
1478 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
1479                                                 const char *buf, size_t count)
1480 {
1481         unsigned long t;
1482
1483         if (parse_strtoul(buf, 0xffff, &t))
1484                 return -EINVAL;
1485
1486         dbg_level = t;
1487
1488         return count;
1489 }
1490
1491 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1492                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
1493
1494 /* version ------------------------------------------------------------- */
1495 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
1496                                                 char *buf)
1497 {
1498         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1499                         TPACPI_DESC, TPACPI_VERSION);
1500 }
1501
1502 static DRIVER_ATTR(version, S_IRUGO,
1503                 tpacpi_driver_version_show, NULL);
1504
1505 /* --------------------------------------------------------------------- */
1506
1507 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1508
1509 /* wlsw_emulstate ------------------------------------------------------ */
1510 static ssize_t tpacpi_driver_wlsw_emulstate_show(struct device_driver *drv,
1511                                                 char *buf)
1512 {
1513         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate);
1514 }
1515
1516 static ssize_t tpacpi_driver_wlsw_emulstate_store(struct device_driver *drv,
1517                                                 const char *buf, size_t count)
1518 {
1519         unsigned long t;
1520
1521         if (parse_strtoul(buf, 1, &t))
1522                 return -EINVAL;
1523
1524         if (tpacpi_wlsw_emulstate != !!t) {
1525                 tpacpi_wlsw_emulstate = !!t;
1526                 tpacpi_rfk_update_hwblock_state(!t);    /* negative logic */
1527         }
1528
1529         return count;
1530 }
1531
1532 static DRIVER_ATTR(wlsw_emulstate, S_IWUSR | S_IRUGO,
1533                 tpacpi_driver_wlsw_emulstate_show,
1534                 tpacpi_driver_wlsw_emulstate_store);
1535
1536 /* bluetooth_emulstate ------------------------------------------------- */
1537 static ssize_t tpacpi_driver_bluetooth_emulstate_show(
1538                                         struct device_driver *drv,
1539                                         char *buf)
1540 {
1541         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate);
1542 }
1543
1544 static ssize_t tpacpi_driver_bluetooth_emulstate_store(
1545                                         struct device_driver *drv,
1546                                         const char *buf, size_t count)
1547 {
1548         unsigned long t;
1549
1550         if (parse_strtoul(buf, 1, &t))
1551                 return -EINVAL;
1552
1553         tpacpi_bluetooth_emulstate = !!t;
1554
1555         return count;
1556 }
1557
1558 static DRIVER_ATTR(bluetooth_emulstate, S_IWUSR | S_IRUGO,
1559                 tpacpi_driver_bluetooth_emulstate_show,
1560                 tpacpi_driver_bluetooth_emulstate_store);
1561
1562 /* wwan_emulstate ------------------------------------------------- */
1563 static ssize_t tpacpi_driver_wwan_emulstate_show(
1564                                         struct device_driver *drv,
1565                                         char *buf)
1566 {
1567         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate);
1568 }
1569
1570 static ssize_t tpacpi_driver_wwan_emulstate_store(
1571                                         struct device_driver *drv,
1572                                         const char *buf, size_t count)
1573 {
1574         unsigned long t;
1575
1576         if (parse_strtoul(buf, 1, &t))
1577                 return -EINVAL;
1578
1579         tpacpi_wwan_emulstate = !!t;
1580
1581         return count;
1582 }
1583
1584 static DRIVER_ATTR(wwan_emulstate, S_IWUSR | S_IRUGO,
1585                 tpacpi_driver_wwan_emulstate_show,
1586                 tpacpi_driver_wwan_emulstate_store);
1587
1588 /* uwb_emulstate ------------------------------------------------- */
1589 static ssize_t tpacpi_driver_uwb_emulstate_show(
1590                                         struct device_driver *drv,
1591                                         char *buf)
1592 {
1593         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate);
1594 }
1595
1596 static ssize_t tpacpi_driver_uwb_emulstate_store(
1597                                         struct device_driver *drv,
1598                                         const char *buf, size_t count)
1599 {
1600         unsigned long t;
1601
1602         if (parse_strtoul(buf, 1, &t))
1603                 return -EINVAL;
1604
1605         tpacpi_uwb_emulstate = !!t;
1606
1607         return count;
1608 }
1609
1610 static DRIVER_ATTR(uwb_emulstate, S_IWUSR | S_IRUGO,
1611                 tpacpi_driver_uwb_emulstate_show,
1612                 tpacpi_driver_uwb_emulstate_store);
1613 #endif
1614
1615 /* --------------------------------------------------------------------- */
1616
1617 static struct driver_attribute *tpacpi_driver_attributes[] = {
1618         &driver_attr_debug_level, &driver_attr_version,
1619         &driver_attr_interface_version,
1620 };
1621
1622 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1623 {
1624         int i, res;
1625
1626         i = 0;
1627         res = 0;
1628         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1629                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1630                 i++;
1631         }
1632
1633 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1634         if (!res && dbg_wlswemul)
1635                 res = driver_create_file(drv, &driver_attr_wlsw_emulstate);
1636         if (!res && dbg_bluetoothemul)
1637                 res = driver_create_file(drv, &driver_attr_bluetooth_emulstate);
1638         if (!res && dbg_wwanemul)
1639                 res = driver_create_file(drv, &driver_attr_wwan_emulstate);
1640         if (!res && dbg_uwbemul)
1641                 res = driver_create_file(drv, &driver_attr_uwb_emulstate);
1642 #endif
1643
1644         return res;
1645 }
1646
1647 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1648 {
1649         int i;
1650
1651         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1652                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1653
1654 #ifdef THINKPAD_ACPI_DEBUGFACILITIES
1655         driver_remove_file(drv, &driver_attr_wlsw_emulstate);
1656         driver_remove_file(drv, &driver_attr_bluetooth_emulstate);
1657         driver_remove_file(drv, &driver_attr_wwan_emulstate);
1658         driver_remove_file(drv, &driver_attr_uwb_emulstate);
1659 #endif
1660 }
1661
1662 /*************************************************************************
1663  * Firmware Data
1664  */
1665
1666 /*
1667  * Table of recommended minimum BIOS versions
1668  *
1669  * Reasons for listing:
1670  *    1. Stable BIOS, listed because the unknown ammount of
1671  *       bugs and bad ACPI behaviour on older versions
1672  *
1673  *    2. BIOS or EC fw with known bugs that trigger on Linux
1674  *
1675  *    3. BIOS with known reduced functionality in older versions
1676  *
1677  *  We recommend the latest BIOS and EC version.
1678  *  We only support the latest BIOS and EC fw version as a rule.
1679  *
1680  *  Sources: IBM ThinkPad Public Web Documents (update changelogs),
1681  *  Information from users in ThinkWiki
1682  *
1683  *  WARNING: we use this table also to detect that the machine is
1684  *  a ThinkPad in some cases, so don't remove entries lightly.
1685  */
1686
1687 #define TPV_Q(__v, __id1, __id2, __bv1, __bv2)          \
1688         { .vendor       = (__v),                        \
1689           .bios         = TPID(__id1, __id2),           \
1690           .ec           = TPACPI_MATCH_ANY,             \
1691           .quirks       = TPACPI_MATCH_ANY << 16        \
1692                           | (__bv1) << 8 | (__bv2) }
1693
1694 #define TPV_Q_X(__v, __bid1, __bid2, __bv1, __bv2,      \
1695                 __eid, __ev1, __ev2)                    \
1696         { .vendor       = (__v),                        \
1697           .bios         = TPID(__bid1, __bid2),         \
1698           .ec           = __eid,                        \
1699           .quirks       = (__ev1) << 24 | (__ev2) << 16 \
1700                           | (__bv1) << 8 | (__bv2) }
1701
1702 #define TPV_QI0(__id1, __id2, __bv1, __bv2) \
1703         TPV_Q(PCI_VENDOR_ID_IBM, __id1, __id2, __bv1, __bv2)
1704
1705 /* Outdated IBM BIOSes often lack the EC id string */
1706 #define TPV_QI1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1707         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1708                 __bv1, __bv2, TPID(__id1, __id2),       \
1709                 __ev1, __ev2),                          \
1710         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1711                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1712                 __ev1, __ev2)
1713
1714 /* Outdated IBM BIOSes often lack the EC id string */
1715 #define TPV_QI2(__bid1, __bid2, __bv1, __bv2,           \
1716                 __eid1, __eid2, __ev1, __ev2)           \
1717         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1718                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1719                 __ev1, __ev2),                          \
1720         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1721                 __bv1, __bv2, TPACPI_MATCH_UNKNOWN,     \
1722                 __ev1, __ev2)
1723
1724 #define TPV_QL0(__id1, __id2, __bv1, __bv2) \
1725         TPV_Q(PCI_VENDOR_ID_LENOVO, __id1, __id2, __bv1, __bv2)
1726
1727 #define TPV_QL1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1728         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __id1, __id2,     \
1729                 __bv1, __bv2, TPID(__id1, __id2),       \
1730                 __ev1, __ev2)
1731
1732 #define TPV_QL2(__bid1, __bid2, __bv1, __bv2,           \
1733                 __eid1, __eid2, __ev1, __ev2)           \
1734         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __bid1, __bid2,   \
1735                 __bv1, __bv2, TPID(__eid1, __eid2),     \
1736                 __ev1, __ev2)
1737
1738 static const struct tpacpi_quirk tpacpi_bios_version_qtable[] __initconst = {
1739         /*  Numeric models ------------------ */
1740         /*      FW MODEL   BIOS VERS          */
1741         TPV_QI0('I', 'M',  '6', '5'),            /* 570 */
1742         TPV_QI0('I', 'U',  '2', '6'),            /* 570E */
1743         TPV_QI0('I', 'B',  '5', '4'),            /* 600 */
1744         TPV_QI0('I', 'H',  '4', '7'),            /* 600E */
1745         TPV_QI0('I', 'N',  '3', '6'),            /* 600E */
1746         TPV_QI0('I', 'T',  '5', '5'),            /* 600X */
1747         TPV_QI0('I', 'D',  '4', '8'),            /* 770, 770E, 770ED */
1748         TPV_QI0('I', 'I',  '4', '2'),            /* 770X */
1749         TPV_QI0('I', 'O',  '2', '3'),            /* 770Z */
1750
1751         /* A-series ------------------------- */
1752         /*      FW MODEL   BIOS VERS  EC VERS */
1753         TPV_QI0('I', 'W',  '5', '9'),            /* A20m */
1754         TPV_QI0('I', 'V',  '6', '9'),            /* A20p */
1755         TPV_QI0('1', '0',  '2', '6'),            /* A21e, A22e */
1756         TPV_QI0('K', 'U',  '3', '6'),            /* A21e */
1757         TPV_QI0('K', 'X',  '3', '6'),            /* A21m, A22m */
1758         TPV_QI0('K', 'Y',  '3', '8'),            /* A21p, A22p */
1759         TPV_QI0('1', 'B',  '1', '7'),            /* A22e */
1760         TPV_QI0('1', '3',  '2', '0'),            /* A22m */
1761         TPV_QI0('1', 'E',  '7', '3'),            /* A30/p (0) */
1762         TPV_QI1('1', 'G',  '4', '1',  '1', '7'), /* A31/p (0) */
1763         TPV_QI1('1', 'N',  '1', '6',  '0', '7'), /* A31/p (0) */
1764
1765         /* G-series ------------------------- */
1766         /*      FW MODEL   BIOS VERS          */
1767         TPV_QI0('1', 'T',  'A', '6'),            /* G40 */
1768         TPV_QI0('1', 'X',  '5', '7'),            /* G41 */
1769
1770         /* R-series, T-series --------------- */
1771         /*      FW MODEL   BIOS VERS  EC VERS */
1772         TPV_QI0('1', 'C',  'F', '0'),            /* R30 */
1773         TPV_QI0('1', 'F',  'F', '1'),            /* R31 */
1774         TPV_QI0('1', 'M',  '9', '7'),            /* R32 */
1775         TPV_QI0('1', 'O',  '6', '1'),            /* R40 */
1776         TPV_QI0('1', 'P',  '6', '5'),            /* R40 */
1777         TPV_QI0('1', 'S',  '7', '0'),            /* R40e */
1778         TPV_QI1('1', 'R',  'D', 'R',  '7', '1'), /* R50/p, R51,
1779                                                     T40/p, T41/p, T42/p (1) */
1780         TPV_QI1('1', 'V',  '7', '1',  '2', '8'), /* R50e, R51 (1) */
1781         TPV_QI1('7', '8',  '7', '1',  '0', '6'), /* R51e (1) */
1782         TPV_QI1('7', '6',  '6', '9',  '1', '6'), /* R52 (1) */
1783         TPV_QI1('7', '0',  '6', '9',  '2', '8'), /* R52, T43 (1) */
1784
1785         TPV_QI0('I', 'Y',  '6', '1'),            /* T20 */
1786         TPV_QI0('K', 'Z',  '3', '4'),            /* T21 */
1787         TPV_QI0('1', '6',  '3', '2'),            /* T22 */
1788         TPV_QI1('1', 'A',  '6', '4',  '2', '3'), /* T23 (0) */
1789         TPV_QI1('1', 'I',  '7', '1',  '2', '0'), /* T30 (0) */
1790         TPV_QI1('1', 'Y',  '6', '5',  '2', '9'), /* T43/p (1) */
1791
1792         TPV_QL1('7', '9',  'E', '3',  '5', '0'), /* T60/p */
1793         TPV_QL1('7', 'C',  'D', '2',  '2', '2'), /* R60, R60i */
1794         TPV_QL1('7', 'E',  'D', '0',  '1', '5'), /* R60e, R60i */
1795
1796         /*      BIOS FW    BIOS VERS  EC FW     EC VERS */
1797         TPV_QI2('1', 'W',  '9', '0',  '1', 'V', '2', '8'), /* R50e (1) */
1798         TPV_QL2('7', 'I',  '3', '4',  '7', '9', '5', '0'), /* T60/p wide */
1799
1800         /* X-series ------------------------- */
1801         /*      FW MODEL   BIOS VERS  EC VERS */
1802         TPV_QI0('I', 'Z',  '9', 'D'),            /* X20, X21 */
1803         TPV_QI0('1', 'D',  '7', '0'),            /* X22, X23, X24 */
1804         TPV_QI1('1', 'K',  '4', '8',  '1', '8'), /* X30 (0) */
1805         TPV_QI1('1', 'Q',  '9', '7',  '2', '3'), /* X31, X32 (0) */
1806         TPV_QI1('1', 'U',  'D', '3',  'B', '2'), /* X40 (0) */
1807         TPV_QI1('7', '4',  '6', '4',  '2', '7'), /* X41 (0) */
1808         TPV_QI1('7', '5',  '6', '0',  '2', '0'), /* X41t (0) */
1809
1810         TPV_QL1('7', 'B',  'D', '7',  '4', '0'), /* X60/s */
1811         TPV_QL1('7', 'J',  '3', '0',  '1', '3'), /* X60t */
1812
1813         /* (0) - older versions lack DMI EC fw string and functionality */
1814         /* (1) - older versions known to lack functionality */
1815 };
1816
1817 #undef TPV_QL1
1818 #undef TPV_QL0
1819 #undef TPV_QI2
1820 #undef TPV_QI1
1821 #undef TPV_QI0
1822 #undef TPV_Q_X
1823 #undef TPV_Q
1824
1825 static void __init tpacpi_check_outdated_fw(void)
1826 {
1827         unsigned long fwvers;
1828         u16 ec_version, bios_version;
1829
1830         fwvers = tpacpi_check_quirks(tpacpi_bios_version_qtable,
1831                                 ARRAY_SIZE(tpacpi_bios_version_qtable));
1832
1833         if (!fwvers)
1834                 return;
1835
1836         bios_version = fwvers & 0xffffU;
1837         ec_version = (fwvers >> 16) & 0xffffU;
1838
1839         /* note that unknown versions are set to 0x0000 and we use that */
1840         if ((bios_version > thinkpad_id.bios_release) ||
1841             (ec_version > thinkpad_id.ec_release &&
1842                                 ec_version != TPACPI_MATCH_ANY)) {
1843                 /*
1844                  * The changelogs would let us track down the exact
1845                  * reason, but it is just too much of a pain to track
1846                  * it.  We only list BIOSes that are either really
1847                  * broken, or really stable to begin with, so it is
1848                  * best if the user upgrades the firmware anyway.
1849                  */
1850                 printk(TPACPI_WARN
1851                         "WARNING: Outdated ThinkPad BIOS/EC firmware\n");
1852                 printk(TPACPI_WARN
1853                         "WARNING: This firmware may be missing critical bug "
1854                         "fixes and/or important features\n");
1855         }
1856 }
1857
1858 static bool __init tpacpi_is_fw_known(void)
1859 {
1860         return tpacpi_check_quirks(tpacpi_bios_version_qtable,
1861                         ARRAY_SIZE(tpacpi_bios_version_qtable)) != 0;
1862 }
1863
1864 /****************************************************************************
1865  ****************************************************************************
1866  *
1867  * Subdrivers
1868  *
1869  ****************************************************************************
1870  ****************************************************************************/
1871
1872 /*************************************************************************
1873  * thinkpad-acpi init subdriver
1874  */
1875
1876 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
1877 {
1878         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
1879         printk(TPACPI_INFO "%s\n", TPACPI_URL);
1880
1881         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
1882                 (thinkpad_id.bios_version_str) ?
1883                         thinkpad_id.bios_version_str : "unknown",
1884                 (thinkpad_id.ec_version_str) ?
1885                         thinkpad_id.ec_version_str : "unknown");
1886
1887         if (thinkpad_id.vendor && thinkpad_id.model_str)
1888                 printk(TPACPI_INFO "%s %s, model %s\n",
1889                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
1890                                 "IBM" : ((thinkpad_id.vendor ==
1891                                                 PCI_VENDOR_ID_LENOVO) ?
1892                                         "Lenovo" : "Unknown vendor"),
1893                         thinkpad_id.model_str,
1894                         (thinkpad_id.nummodel_str) ?
1895                                 thinkpad_id.nummodel_str : "unknown");
1896
1897         tpacpi_check_outdated_fw();
1898         return 0;
1899 }
1900
1901 static int thinkpad_acpi_driver_read(struct seq_file *m)
1902 {
1903         seq_printf(m, "driver:\t\t%s\n", TPACPI_DESC);
1904         seq_printf(m, "version:\t%s\n", TPACPI_VERSION);
1905         return 0;
1906 }
1907
1908 static struct ibm_struct thinkpad_acpi_driver_data = {
1909         .name = "driver",
1910         .read = thinkpad_acpi_driver_read,
1911 };
1912
1913 /*************************************************************************
1914  * Hotkey subdriver
1915  */
1916
1917 /*
1918  * ThinkPad firmware event model
1919  *
1920  * The ThinkPad firmware has two main event interfaces: normal ACPI
1921  * notifications (which follow the ACPI standard), and a private event
1922  * interface.
1923  *
1924  * The private event interface also issues events for the hotkeys.  As
1925  * the driver gained features, the event handling code ended up being
1926  * built around the hotkey subdriver.  This will need to be refactored
1927  * to a more formal event API eventually.
1928  *
1929  * Some "hotkeys" are actually supposed to be used as event reports,
1930  * such as "brightness has changed", "volume has changed", depending on
1931  * the ThinkPad model and how the firmware is operating.
1932  *
1933  * Unlike other classes, hotkey-class events have mask/unmask control on
1934  * non-ancient firmware.  However, how it behaves changes a lot with the
1935  * firmware model and version.
1936  */
1937
1938 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1939         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1940         TP_ACPI_HOTKEYSCAN_FNF2,
1941         TP_ACPI_HOTKEYSCAN_FNF3,
1942         TP_ACPI_HOTKEYSCAN_FNF4,
1943         TP_ACPI_HOTKEYSCAN_FNF5,
1944         TP_ACPI_HOTKEYSCAN_FNF6,
1945         TP_ACPI_HOTKEYSCAN_FNF7,
1946         TP_ACPI_HOTKEYSCAN_FNF8,
1947         TP_ACPI_HOTKEYSCAN_FNF9,
1948         TP_ACPI_HOTKEYSCAN_FNF10,
1949         TP_ACPI_HOTKEYSCAN_FNF11,
1950         TP_ACPI_HOTKEYSCAN_FNF12,
1951         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1952         TP_ACPI_HOTKEYSCAN_FNINSERT,
1953         TP_ACPI_HOTKEYSCAN_FNDELETE,
1954         TP_ACPI_HOTKEYSCAN_FNHOME,
1955         TP_ACPI_HOTKEYSCAN_FNEND,
1956         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1957         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1958         TP_ACPI_HOTKEYSCAN_FNSPACE,
1959         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1960         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1961         TP_ACPI_HOTKEYSCAN_MUTE,
1962         TP_ACPI_HOTKEYSCAN_THINKPAD,
1963 };
1964
1965 enum {  /* Keys/events available through NVRAM polling */
1966         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1967         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1968 };
1969
1970 enum {  /* Positions of some of the keys in hotkey masks */
1971         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1972         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1973         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1974         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1975         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1976         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1977         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1978         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1979         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1980         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1981         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1982 };
1983
1984 enum {  /* NVRAM to ACPI HKEY group map */
1985         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1986                                           TP_ACPI_HKEY_ZOOM_MASK |
1987                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1988                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1989         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1990                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1991         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1992                                           TP_ACPI_HKEY_VOLDWN_MASK |
1993                                           TP_ACPI_HKEY_MUTE_MASK,
1994 };
1995
1996 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1997 struct tp_nvram_state {
1998        u16 thinkpad_toggle:1;
1999        u16 zoom_toggle:1;
2000        u16 display_toggle:1;
2001        u16 thinklight_toggle:1;
2002        u16 hibernate_toggle:1;
2003        u16 displayexp_toggle:1;
2004        u16 display_state:1;
2005        u16 brightness_toggle:1;
2006        u16 volume_toggle:1;
2007        u16 mute:1;
2008
2009        u8 brightness_level;
2010        u8 volume_level;
2011 };
2012
2013 /* kthread for the hotkey poller */
2014 static struct task_struct *tpacpi_hotkey_task;
2015
2016 /* Acquired while the poller kthread is running, use to sync start/stop */
2017 static struct mutex hotkey_thread_mutex;
2018
2019 /*
2020  * Acquire mutex to write poller control variables as an
2021  * atomic block.
2022  *
2023  * Increment hotkey_config_change when changing them if you
2024  * want the kthread to forget old state.
2025  *
2026  * See HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
2027  */
2028 static struct mutex hotkey_thread_data_mutex;
2029 static unsigned int hotkey_config_change;
2030
2031 /*
2032  * hotkey poller control variables
2033  *
2034  * Must be atomic or readers will also need to acquire mutex
2035  *
2036  * HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
2037  * should be used only when the changes need to be taken as
2038  * a block, OR when one needs to force the kthread to forget
2039  * old state.
2040  */
2041 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
2042 static unsigned int hotkey_poll_freq = 10; /* Hz */
2043
2044 #define HOTKEY_CONFIG_CRITICAL_START \
2045         do { \
2046                 mutex_lock(&hotkey_thread_data_mutex); \
2047                 hotkey_config_change++; \
2048         } while (0);
2049 #define HOTKEY_CONFIG_CRITICAL_END \
2050         mutex_unlock(&hotkey_thread_data_mutex);
2051
2052 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2053
2054 #define hotkey_source_mask 0U
2055 #define HOTKEY_CONFIG_CRITICAL_START
2056 #define HOTKEY_CONFIG_CRITICAL_END
2057
2058 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2059
2060 static struct mutex hotkey_mutex;
2061
2062 static enum {   /* Reasons for waking up */
2063         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
2064         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
2065         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
2066 } hotkey_wakeup_reason;
2067
2068 static int hotkey_autosleep_ack;
2069
2070 static u32 hotkey_orig_mask;            /* events the BIOS had enabled */
2071 static u32 hotkey_all_mask;             /* all events supported in fw */
2072 static u32 hotkey_reserved_mask;        /* events better left disabled */
2073 static u32 hotkey_driver_mask;          /* events needed by the driver */
2074 static u32 hotkey_user_mask;            /* events visible to userspace */
2075 static u32 hotkey_acpi_mask;            /* events enabled in firmware */
2076
2077 static unsigned int hotkey_report_mode;
2078
2079 static u16 *hotkey_keycode_map;
2080
2081 static struct attribute_set *hotkey_dev_attributes;
2082
2083 static void tpacpi_driver_event(const unsigned int hkey_event);
2084 static void hotkey_driver_event(const unsigned int scancode);
2085 static void hotkey_poll_setup(const bool may_warn);
2086
2087 /* HKEY.MHKG() return bits */
2088 #define TP_HOTKEY_TABLET_MASK (1 << 3)
2089
2090 static int hotkey_get_wlsw(void)
2091 {
2092         int status;
2093
2094         if (!tp_features.hotkey_wlsw)
2095                 return -ENODEV;
2096
2097 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2098         if (dbg_wlswemul)
2099                 return (tpacpi_wlsw_emulstate) ?
2100                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2101 #endif
2102
2103         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
2104                 return -EIO;
2105
2106         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2107 }
2108
2109 static int hotkey_get_tablet_mode(int *status)
2110 {
2111         int s;
2112
2113         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
2114                 return -EIO;
2115
2116         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
2117         return 0;
2118 }
2119
2120 /*
2121  * Reads current event mask from firmware, and updates
2122  * hotkey_acpi_mask accordingly.  Also resets any bits
2123  * from hotkey_user_mask that are unavailable to be
2124  * delivered (shadow requirement of the userspace ABI).
2125  *
2126  * Call with hotkey_mutex held
2127  */
2128 static int hotkey_mask_get(void)
2129 {
2130         if (tp_features.hotkey_mask) {
2131                 u32 m = 0;
2132
2133                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
2134                         return -EIO;
2135
2136                 hotkey_acpi_mask = m;
2137         } else {
2138                 /* no mask support doesn't mean no event support... */
2139                 hotkey_acpi_mask = hotkey_all_mask;
2140         }
2141
2142         /* sync userspace-visible mask */
2143         hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask);
2144
2145         return 0;
2146 }
2147
2148 void static hotkey_mask_warn_incomplete_mask(void)
2149 {
2150         /* log only what the user can fix... */
2151         const u32 wantedmask = hotkey_driver_mask &
2152                 ~(hotkey_acpi_mask | hotkey_source_mask) &
2153                 (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK);
2154
2155         if (wantedmask)
2156                 printk(TPACPI_NOTICE
2157                         "required events 0x%08x not enabled!\n",
2158                         wantedmask);
2159 }
2160
2161 /*
2162  * Set the firmware mask when supported
2163  *
2164  * Also calls hotkey_mask_get to update hotkey_acpi_mask.
2165  *
2166  * NOTE: does not set bits in hotkey_user_mask, but may reset them.
2167  *
2168  * Call with hotkey_mutex held
2169  */
2170 static int hotkey_mask_set(u32 mask)
2171 {
2172         int i;
2173         int rc = 0;
2174
2175         const u32 fwmask = mask & ~hotkey_source_mask;
2176
2177         if (tp_features.hotkey_mask) {
2178                 for (i = 0; i < 32; i++) {
2179                         if (!acpi_evalf(hkey_handle,
2180                                         NULL, "MHKM", "vdd", i + 1,
2181                                         !!(mask & (1 << i)))) {
2182                                 rc = -EIO;
2183                                 break;
2184                         }
2185                 }
2186         }
2187
2188         /*
2189          * We *must* make an inconditional call to hotkey_mask_get to
2190          * refresh hotkey_acpi_mask and update hotkey_user_mask
2191          *
2192          * Take the opportunity to also log when we cannot _enable_
2193          * a given event.
2194          */
2195         if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) {
2196                 printk(TPACPI_NOTICE
2197                        "asked for hotkey mask 0x%08x, but "
2198                        "firmware forced it to 0x%08x\n",
2199                        fwmask, hotkey_acpi_mask);
2200         }
2201
2202         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING)
2203                 hotkey_mask_warn_incomplete_mask();
2204
2205         return rc;
2206 }
2207
2208 /*
2209  * Sets hotkey_user_mask and tries to set the firmware mask
2210  *
2211  * Call with hotkey_mutex held
2212  */
2213 static int hotkey_user_mask_set(const u32 mask)
2214 {
2215         int rc;
2216
2217         /* Give people a chance to notice they are doing something that
2218          * is bound to go boom on their users sooner or later */
2219         if (!tp_warned.hotkey_mask_ff &&
2220             (mask == 0xffff || mask == 0xffffff ||
2221              mask == 0xffffffff)) {
2222                 tp_warned.hotkey_mask_ff = 1;
2223                 printk(TPACPI_NOTICE
2224                        "setting the hotkey mask to 0x%08x is likely "
2225                        "not the best way to go about it\n", mask);
2226                 printk(TPACPI_NOTICE
2227                        "please consider using the driver defaults, "
2228                        "and refer to up-to-date thinkpad-acpi "
2229                        "documentation\n");
2230         }
2231
2232         /* Try to enable what the user asked for, plus whatever we need.
2233          * this syncs everything but won't enable bits in hotkey_user_mask */
2234         rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask);
2235
2236         /* Enable the available bits in hotkey_user_mask */
2237         hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask);
2238
2239         return rc;
2240 }
2241
2242 /*
2243  * Sets the driver hotkey mask.
2244  *
2245  * Can be called even if the hotkey subdriver is inactive
2246  */
2247 static int tpacpi_hotkey_driver_mask_set(const u32 mask)
2248 {
2249         int rc;
2250
2251         /* Do the right thing if hotkey_init has not been called yet */
2252         if (!tp_features.hotkey) {
2253                 hotkey_driver_mask = mask;
2254                 return 0;
2255         }
2256
2257         mutex_lock(&hotkey_mutex);
2258
2259         HOTKEY_CONFIG_CRITICAL_START
2260         hotkey_driver_mask = mask;
2261 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2262         hotkey_source_mask |= (mask & ~hotkey_all_mask);
2263 #endif
2264         HOTKEY_CONFIG_CRITICAL_END
2265
2266         rc = hotkey_mask_set((hotkey_acpi_mask | hotkey_driver_mask) &
2267                                                         ~hotkey_source_mask);
2268         hotkey_poll_setup(true);
2269
2270         mutex_unlock(&hotkey_mutex);
2271
2272         return rc;
2273 }
2274
2275 static int hotkey_status_get(int *status)
2276 {
2277         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
2278                 return -EIO;
2279
2280         return 0;
2281 }
2282
2283 static int hotkey_status_set(bool enable)
2284 {
2285         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
2286                 return -EIO;
2287
2288         return 0;
2289 }
2290
2291 static void tpacpi_input_send_tabletsw(void)
2292 {
2293         int state;
2294
2295         if (tp_features.hotkey_tablet &&
2296             !hotkey_get_tablet_mode(&state)) {
2297                 mutex_lock(&tpacpi_inputdev_send_mutex);
2298
2299                 input_report_switch(tpacpi_inputdev,
2300                                     SW_TABLET_MODE, !!state);
2301                 input_sync(tpacpi_inputdev);
2302
2303                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2304         }
2305 }
2306
2307 /* Do NOT call without validating scancode first */
2308 static void tpacpi_input_send_key(const unsigned int scancode)
2309 {
2310         const unsigned int keycode = hotkey_keycode_map[scancode];
2311
2312         if (keycode != KEY_RESERVED) {
2313                 mutex_lock(&tpacpi_inputdev_send_mutex);
2314
2315                 input_report_key(tpacpi_inputdev, keycode, 1);
2316                 if (keycode == KEY_UNKNOWN)
2317                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2318                                     scancode);
2319                 input_sync(tpacpi_inputdev);
2320
2321                 input_report_key(tpacpi_inputdev, keycode, 0);
2322                 if (keycode == KEY_UNKNOWN)
2323                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2324                                     scancode);
2325                 input_sync(tpacpi_inputdev);
2326
2327                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2328         }
2329 }
2330
2331 /* Do NOT call without validating scancode first */
2332 static void tpacpi_input_send_key_masked(const unsigned int scancode)
2333 {
2334         hotkey_driver_event(scancode);
2335         if (hotkey_user_mask & (1 << scancode))
2336                 tpacpi_input_send_key(scancode);
2337 }
2338
2339 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2340 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
2341
2342 /* Do NOT call without validating scancode first */
2343 static void tpacpi_hotkey_send_key(unsigned int scancode)
2344 {
2345         tpacpi_input_send_key_masked(scancode);
2346         if (hotkey_report_mode < 2) {
2347                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
2348                                 0x80, TP_HKEY_EV_HOTKEY_BASE + scancode);
2349         }
2350 }
2351
2352 static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m)
2353 {
2354         u8 d;
2355
2356         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
2357                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
2358                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
2359                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
2360                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
2361                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
2362         }
2363         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
2364                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
2365                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2366         }
2367         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2368                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2369                 n->displayexp_toggle =
2370                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2371         }
2372         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2373                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2374                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2375                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2376                 n->brightness_toggle =
2377                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2378         }
2379         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2380                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2381                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2382                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2383                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2384                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2385         }
2386 }
2387
2388 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2389                                            struct tp_nvram_state *newn,
2390                                            const u32 event_mask)
2391 {
2392
2393 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2394         do { \
2395                 if ((event_mask & (1 << __scancode)) && \
2396                     oldn->__member != newn->__member) \
2397                         tpacpi_hotkey_send_key(__scancode); \
2398         } while (0)
2399
2400 #define TPACPI_MAY_SEND_KEY(__scancode) \
2401         do { \
2402                 if (event_mask & (1 << __scancode)) \
2403                         tpacpi_hotkey_send_key(__scancode); \
2404         } while (0)
2405
2406         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2407         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2408         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2409         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2410
2411         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2412
2413         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2414
2415         /* handle volume */
2416         if (oldn->volume_toggle != newn->volume_toggle) {
2417                 if (oldn->mute != newn->mute) {
2418                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2419                 }
2420                 if (oldn->volume_level > newn->volume_level) {
2421                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2422                 } else if (oldn->volume_level < newn->volume_level) {
2423                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2424                 } else if (oldn->mute == newn->mute) {
2425                         /* repeated key presses that didn't change state */
2426                         if (newn->mute) {
2427                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2428                         } else if (newn->volume_level != 0) {
2429                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2430                         } else {
2431                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2432                         }
2433                 }
2434         }
2435
2436         /* handle brightness */
2437         if (oldn->brightness_toggle != newn->brightness_toggle) {
2438                 if (oldn->brightness_level < newn->brightness_level) {
2439                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2440                 } else if (oldn->brightness_level > newn->brightness_level) {
2441                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2442                 } else {
2443                         /* repeated key presses that didn't change state */
2444                         if (newn->brightness_level != 0) {
2445                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2446                         } else {
2447                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2448                         }
2449                 }
2450         }
2451
2452 #undef TPACPI_COMPARE_KEY
2453 #undef TPACPI_MAY_SEND_KEY
2454 }
2455
2456 /*
2457  * Polling driver
2458  *
2459  * We track all events in hotkey_source_mask all the time, since
2460  * most of them are edge-based.  We only issue those requested by
2461  * hotkey_user_mask or hotkey_driver_mask, though.
2462  */
2463 static int hotkey_kthread(void *data)
2464 {
2465         struct tp_nvram_state s[2];
2466         u32 poll_mask, event_mask;
2467         unsigned int si, so;
2468         unsigned long t;
2469         unsigned int change_detector, must_reset;
2470         unsigned int poll_freq;
2471
2472         mutex_lock(&hotkey_thread_mutex);
2473
2474         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2475                 goto exit;
2476
2477         set_freezable();
2478
2479         so = 0;
2480         si = 1;
2481         t = 0;
2482
2483         /* Initial state for compares */
2484         mutex_lock(&hotkey_thread_data_mutex);
2485         change_detector = hotkey_config_change;
2486         poll_mask = hotkey_source_mask;
2487         event_mask = hotkey_source_mask &
2488                         (hotkey_driver_mask | hotkey_user_mask);
2489         poll_freq = hotkey_poll_freq;
2490         mutex_unlock(&hotkey_thread_data_mutex);
2491         hotkey_read_nvram(&s[so], poll_mask);
2492
2493         while (!kthread_should_stop()) {
2494                 if (t == 0) {
2495                         if (likely(poll_freq))
2496                                 t = 1000/poll_freq;
2497                         else
2498                                 t = 100;        /* should never happen... */
2499                 }
2500                 t = msleep_interruptible(t);
2501                 if (unlikely(kthread_should_stop()))
2502                         break;
2503                 must_reset = try_to_freeze();
2504                 if (t > 0 && !must_reset)
2505                         continue;
2506
2507                 mutex_lock(&hotkey_thread_data_mutex);
2508                 if (must_reset || hotkey_config_change != change_detector) {
2509                         /* forget old state on thaw or config change */
2510                         si = so;
2511                         t = 0;
2512                         change_detector = hotkey_config_change;
2513                 }
2514                 poll_mask = hotkey_source_mask;
2515                 event_mask = hotkey_source_mask &
2516                                 (hotkey_driver_mask | hotkey_user_mask);
2517                 poll_freq = hotkey_poll_freq;
2518                 mutex_unlock(&hotkey_thread_data_mutex);
2519
2520                 if (likely(poll_mask)) {
2521                         hotkey_read_nvram(&s[si], poll_mask);
2522                         if (likely(si != so)) {
2523                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2524                                                                 event_mask);
2525                         }
2526                 }
2527
2528                 so = si;
2529                 si ^= 1;
2530         }
2531
2532 exit:
2533         mutex_unlock(&hotkey_thread_mutex);
2534         return 0;
2535 }
2536
2537 /* call with hotkey_mutex held */
2538 static void hotkey_poll_stop_sync(void)
2539 {
2540         if (tpacpi_hotkey_task) {
2541                 if (frozen(tpacpi_hotkey_task) ||
2542                     freezing(tpacpi_hotkey_task))
2543                         thaw_process(tpacpi_hotkey_task);
2544
2545                 kthread_stop(tpacpi_hotkey_task);
2546                 tpacpi_hotkey_task = NULL;
2547                 mutex_lock(&hotkey_thread_mutex);
2548                 /* at this point, the thread did exit */
2549                 mutex_unlock(&hotkey_thread_mutex);
2550         }
2551 }
2552
2553 /* call with hotkey_mutex held */
2554 static void hotkey_poll_setup(const bool may_warn)
2555 {
2556         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2557         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2558
2559         if (hotkey_poll_freq > 0 &&
2560             (poll_driver_mask ||
2561              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2562                 if (!tpacpi_hotkey_task) {
2563                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2564                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2565                         if (IS_ERR(tpacpi_hotkey_task)) {
2566                                 tpacpi_hotkey_task = NULL;
2567                                 printk(TPACPI_ERR
2568                                        "could not create kernel thread "
2569                                        "for hotkey polling\n");
2570                         }
2571                 }
2572         } else {
2573                 hotkey_poll_stop_sync();
2574                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2575                     hotkey_poll_freq == 0) {
2576                         printk(TPACPI_NOTICE
2577                                 "hot keys 0x%08x and/or events 0x%08x "
2578                                 "require polling, which is currently "
2579                                 "disabled\n",
2580                                 poll_user_mask, poll_driver_mask);
2581                 }
2582         }
2583 }
2584
2585 static void hotkey_poll_setup_safe(const bool may_warn)
2586 {
2587         mutex_lock(&hotkey_mutex);
2588         hotkey_poll_setup(may_warn);
2589         mutex_unlock(&hotkey_mutex);
2590 }
2591
2592 /* call with hotkey_mutex held */
2593 static void hotkey_poll_set_freq(unsigned int freq)
2594 {
2595         if (!freq)
2596                 hotkey_poll_stop_sync();
2597
2598         hotkey_poll_freq = freq;
2599 }
2600
2601 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2602
2603 static void hotkey_poll_setup(const bool __unused)
2604 {
2605 }
2606
2607 static void hotkey_poll_setup_safe(const bool __unused)
2608 {
2609 }
2610
2611 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2612
2613 static int hotkey_inputdev_open(struct input_dev *dev)
2614 {
2615         switch (tpacpi_lifecycle) {
2616         case TPACPI_LIFE_INIT:
2617         case TPACPI_LIFE_RUNNING:
2618                 hotkey_poll_setup_safe(false);
2619                 return 0;
2620         case TPACPI_LIFE_EXITING:
2621                 return -EBUSY;
2622         }
2623
2624         /* Should only happen if tpacpi_lifecycle is corrupt */
2625         BUG();
2626         return -EBUSY;
2627 }
2628
2629 static void hotkey_inputdev_close(struct input_dev *dev)
2630 {
2631         /* disable hotkey polling when possible */
2632         if (tpacpi_lifecycle != TPACPI_LIFE_EXITING &&
2633             !(hotkey_source_mask & hotkey_driver_mask))
2634                 hotkey_poll_setup_safe(false);
2635 }
2636
2637 /* sysfs hotkey enable ------------------------------------------------- */
2638 static ssize_t hotkey_enable_show(struct device *dev,
2639                            struct device_attribute *attr,
2640                            char *buf)
2641 {
2642         int res, status;
2643
2644         printk_deprecated_attribute("hotkey_enable",
2645                         "Hotkey reporting is always enabled");
2646
2647         res = hotkey_status_get(&status);
2648         if (res)
2649                 return res;
2650
2651         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2652 }
2653
2654 static ssize_t hotkey_enable_store(struct device *dev,
2655                             struct device_attribute *attr,
2656                             const char *buf, size_t count)
2657 {
2658         unsigned long t;
2659
2660         printk_deprecated_attribute("hotkey_enable",
2661                         "Hotkeys can be disabled through hotkey_mask");
2662
2663         if (parse_strtoul(buf, 1, &t))
2664                 return -EINVAL;
2665
2666         if (t == 0)
2667                 return -EPERM;
2668
2669         return count;
2670 }
2671
2672 static struct device_attribute dev_attr_hotkey_enable =
2673         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2674                 hotkey_enable_show, hotkey_enable_store);
2675
2676 /* sysfs hotkey mask --------------------------------------------------- */
2677 static ssize_t hotkey_mask_show(struct device *dev,
2678                            struct device_attribute *attr,
2679                            char *buf)
2680 {
2681         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2682 }
2683
2684 static ssize_t hotkey_mask_store(struct device *dev,
2685                             struct device_attribute *attr,
2686                             const char *buf, size_t count)
2687 {
2688         unsigned long t;
2689         int res;
2690
2691         if (parse_strtoul(buf, 0xffffffffUL, &t))
2692                 return -EINVAL;
2693
2694         if (mutex_lock_killable(&hotkey_mutex))
2695                 return -ERESTARTSYS;
2696
2697         res = hotkey_user_mask_set(t);
2698
2699 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2700         hotkey_poll_setup(true);
2701 #endif
2702
2703         mutex_unlock(&hotkey_mutex);
2704
2705         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2706
2707         return (res) ? res : count;
2708 }
2709
2710 static struct device_attribute dev_attr_hotkey_mask =
2711         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2712                 hotkey_mask_show, hotkey_mask_store);
2713
2714 /* sysfs hotkey bios_enabled ------------------------------------------- */
2715 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2716                            struct device_attribute *attr,
2717                            char *buf)
2718 {
2719         return sprintf(buf, "0\n");
2720 }
2721
2722 static struct device_attribute dev_attr_hotkey_bios_enabled =
2723         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2724
2725 /* sysfs hotkey bios_mask ---------------------------------------------- */
2726 static ssize_t hotkey_bios_mask_show(struct device *dev,
2727                            struct device_attribute *attr,
2728                            char *buf)
2729 {
2730         printk_deprecated_attribute("hotkey_bios_mask",
2731                         "This attribute is useless.");
2732         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2733 }
2734
2735 static struct device_attribute dev_attr_hotkey_bios_mask =
2736         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2737
2738 /* sysfs hotkey all_mask ----------------------------------------------- */
2739 static ssize_t hotkey_all_mask_show(struct device *dev,
2740                            struct device_attribute *attr,
2741                            char *buf)
2742 {
2743         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2744                                 hotkey_all_mask | hotkey_source_mask);
2745 }
2746
2747 static struct device_attribute dev_attr_hotkey_all_mask =
2748         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2749
2750 /* sysfs hotkey recommended_mask --------------------------------------- */
2751 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2752                                             struct device_attribute *attr,
2753                                             char *buf)
2754 {
2755         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2756                         (hotkey_all_mask | hotkey_source_mask)
2757                         & ~hotkey_reserved_mask);
2758 }
2759
2760 static struct device_attribute dev_attr_hotkey_recommended_mask =
2761         __ATTR(hotkey_recommended_mask, S_IRUGO,
2762                 hotkey_recommended_mask_show, NULL);
2763
2764 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2765
2766 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2767 static ssize_t hotkey_source_mask_show(struct device *dev,
2768                            struct device_attribute *attr,
2769                            char *buf)
2770 {
2771         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2772 }
2773
2774 static ssize_t hotkey_source_mask_store(struct device *dev,
2775                             struct device_attribute *attr,
2776                             const char *buf, size_t count)
2777 {
2778         unsigned long t;
2779         u32 r_ev;
2780         int rc;
2781
2782         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2783                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2784                 return -EINVAL;
2785
2786         if (mutex_lock_killable(&hotkey_mutex))
2787                 return -ERESTARTSYS;
2788
2789         HOTKEY_CONFIG_CRITICAL_START
2790         hotkey_source_mask = t;
2791         HOTKEY_CONFIG_CRITICAL_END
2792
2793         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2794                         ~hotkey_source_mask);
2795         hotkey_poll_setup(true);
2796
2797         /* check if events needed by the driver got disabled */
2798         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2799                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2800
2801         mutex_unlock(&hotkey_mutex);
2802
2803         if (rc < 0)
2804                 printk(TPACPI_ERR "hotkey_source_mask: failed to update the"
2805                         "firmware event mask!\n");
2806
2807         if (r_ev)
2808                 printk(TPACPI_NOTICE "hotkey_source_mask: "
2809                         "some important events were disabled: "
2810                         "0x%04x\n", r_ev);
2811
2812         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2813
2814         return (rc < 0) ? rc : count;
2815 }
2816
2817 static struct device_attribute dev_attr_hotkey_source_mask =
2818         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2819                 hotkey_source_mask_show, hotkey_source_mask_store);
2820
2821 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2822 static ssize_t hotkey_poll_freq_show(struct device *dev,
2823                            struct device_attribute *attr,
2824                            char *buf)
2825 {
2826         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2827 }
2828
2829 static ssize_t hotkey_poll_freq_store(struct device *dev,
2830                             struct device_attribute *attr,
2831                             const char *buf, size_t count)
2832 {
2833         unsigned long t;
2834
2835         if (parse_strtoul(buf, 25, &t))
2836                 return -EINVAL;
2837
2838         if (mutex_lock_killable(&hotkey_mutex))
2839                 return -ERESTARTSYS;
2840
2841         hotkey_poll_set_freq(t);
2842         hotkey_poll_setup(true);
2843
2844         mutex_unlock(&hotkey_mutex);
2845
2846         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2847
2848         return count;
2849 }
2850
2851 static struct device_attribute dev_attr_hotkey_poll_freq =
2852         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2853                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2854
2855 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2856
2857 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2858 static ssize_t hotkey_radio_sw_show(struct device *dev,
2859                            struct device_attribute *attr,
2860                            char *buf)
2861 {
2862         int res;
2863         res = hotkey_get_wlsw();
2864         if (res < 0)
2865                 return res;
2866
2867         /* Opportunistic update */
2868         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2869
2870         return snprintf(buf, PAGE_SIZE, "%d\n",
2871                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2872 }
2873
2874 static struct device_attribute dev_attr_hotkey_radio_sw =
2875         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
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 struct device_attribute dev_attr_hotkey_tablet_mode =
2898         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2899
2900 static void hotkey_tablet_mode_notify_change(void)
2901 {
2902         if (tp_features.hotkey_tablet)
2903                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2904                              "hotkey_tablet_mode");
2905 }
2906
2907 /* sysfs hotkey report_mode -------------------------------------------- */
2908 static ssize_t hotkey_report_mode_show(struct device *dev,
2909                            struct device_attribute *attr,
2910                            char *buf)
2911 {
2912         return snprintf(buf, PAGE_SIZE, "%d\n",
2913                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2914 }
2915
2916 static struct device_attribute dev_attr_hotkey_report_mode =
2917         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2918
2919 /* sysfs wakeup reason (pollable) -------------------------------------- */
2920 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2921                            struct device_attribute *attr,
2922                            char *buf)
2923 {
2924         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2925 }
2926
2927 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2928         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2929
2930 static void hotkey_wakeup_reason_notify_change(void)
2931 {
2932         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2933                      "wakeup_reason");
2934 }
2935
2936 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2937 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2938                            struct device_attribute *attr,
2939                            char *buf)
2940 {
2941         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2942 }
2943
2944 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2945         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2946                hotkey_wakeup_hotunplug_complete_show, NULL);
2947
2948 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2949 {
2950         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2951                      "wakeup_hotunplug_complete");
2952 }
2953
2954 /* --------------------------------------------------------------------- */
2955
2956 static struct attribute *hotkey_attributes[] __initdata = {
2957         &dev_attr_hotkey_enable.attr,
2958         &dev_attr_hotkey_bios_enabled.attr,
2959         &dev_attr_hotkey_bios_mask.attr,
2960         &dev_attr_hotkey_report_mode.attr,
2961         &dev_attr_hotkey_wakeup_reason.attr,
2962         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2963         &dev_attr_hotkey_mask.attr,
2964         &dev_attr_hotkey_all_mask.attr,
2965         &dev_attr_hotkey_recommended_mask.attr,
2966 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2967         &dev_attr_hotkey_source_mask.attr,
2968         &dev_attr_hotkey_poll_freq.attr,
2969 #endif
2970 };
2971
2972 /*
2973  * Sync both the hw and sw blocking state of all switches
2974  */
2975 static void tpacpi_send_radiosw_update(void)
2976 {
2977         int wlsw;
2978
2979         /*
2980          * We must sync all rfkill controllers *before* issuing any
2981          * rfkill input events, or we will race the rfkill core input
2982          * handler.
2983          *
2984          * tpacpi_inputdev_send_mutex works as a syncronization point
2985          * for the above.
2986          *
2987          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2988          */
2989
2990         wlsw = hotkey_get_wlsw();
2991
2992         /* Sync hw blocking state first if it is hw-blocked */
2993         if (wlsw == TPACPI_RFK_RADIO_OFF)
2994                 tpacpi_rfk_update_hwblock_state(true);
2995
2996         /* Sync sw blocking state */
2997         tpacpi_rfk_update_swstate_all();
2998
2999         /* Sync hw blocking state last if it is hw-unblocked */
3000         if (wlsw == TPACPI_RFK_RADIO_ON)
3001                 tpacpi_rfk_update_hwblock_state(false);
3002
3003         /* Issue rfkill input event for WLSW switch */
3004         if (!(wlsw < 0)) {
3005                 mutex_lock(&tpacpi_inputdev_send_mutex);
3006
3007                 input_report_switch(tpacpi_inputdev,
3008                                     SW_RFKILL_ALL, (wlsw > 0));
3009                 input_sync(tpacpi_inputdev);
3010
3011                 mutex_unlock(&tpacpi_inputdev_send_mutex);
3012         }
3013
3014         /*
3015          * this can be unconditional, as we will poll state again
3016          * if userspace uses the notify to read data
3017          */
3018         hotkey_radio_sw_notify_change();
3019 }
3020
3021 static void hotkey_exit(void)
3022 {
3023 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3024         mutex_lock(&hotkey_mutex);
3025         hotkey_poll_stop_sync();
3026         mutex_unlock(&hotkey_mutex);
3027 #endif
3028
3029         if (hotkey_dev_attributes)
3030                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3031
3032         kfree(hotkey_keycode_map);
3033
3034         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
3035                    "restoring original HKEY status and mask\n");
3036         /* yes, there is a bitwise or below, we want the
3037          * functions to be called even if one of them fail */
3038         if (((tp_features.hotkey_mask &&
3039               hotkey_mask_set(hotkey_orig_mask)) |
3040              hotkey_status_set(false)) != 0)
3041                 printk(TPACPI_ERR
3042                        "failed to restore hot key mask "
3043                        "to BIOS defaults\n");
3044 }
3045
3046 static void __init hotkey_unmap(const unsigned int scancode)
3047 {
3048         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
3049                 clear_bit(hotkey_keycode_map[scancode],
3050                           tpacpi_inputdev->keybit);
3051                 hotkey_keycode_map[scancode] = KEY_RESERVED;
3052         }
3053 }
3054
3055 /*
3056  * HKEY quirks:
3057  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
3058  */
3059
3060 #define TPACPI_HK_Q_INIMASK     0x0001
3061
3062 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
3063         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
3064         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
3065         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
3066         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
3067         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
3068         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
3069         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
3070         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
3071         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
3072         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
3073         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
3074         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
3075         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
3076         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
3077         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
3078         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
3079         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
3080         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
3081         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
3082 };
3083
3084 static int __init hotkey_init(struct ibm_init_struct *iibm)
3085 {
3086         /* Requirements for changing the default keymaps:
3087          *
3088          * 1. Many of the keys are mapped to KEY_RESERVED for very
3089          *    good reasons.  Do not change them unless you have deep
3090          *    knowledge on the IBM and Lenovo ThinkPad firmware for
3091          *    the various ThinkPad models.  The driver behaves
3092          *    differently for KEY_RESERVED: such keys have their
3093          *    hot key mask *unset* in mask_recommended, and also
3094          *    in the initial hot key mask programmed into the
3095          *    firmware at driver load time, which means the firm-
3096          *    ware may react very differently if you change them to
3097          *    something else;
3098          *
3099          * 2. You must be subscribed to the linux-thinkpad and
3100          *    ibm-acpi-devel mailing lists, and you should read the
3101          *    list archives since 2007 if you want to change the
3102          *    keymaps.  This requirement exists so that you will
3103          *    know the past history of problems with the thinkpad-
3104          *    acpi driver keymaps, and also that you will be
3105          *    listening to any bug reports;
3106          *
3107          * 3. Do not send thinkpad-acpi specific patches directly to
3108          *    for merging, *ever*.  Send them to the linux-acpi
3109          *    mailinglist for comments.  Merging is to be done only
3110          *    through acpi-test and the ACPI maintainer.
3111          *
3112          * If the above is too much to ask, don't change the keymap.
3113          * Ask the thinkpad-acpi maintainer to do it, instead.
3114          */
3115         static u16 ibm_keycode_map[] __initdata = {
3116                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3117                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
3118                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3119                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3120
3121                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3122                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3123                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3124                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3125
3126                 /* brightness: firmware always reacts to them */
3127                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3128                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3129
3130                 /* Thinklight: firmware always react to it */
3131                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3132
3133                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3134                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3135
3136                 /* Volume: firmware always react to it and reprograms
3137                  * the built-in *extra* mixer.  Never map it to control
3138                  * another mixer by default. */
3139                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3140                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3141                 KEY_RESERVED,   /* 0x16: MUTE */
3142
3143                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3144
3145                 /* (assignments unknown, please report if found) */
3146                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3147                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3148         };
3149         static u16 lenovo_keycode_map[] __initdata = {
3150                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3151                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3152                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3153                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3154
3155                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3156                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3157                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3158                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3159
3160                 /* These should be enabled --only-- when ACPI video
3161                  * is disabled (i.e. in "vendor" mode), and are handled
3162                  * in a special way by the init code */
3163                 KEY_BRIGHTNESSUP,       /* 0x0F: FN+HOME (brightness up) */
3164                 KEY_BRIGHTNESSDOWN,     /* 0x10: FN+END (brightness down) */
3165
3166                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3167
3168                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3169                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3170
3171                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
3172                  * react to it and reprograms the built-in *extra* mixer.
3173                  * Never map it to control another mixer by default.
3174                  *
3175                  * T60?, T61, R60?, R61: firmware and EC tries to send
3176                  * these over the regular keyboard, so these are no-ops,
3177                  * but there are still weird bugs re. MUTE, so do not
3178                  * change unless you get test reports from all Lenovo
3179                  * models.  May cause the BIOS to interfere with the
3180                  * HDA mixer.
3181                  */
3182                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3183                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3184                 KEY_RESERVED,   /* 0x16: MUTE */
3185
3186                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3187
3188                 /* (assignments unknown, please report if found) */
3189                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3190                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3191         };
3192
3193 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
3194 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
3195 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
3196
3197         int res, i;
3198         int status;
3199         int hkeyv;
3200         bool radiosw_state  = false;
3201         bool tabletsw_state = false;
3202
3203         unsigned long quirks;
3204
3205         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3206                         "initializing hotkey subdriver\n");
3207
3208         BUG_ON(!tpacpi_inputdev);
3209         BUG_ON(tpacpi_inputdev->open != NULL ||
3210                tpacpi_inputdev->close != NULL);
3211
3212         TPACPI_ACPIHANDLE_INIT(hkey);
3213         mutex_init(&hotkey_mutex);
3214
3215 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3216         mutex_init(&hotkey_thread_mutex);
3217         mutex_init(&hotkey_thread_data_mutex);
3218 #endif
3219
3220         /* hotkey not supported on 570 */
3221         tp_features.hotkey = hkey_handle != NULL;
3222
3223         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3224                 "hotkeys are %s\n",
3225                 str_supported(tp_features.hotkey));
3226
3227         if (!tp_features.hotkey)
3228                 return 1;
3229
3230         quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable,
3231                                      ARRAY_SIZE(tpacpi_hotkey_qtable));
3232
3233         tpacpi_disable_brightness_delay();
3234
3235         /* MUST have enough space for all attributes to be added to
3236          * hotkey_dev_attributes */
3237         hotkey_dev_attributes = create_attr_set(
3238                                         ARRAY_SIZE(hotkey_attributes) + 2,
3239                                         NULL);
3240         if (!hotkey_dev_attributes)
3241                 return -ENOMEM;
3242         res = add_many_to_attr_set(hotkey_dev_attributes,
3243                         hotkey_attributes,
3244                         ARRAY_SIZE(hotkey_attributes));
3245         if (res)
3246                 goto err_exit;
3247
3248         /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p,
3249            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
3250            for HKEY interface version 0x100 */
3251         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
3252                 if ((hkeyv >> 8) != 1) {
3253                         printk(TPACPI_ERR "unknown version of the "
3254                                "HKEY interface: 0x%x\n", hkeyv);
3255                         printk(TPACPI_ERR "please report this to %s\n",
3256                                TPACPI_MAIL);
3257                 } else {
3258                         /*
3259                          * MHKV 0x100 in A31, R40, R40e,
3260                          * T4x, X31, and later
3261                          */
3262                         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3263                                 "firmware HKEY interface version: 0x%x\n",
3264                                 hkeyv);
3265
3266                         /* Paranoia check AND init hotkey_all_mask */
3267                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3268                                         "MHKA", "qd")) {
3269                                 printk(TPACPI_ERR
3270                                        "missing MHKA handler, "
3271                                        "please report this to %s\n",
3272                                        TPACPI_MAIL);
3273                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3274                                 hotkey_all_mask = 0x080cU;
3275                         } else {
3276                                 tp_features.hotkey_mask = 1;
3277                         }
3278                 }
3279         }
3280
3281         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3282                 "hotkey masks are %s\n",
3283                 str_supported(tp_features.hotkey_mask));
3284
3285         /* Init hotkey_all_mask if not initialized yet */
3286         if (!tp_features.hotkey_mask && !hotkey_all_mask &&
3287             (quirks & TPACPI_HK_Q_INIMASK))
3288                 hotkey_all_mask = 0x080cU;  /* FN+F12, FN+F4, FN+F3 */
3289
3290         /* Init hotkey_acpi_mask and hotkey_orig_mask */
3291         if (tp_features.hotkey_mask) {
3292                 /* hotkey_source_mask *must* be zero for
3293                  * the first hotkey_mask_get to return hotkey_orig_mask */
3294                 res = hotkey_mask_get();
3295                 if (res)
3296                         goto err_exit;
3297
3298                 hotkey_orig_mask = hotkey_acpi_mask;
3299         } else {
3300                 hotkey_orig_mask = hotkey_all_mask;
3301                 hotkey_acpi_mask = hotkey_all_mask;
3302         }
3303
3304 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3305         if (dbg_wlswemul) {
3306                 tp_features.hotkey_wlsw = 1;
3307                 radiosw_state = !!tpacpi_wlsw_emulstate;
3308                 printk(TPACPI_INFO
3309                         "radio switch emulation enabled\n");
3310         } else
3311 #endif
3312         /* Not all thinkpads have a hardware radio switch */
3313         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
3314                 tp_features.hotkey_wlsw = 1;
3315                 radiosw_state = !!status;
3316                 printk(TPACPI_INFO
3317                         "radio switch found; radios are %s\n",
3318                         enabled(status, 0));
3319         }
3320         if (tp_features.hotkey_wlsw)
3321                 res = add_to_attr_set(hotkey_dev_attributes,
3322                                 &dev_attr_hotkey_radio_sw.attr);
3323
3324         /* For X41t, X60t, X61t Tablets... */
3325         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
3326                 tp_features.hotkey_tablet = 1;
3327                 tabletsw_state = !!(status & TP_HOTKEY_TABLET_MASK);
3328                 printk(TPACPI_INFO
3329                         "possible tablet mode switch found; "
3330                         "ThinkPad in %s mode\n",
3331                         (tabletsw_state) ? "tablet" : "laptop");
3332                 res = add_to_attr_set(hotkey_dev_attributes,
3333                                 &dev_attr_hotkey_tablet_mode.attr);
3334         }
3335
3336         if (!res)
3337                 res = register_attr_set_with_sysfs(
3338                                 hotkey_dev_attributes,
3339                                 &tpacpi_pdev->dev.kobj);
3340         if (res)
3341                 goto err_exit;
3342
3343         /* Set up key map */
3344
3345         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
3346                                         GFP_KERNEL);
3347         if (!hotkey_keycode_map) {
3348                 printk(TPACPI_ERR
3349                         "failed to allocate memory for key map\n");
3350                 res = -ENOMEM;
3351                 goto err_exit;
3352         }
3353
3354         if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
3355                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3356                            "using Lenovo default hot key map\n");
3357                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
3358                         TPACPI_HOTKEY_MAP_SIZE);
3359         } else {
3360                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3361                            "using IBM default hot key map\n");
3362                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
3363                         TPACPI_HOTKEY_MAP_SIZE);
3364         }
3365
3366         input_set_capability(tpacpi_inputdev, EV_MSC, MSC_SCAN);
3367         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
3368         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
3369         tpacpi_inputdev->keycode = hotkey_keycode_map;
3370         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
3371                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
3372                         input_set_capability(tpacpi_inputdev, EV_KEY,
3373                                                 hotkey_keycode_map[i]);
3374                 } else {
3375                         if (i < sizeof(hotkey_reserved_mask)*8)
3376                                 hotkey_reserved_mask |= 1 << i;
3377                 }
3378         }
3379
3380         if (tp_features.hotkey_wlsw) {
3381                 input_set_capability(tpacpi_inputdev, EV_SW, SW_RFKILL_ALL);
3382                 input_report_switch(tpacpi_inputdev,
3383                                     SW_RFKILL_ALL, radiosw_state);
3384         }
3385         if (tp_features.hotkey_tablet) {
3386                 input_set_capability(tpacpi_inputdev, EV_SW, SW_TABLET_MODE);
3387                 input_report_switch(tpacpi_inputdev,
3388                                     SW_TABLET_MODE, tabletsw_state);
3389         }
3390
3391         /* Do not issue duplicate brightness change events to
3392          * userspace */
3393         if (!tp_features.bright_acpimode)
3394                 /* update bright_acpimode... */
3395                 tpacpi_check_std_acpi_brightness_support();
3396
3397         if (tp_features.bright_acpimode && acpi_video_backlight_support()) {
3398                 printk(TPACPI_INFO
3399                        "This ThinkPad has standard ACPI backlight "
3400                        "brightness control, supported by the ACPI "
3401                        "video driver\n");
3402                 printk(TPACPI_NOTICE
3403                        "Disabling thinkpad-acpi brightness events "
3404                        "by default...\n");
3405
3406                 /* Disable brightness up/down on Lenovo thinkpads when
3407                  * ACPI is handling them, otherwise it is plain impossible
3408                  * for userspace to do something even remotely sane */
3409                 hotkey_reserved_mask |=
3410                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
3411                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
3412                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME);
3413                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND);
3414         }
3415
3416 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3417         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
3418                                 & ~hotkey_all_mask
3419                                 & ~hotkey_reserved_mask;
3420
3421         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3422                     "hotkey source mask 0x%08x, polling freq %u\n",
3423                     hotkey_source_mask, hotkey_poll_freq);
3424 #endif
3425
3426         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3427                         "enabling firmware HKEY event interface...\n");
3428         res = hotkey_status_set(true);
3429         if (res) {
3430                 hotkey_exit();
3431                 return res;
3432         }
3433         res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask)
3434                                | hotkey_driver_mask)
3435                               & ~hotkey_source_mask);
3436         if (res < 0 && res != -ENXIO) {
3437                 hotkey_exit();
3438                 return res;
3439         }
3440         hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask)
3441                                 & ~hotkey_reserved_mask;
3442         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3443                 "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n",
3444                 hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask);
3445
3446         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3447                         "legacy ibm/hotkey event reporting over procfs %s\n",
3448                         (hotkey_report_mode < 2) ?
3449                                 "enabled" : "disabled");
3450
3451         tpacpi_inputdev->open = &hotkey_inputdev_open;
3452         tpacpi_inputdev->close = &hotkey_inputdev_close;
3453
3454         hotkey_poll_setup_safe(true);
3455
3456         return 0;
3457
3458 err_exit:
3459         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3460         hotkey_dev_attributes = NULL;
3461
3462         return (res < 0)? res : 1;
3463 }
3464
3465 static bool hotkey_notify_hotkey(const u32 hkey,
3466                                  bool *send_acpi_ev,
3467                                  bool *ignore_acpi_ev)
3468 {
3469         /* 0x1000-0x1FFF: key presses */
3470         unsigned int scancode = hkey & 0xfff;
3471         *send_acpi_ev = true;
3472         *ignore_acpi_ev = false;
3473
3474         if (scancode > 0 && scancode < 0x21) {
3475                 scancode--;
3476                 if (!(hotkey_source_mask & (1 << scancode))) {
3477                         tpacpi_input_send_key_masked(scancode);
3478                         *send_acpi_ev = false;
3479                 } else {
3480                         *ignore_acpi_ev = true;
3481                 }
3482                 return true;
3483         }
3484         return false;
3485 }
3486
3487 static bool hotkey_notify_wakeup(const u32 hkey,
3488                                  bool *send_acpi_ev,
3489                                  bool *ignore_acpi_ev)
3490 {
3491         /* 0x2000-0x2FFF: Wakeup reason */
3492         *send_acpi_ev = true;
3493         *ignore_acpi_ev = false;
3494
3495         switch (hkey) {
3496         case TP_HKEY_EV_WKUP_S3_UNDOCK: /* suspend, undock */
3497         case TP_HKEY_EV_WKUP_S4_UNDOCK: /* hibernation, undock */
3498                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3499                 *ignore_acpi_ev = true;
3500                 break;
3501
3502         case TP_HKEY_EV_WKUP_S3_BAYEJ: /* suspend, bay eject */
3503         case TP_HKEY_EV_WKUP_S4_BAYEJ: /* hibernation, bay eject */
3504                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3505                 *ignore_acpi_ev = true;
3506                 break;
3507
3508         case TP_HKEY_EV_WKUP_S3_BATLOW: /* Battery on critical low level/S3 */
3509         case TP_HKEY_EV_WKUP_S4_BATLOW: /* Battery on critical low level/S4 */
3510                 printk(TPACPI_ALERT
3511                         "EMERGENCY WAKEUP: battery almost empty\n");
3512                 /* how to auto-heal: */
3513                 /* 2313: woke up from S3, go to S4/S5 */
3514                 /* 2413: woke up from S4, go to S5 */
3515                 break;
3516
3517         default:
3518                 return false;
3519         }
3520
3521         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3522                 printk(TPACPI_INFO
3523                        "woke up due to a hot-unplug "
3524                        "request...\n");
3525                 hotkey_wakeup_reason_notify_change();
3526         }
3527         return true;
3528 }
3529
3530 static bool hotkey_notify_usrevent(const u32 hkey,
3531                                  bool *send_acpi_ev,
3532                                  bool *ignore_acpi_ev)
3533 {
3534         /* 0x5000-0x5FFF: human interface helpers */
3535         *send_acpi_ev = true;
3536         *ignore_acpi_ev = false;
3537
3538         switch (hkey) {
3539         case TP_HKEY_EV_PEN_INSERTED:  /* X61t: tablet pen inserted into bay */
3540         case TP_HKEY_EV_PEN_REMOVED:   /* X61t: tablet pen removed from bay */
3541                 return true;
3542
3543         case TP_HKEY_EV_TABLET_TABLET:   /* X41t-X61t: tablet mode */
3544         case TP_HKEY_EV_TABLET_NOTEBOOK: /* X41t-X61t: normal mode */
3545                 tpacpi_input_send_tabletsw();
3546                 hotkey_tablet_mode_notify_change();
3547                 *send_acpi_ev = false;
3548                 return true;
3549
3550         case TP_HKEY_EV_LID_CLOSE:      /* Lid closed */
3551         case TP_HKEY_EV_LID_OPEN:       /* Lid opened */
3552         case TP_HKEY_EV_BRGHT_CHANGED:  /* brightness changed */
3553                 /* do not propagate these events */
3554                 *ignore_acpi_ev = true;
3555                 return true;
3556
3557         default:
3558                 return false;
3559         }
3560 }
3561
3562 static void thermal_dump_all_sensors(void);
3563
3564 static bool hotkey_notify_thermal(const u32 hkey,
3565                                  bool *send_acpi_ev,
3566                                  bool *ignore_acpi_ev)
3567 {
3568         bool known = true;
3569
3570         /* 0x6000-0x6FFF: thermal alarms */
3571         *send_acpi_ev = true;
3572         *ignore_acpi_ev = false;
3573
3574         switch (hkey) {
3575         case TP_HKEY_EV_THM_TABLE_CHANGED:
3576                 printk(TPACPI_INFO
3577                         "EC reports that Thermal Table has changed\n");
3578                 /* recommended action: do nothing, we don't have
3579                  * Lenovo ATM information */
3580                 return true;
3581         case TP_HKEY_EV_ALARM_BAT_HOT:
3582                 printk(TPACPI_CRIT
3583                         "THERMAL ALARM: battery is too hot!\n");
3584                 /* recommended action: warn user through gui */
3585                 break;
3586         case TP_HKEY_EV_ALARM_BAT_XHOT:
3587                 printk(TPACPI_ALERT
3588                         "THERMAL EMERGENCY: battery is extremely hot!\n");
3589                 /* recommended action: immediate sleep/hibernate */
3590                 break;
3591         case TP_HKEY_EV_ALARM_SENSOR_HOT:
3592                 printk(TPACPI_CRIT
3593                         "THERMAL ALARM: "
3594                         "a sensor reports something is too hot!\n");
3595                 /* recommended action: warn user through gui, that */
3596                 /* some internal component is too hot */
3597                 break;
3598         case TP_HKEY_EV_ALARM_SENSOR_XHOT:
3599                 printk(TPACPI_ALERT
3600                         "THERMAL EMERGENCY: "
3601                         "a sensor reports something is extremely hot!\n");
3602                 /* recommended action: immediate sleep/hibernate */
3603                 break;
3604         default:
3605                 printk(TPACPI_ALERT
3606                          "THERMAL ALERT: unknown thermal alarm received\n");
3607                 known = false;
3608         }
3609
3610         thermal_dump_all_sensors();
3611
3612         return known;
3613 }
3614
3615 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3616 {
3617         u32 hkey;
3618         bool send_acpi_ev;
3619         bool ignore_acpi_ev;
3620         bool known_ev;
3621
3622         if (event != 0x80) {
3623                 printk(TPACPI_ERR
3624                        "unknown HKEY notification event %d\n", event);
3625                 /* forward it to userspace, maybe it knows how to handle it */
3626                 acpi_bus_generate_netlink_event(
3627                                         ibm->acpi->device->pnp.device_class,
3628                                         dev_name(&ibm->acpi->device->dev),
3629                                         event, 0);
3630                 return;
3631         }
3632
3633         while (1) {
3634                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
3635                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
3636                         return;
3637                 }
3638
3639                 if (hkey == 0) {
3640                         /* queue empty */
3641                         return;
3642                 }
3643
3644                 send_acpi_ev = true;
3645                 ignore_acpi_ev = false;
3646
3647                 switch (hkey >> 12) {
3648                 case 1:
3649                         /* 0x1000-0x1FFF: key presses */
3650                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
3651                                                  &ignore_acpi_ev);
3652                         break;
3653                 case 2:
3654                         /* 0x2000-0x2FFF: Wakeup reason */
3655                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
3656                                                  &ignore_acpi_ev);
3657                         break;
3658                 case 3:
3659                         /* 0x3000-0x3FFF: bay-related wakeups */
3660                         switch (hkey) {
3661                         case TP_HKEY_EV_BAYEJ_ACK:
3662                                 hotkey_autosleep_ack = 1;
3663                                 printk(TPACPI_INFO
3664                                        "bay ejected\n");
3665                                 hotkey_wakeup_hotunplug_complete_notify_change();
3666                                 known_ev = true;
3667                                 break;
3668                         case TP_HKEY_EV_OPTDRV_EJ:
3669                                 /* FIXME: kick libata if SATA link offline */
3670                                 known_ev = true;
3671                                 break;
3672                         default:
3673                                 known_ev = false;
3674                         }
3675                         break;
3676                 case 4:
3677                         /* 0x4000-0x4FFF: dock-related wakeups */
3678                         if (hkey == TP_HKEY_EV_UNDOCK_ACK) {
3679                                 hotkey_autosleep_ack = 1;
3680                                 printk(TPACPI_INFO
3681                                        "undocked\n");
3682                                 hotkey_wakeup_hotunplug_complete_notify_change();
3683                                 known_ev = true;
3684                         } else {
3685                                 known_ev = false;
3686                         }
3687                         break;
3688                 case 5:
3689                         /* 0x5000-0x5FFF: human interface helpers */
3690                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
3691                                                  &ignore_acpi_ev);
3692                         break;
3693                 case 6:
3694                         /* 0x6000-0x6FFF: thermal alarms */
3695                         known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev,
3696                                                  &ignore_acpi_ev);
3697                         break;
3698                 case 7:
3699                         /* 0x7000-0x7FFF: misc */
3700                         if (tp_features.hotkey_wlsw &&
3701                                         hkey == TP_HKEY_EV_RFKILL_CHANGED) {
3702                                 tpacpi_send_radiosw_update();
3703                                 send_acpi_ev = 0;
3704                                 known_ev = true;
3705                                 break;
3706                         }
3707                         /* fallthrough to default */
3708                 default:
3709                         known_ev = false;
3710                 }
3711                 if (!known_ev) {
3712                         printk(TPACPI_NOTICE
3713                                "unhandled HKEY event 0x%04x\n", hkey);
3714                         printk(TPACPI_NOTICE
3715                                "please report the conditions when this "
3716                                "event happened to %s\n", TPACPI_MAIL);
3717                 }
3718
3719                 /* Legacy events */
3720                 if (!ignore_acpi_ev &&
3721                     (send_acpi_ev || hotkey_report_mode < 2)) {
3722                         acpi_bus_generate_proc_event(ibm->acpi->device,
3723                                                      event, hkey);
3724                 }
3725
3726                 /* netlink events */
3727                 if (!ignore_acpi_ev && send_acpi_ev) {
3728                         acpi_bus_generate_netlink_event(
3729                                         ibm->acpi->device->pnp.device_class,
3730                                         dev_name(&ibm->acpi->device->dev),
3731                                         event, hkey);
3732                 }
3733         }
3734 }
3735
3736 static void hotkey_suspend(pm_message_t state)
3737 {
3738         /* Do these on suspend, we get the events on early resume! */
3739         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
3740         hotkey_autosleep_ack = 0;
3741 }
3742
3743 static void hotkey_resume(void)
3744 {
3745         tpacpi_disable_brightness_delay();
3746
3747         if (hotkey_status_set(true) < 0 ||
3748             hotkey_mask_set(hotkey_acpi_mask) < 0)
3749                 printk(TPACPI_ERR
3750                        "error while attempting to reset the event "
3751                        "firmware interface\n");
3752
3753         tpacpi_send_radiosw_update();
3754         hotkey_tablet_mode_notify_change();
3755         hotkey_wakeup_reason_notify_change();
3756         hotkey_wakeup_hotunplug_complete_notify_change();
3757         hotkey_poll_setup_safe(false);
3758 }
3759
3760 /* procfs -------------------------------------------------------------- */
3761 static int hotkey_read(struct seq_file *m)
3762 {
3763         int res, status;
3764
3765         if (!tp_features.hotkey) {
3766                 seq_printf(m, "status:\t\tnot supported\n");
3767                 return 0;
3768         }
3769
3770         if (mutex_lock_killable(&hotkey_mutex))
3771                 return -ERESTARTSYS;
3772         res = hotkey_status_get(&status);
3773         if (!res)
3774                 res = hotkey_mask_get();
3775         mutex_unlock(&hotkey_mutex);
3776         if (res)
3777                 return res;
3778
3779         seq_printf(m, "status:\t\t%s\n", enabled(status, 0));
3780         if (hotkey_all_mask) {
3781                 seq_printf(m, "mask:\t\t0x%08x\n", hotkey_user_mask);
3782                 seq_printf(m, "commands:\tenable, disable, reset, <mask>\n");
3783         } else {
3784                 seq_printf(m, "mask:\t\tnot supported\n");
3785                 seq_printf(m, "commands:\tenable, disable, reset\n");
3786         }
3787
3788         return 0;
3789 }
3790
3791 static void hotkey_enabledisable_warn(bool enable)
3792 {
3793         tpacpi_log_usertask("procfs hotkey enable/disable");
3794         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
3795                         TPACPI_WARN
3796                         "hotkey enable/disable functionality has been "
3797                         "removed from the driver.  Hotkeys are always "
3798                         "enabled\n"))
3799                 printk(TPACPI_ERR
3800                         "Please remove the hotkey=enable module "
3801                         "parameter, it is deprecated.  Hotkeys are always "
3802                         "enabled\n");
3803 }
3804
3805 static int hotkey_write(char *buf)
3806 {
3807         int res;
3808         u32 mask;
3809         char *cmd;
3810
3811         if (!tp_features.hotkey)
3812                 return -ENODEV;
3813
3814         if (mutex_lock_killable(&hotkey_mutex))
3815                 return -ERESTARTSYS;
3816
3817         mask = hotkey_user_mask;
3818
3819         res = 0;
3820         while ((cmd = next_cmd(&buf))) {
3821                 if (strlencmp(cmd, "enable") == 0) {
3822                         hotkey_enabledisable_warn(1);
3823                 } else if (strlencmp(cmd, "disable") == 0) {
3824                         hotkey_enabledisable_warn(0);
3825                         res = -EPERM;
3826                 } else if (strlencmp(cmd, "reset") == 0) {
3827                         mask = (hotkey_all_mask | hotkey_source_mask)
3828                                 & ~hotkey_reserved_mask;
3829                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
3830                         /* mask set */
3831                 } else if (sscanf(cmd, "%x", &mask) == 1) {
3832                         /* mask set */
3833                 } else {
3834                         res = -EINVAL;
3835                         goto errexit;
3836                 }
3837         }
3838
3839         if (!res) {
3840                 tpacpi_disclose_usertask("procfs hotkey",
3841                         "set mask to 0x%08x\n", mask);
3842                 res = hotkey_user_mask_set(mask);
3843         }
3844
3845 errexit:
3846         mutex_unlock(&hotkey_mutex);
3847         return res;
3848 }
3849
3850 static const struct acpi_device_id ibm_htk_device_ids[] = {
3851         {TPACPI_ACPI_HKEY_HID, 0},
3852         {"", 0},
3853 };
3854
3855 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
3856         .hid = ibm_htk_device_ids,
3857         .notify = hotkey_notify,
3858         .handle = &hkey_handle,
3859         .type = ACPI_DEVICE_NOTIFY,
3860 };
3861
3862 static struct ibm_struct hotkey_driver_data = {
3863         .name = "hotkey",
3864         .read = hotkey_read,
3865         .write = hotkey_write,
3866         .exit = hotkey_exit,
3867         .resume = hotkey_resume,
3868         .suspend = hotkey_suspend,
3869         .acpi = &ibm_hotkey_acpidriver,
3870 };
3871
3872 /*************************************************************************
3873  * Bluetooth subdriver
3874  */
3875
3876 enum {
3877         /* ACPI GBDC/SBDC bits */
3878         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
3879         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
3880         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
3881                                                    off / last state */
3882 };
3883
3884 enum {
3885         /* ACPI \BLTH commands */
3886         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
3887         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
3888         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
3889         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
3890         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
3891 };
3892
3893 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
3894
3895 static int bluetooth_get_status(void)
3896 {
3897         int status;
3898
3899 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3900         if (dbg_bluetoothemul)
3901                 return (tpacpi_bluetooth_emulstate) ?
3902                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3903 #endif
3904
3905         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
3906                 return -EIO;
3907
3908         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
3909                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3910 }
3911
3912 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
3913 {
3914         int status;
3915
3916         vdbg_printk(TPACPI_DBG_RFKILL,
3917                 "will attempt to %s bluetooth\n",
3918                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3919
3920 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3921         if (dbg_bluetoothemul) {
3922                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
3923                 return 0;
3924         }
3925 #endif
3926
3927         /* We make sure to keep TP_ACPI_BLUETOOTH_RESUMECTRL off */
3928         status = TP_ACPI_BLUETOOTH_RESUMECTRL;
3929         if (state == TPACPI_RFK_RADIO_ON)
3930                 status |= TP_ACPI_BLUETOOTH_RADIOSSW;
3931
3932         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
3933                 return -EIO;
3934
3935         return 0;
3936 }
3937
3938 /* sysfs bluetooth enable ---------------------------------------------- */
3939 static ssize_t bluetooth_enable_show(struct device *dev,
3940                            struct device_attribute *attr,
3941                            char *buf)
3942 {
3943         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
3944                         attr, buf);
3945 }
3946
3947 static ssize_t bluetooth_enable_store(struct device *dev,
3948                             struct device_attribute *attr,
3949                             const char *buf, size_t count)
3950 {
3951         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
3952                                 attr, buf, count);
3953 }
3954
3955 static struct device_attribute dev_attr_bluetooth_enable =
3956         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
3957                 bluetooth_enable_show, bluetooth_enable_store);
3958
3959 /* --------------------------------------------------------------------- */
3960
3961 static struct attribute *bluetooth_attributes[] = {
3962         &dev_attr_bluetooth_enable.attr,
3963         NULL
3964 };
3965
3966 static const struct attribute_group bluetooth_attr_group = {
3967         .attrs = bluetooth_attributes,
3968 };
3969
3970 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
3971         .get_status = bluetooth_get_status,
3972         .set_status = bluetooth_set_status,
3973 };
3974
3975 static void bluetooth_shutdown(void)
3976 {
3977         /* Order firmware to save current state to NVRAM */
3978         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3979                         TP_ACPI_BLTH_SAVE_STATE))
3980                 printk(TPACPI_NOTICE
3981                         "failed to save bluetooth state to NVRAM\n");
3982         else
3983                 vdbg_printk(TPACPI_DBG_RFKILL,
3984                         "bluestooth state saved to NVRAM\n");
3985 }
3986
3987 static void bluetooth_exit(void)
3988 {
3989         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3990                         &bluetooth_attr_group);
3991
3992         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3993
3994         bluetooth_shutdown();
3995 }
3996
3997 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3998 {
3999         int res;
4000         int status = 0;
4001
4002         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4003                         "initializing bluetooth subdriver\n");
4004
4005         TPACPI_ACPIHANDLE_INIT(hkey);
4006
4007         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4008            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
4009         tp_features.bluetooth = hkey_handle &&
4010             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
4011
4012         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4013                 "bluetooth is %s, status 0x%02x\n",
4014                 str_supported(tp_features.bluetooth),
4015                 status);
4016
4017 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4018         if (dbg_bluetoothemul) {
4019                 tp_features.bluetooth = 1;
4020                 printk(TPACPI_INFO
4021                         "bluetooth switch emulation enabled\n");
4022         } else
4023 #endif
4024         if (tp_features.bluetooth &&
4025             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
4026                 /* no bluetooth hardware present in system */
4027                 tp_features.bluetooth = 0;
4028                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4029                            "bluetooth hardware not installed\n");
4030         }
4031
4032         if (!tp_features.bluetooth)
4033                 return 1;
4034
4035         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
4036                                 &bluetooth_tprfk_ops,
4037                                 RFKILL_TYPE_BLUETOOTH,
4038                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
4039                                 true);
4040         if (res)
4041                 return res;
4042
4043         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4044                                 &bluetooth_attr_group);
4045         if (res) {
4046                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
4047                 return res;
4048         }
4049
4050         return 0;
4051 }
4052
4053 /* procfs -------------------------------------------------------------- */
4054 static int bluetooth_read(struct seq_file *m)
4055 {
4056         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, m);
4057 }
4058
4059 static int bluetooth_write(char *buf)
4060 {
4061         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
4062 }
4063
4064 static struct ibm_struct bluetooth_driver_data = {
4065         .name = "bluetooth",
4066         .read = bluetooth_read,
4067         .write = bluetooth_write,
4068         .exit = bluetooth_exit,
4069         .shutdown = bluetooth_shutdown,
4070 };
4071
4072 /*************************************************************************
4073  * Wan subdriver
4074  */
4075
4076 enum {
4077         /* ACPI GWAN/SWAN bits */
4078         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
4079         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
4080         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
4081                                                    off / last state */
4082 };
4083
4084 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
4085
4086 static int wan_get_status(void)
4087 {
4088         int status;
4089
4090 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4091         if (dbg_wwanemul)
4092                 return (tpacpi_wwan_emulstate) ?
4093                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4094 #endif
4095
4096         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
4097                 return -EIO;
4098
4099         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
4100                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4101 }
4102
4103 static int wan_set_status(enum tpacpi_rfkill_state state)
4104 {
4105         int status;
4106
4107         vdbg_printk(TPACPI_DBG_RFKILL,
4108                 "will attempt to %s wwan\n",
4109                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4110
4111 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4112         if (dbg_wwanemul) {
4113                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
4114                 return 0;
4115         }
4116 #endif
4117
4118         /* We make sure to set TP_ACPI_WANCARD_RESUMECTRL */
4119         status = TP_ACPI_WANCARD_RESUMECTRL;
4120         if (state == TPACPI_RFK_RADIO_ON)
4121                 status |= TP_ACPI_WANCARD_RADIOSSW;
4122
4123         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
4124                 return -EIO;
4125
4126         return 0;
4127 }
4128
4129 /* sysfs wan enable ---------------------------------------------------- */
4130 static ssize_t wan_enable_show(struct device *dev,
4131                            struct device_attribute *attr,
4132                            char *buf)
4133 {
4134         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
4135                         attr, buf);
4136 }
4137
4138 static ssize_t wan_enable_store(struct device *dev,
4139                             struct device_attribute *attr,
4140                             const char *buf, size_t count)
4141 {
4142         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
4143                         attr, buf, count);
4144 }
4145
4146 static struct device_attribute dev_attr_wan_enable =
4147         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
4148                 wan_enable_show, wan_enable_store);
4149
4150 /* --------------------------------------------------------------------- */
4151
4152 static struct attribute *wan_attributes[] = {
4153         &dev_attr_wan_enable.attr,
4154         NULL
4155 };
4156
4157 static const struct attribute_group wan_attr_group = {
4158         .attrs = wan_attributes,
4159 };
4160
4161 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
4162         .get_status = wan_get_status,
4163         .set_status = wan_set_status,
4164 };
4165
4166 static void wan_shutdown(void)
4167 {
4168         /* Order firmware to save current state to NVRAM */
4169         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
4170                         TP_ACPI_WGSV_SAVE_STATE))
4171                 printk(TPACPI_NOTICE
4172                         "failed to save WWAN state to NVRAM\n");
4173         else
4174                 vdbg_printk(TPACPI_DBG_RFKILL,
4175                         "WWAN state saved to NVRAM\n");
4176 }
4177
4178 static void wan_exit(void)
4179 {
4180         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4181                 &wan_attr_group);
4182
4183         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4184
4185         wan_shutdown();
4186 }
4187
4188 static int __init wan_init(struct ibm_init_struct *iibm)
4189 {
4190         int res;
4191         int status = 0;
4192
4193         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4194                         "initializing wan subdriver\n");
4195
4196         TPACPI_ACPIHANDLE_INIT(hkey);
4197
4198         tp_features.wan = hkey_handle &&
4199             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
4200
4201         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4202                 "wan is %s, status 0x%02x\n",
4203                 str_supported(tp_features.wan),
4204                 status);
4205
4206 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4207         if (dbg_wwanemul) {
4208                 tp_features.wan = 1;
4209                 printk(TPACPI_INFO
4210                         "wwan switch emulation enabled\n");
4211         } else
4212 #endif
4213         if (tp_features.wan &&
4214             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
4215                 /* no wan hardware present in system */
4216                 tp_features.wan = 0;
4217                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4218                            "wan hardware not installed\n");
4219         }
4220
4221         if (!tp_features.wan)
4222                 return 1;
4223
4224         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
4225                                 &wan_tprfk_ops,
4226                                 RFKILL_TYPE_WWAN,
4227                                 TPACPI_RFK_WWAN_SW_NAME,
4228                                 true);
4229         if (res)
4230                 return res;
4231
4232         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4233                                 &wan_attr_group);
4234
4235         if (res) {
4236                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4237                 return res;
4238         }
4239
4240         return 0;
4241 }
4242
4243 /* procfs -------------------------------------------------------------- */
4244 static int wan_read(struct seq_file *m)
4245 {
4246         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, m);
4247 }
4248
4249 static int wan_write(char *buf)
4250 {
4251         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
4252 }
4253
4254 static struct ibm_struct wan_driver_data = {
4255         .name = "wan",
4256         .read = wan_read,
4257         .write = wan_write,
4258         .exit = wan_exit,
4259         .shutdown = wan_shutdown,
4260 };
4261
4262 /*************************************************************************
4263  * UWB subdriver
4264  */
4265
4266 enum {
4267         /* ACPI GUWB/SUWB bits */
4268         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
4269         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
4270 };
4271
4272 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
4273
4274 static int uwb_get_status(void)
4275 {
4276         int status;
4277
4278 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4279         if (dbg_uwbemul)
4280                 return (tpacpi_uwb_emulstate) ?
4281                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4282 #endif
4283
4284         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
4285                 return -EIO;
4286
4287         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
4288                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4289 }
4290
4291 static int uwb_set_status(enum tpacpi_rfkill_state state)
4292 {
4293         int status;
4294
4295         vdbg_printk(TPACPI_DBG_RFKILL,
4296                 "will attempt to %s UWB\n",
4297                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4298
4299 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4300         if (dbg_uwbemul) {
4301                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
4302                 return 0;
4303         }
4304 #endif
4305
4306         if (state == TPACPI_RFK_RADIO_ON)
4307                 status = TP_ACPI_UWB_RADIOSSW;
4308         else
4309                 status = 0;
4310
4311         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
4312                 return -EIO;
4313
4314         return 0;
4315 }
4316
4317 /* --------------------------------------------------------------------- */
4318
4319 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
4320         .get_status = uwb_get_status,
4321         .set_status = uwb_set_status,
4322 };
4323
4324 static void uwb_exit(void)
4325 {
4326         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
4327 }
4328
4329 static int __init uwb_init(struct ibm_init_struct *iibm)
4330 {
4331         int res;
4332         int status = 0;
4333
4334         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4335                         "initializing uwb subdriver\n");
4336
4337         TPACPI_ACPIHANDLE_INIT(hkey);
4338
4339         tp_features.uwb = hkey_handle &&
4340             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
4341
4342         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4343                 "uwb is %s, status 0x%02x\n",
4344                 str_supported(tp_features.uwb),
4345                 status);
4346
4347 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4348         if (dbg_uwbemul) {
4349                 tp_features.uwb = 1;
4350                 printk(TPACPI_INFO
4351                         "uwb switch emulation enabled\n");
4352         } else
4353 #endif
4354         if (tp_features.uwb &&
4355             !(status & TP_ACPI_UWB_HWPRESENT)) {
4356                 /* no uwb hardware present in system */
4357                 tp_features.uwb = 0;
4358                 dbg_printk(TPACPI_DBG_INIT,
4359                            "uwb hardware not installed\n");
4360         }
4361
4362         if (!tp_features.uwb)
4363                 return 1;
4364
4365         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
4366                                 &uwb_tprfk_ops,
4367                                 RFKILL_TYPE_UWB,
4368                                 TPACPI_RFK_UWB_SW_NAME,
4369                                 false);
4370         return res;
4371 }
4372
4373 static struct ibm_struct uwb_driver_data = {
4374         .name = "uwb",
4375         .exit = uwb_exit,
4376         .flags.experimental = 1,
4377 };
4378
4379 /*************************************************************************
4380  * Video subdriver
4381  */
4382
4383 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
4384
4385 enum video_access_mode {
4386         TPACPI_VIDEO_NONE = 0,
4387         TPACPI_VIDEO_570,       /* 570 */
4388         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
4389         TPACPI_VIDEO_NEW,       /* all others */
4390 };
4391
4392 enum {  /* video status flags, based on VIDEO_570 */
4393         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
4394         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
4395         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
4396 };
4397
4398 enum {  /* TPACPI_VIDEO_570 constants */
4399         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
4400         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
4401                                                  * video_status_flags */
4402         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
4403         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
4404 };
4405
4406 static enum video_access_mode video_supported;
4407 static int video_orig_autosw;
4408
4409 static int video_autosw_get(void);
4410 static int video_autosw_set(int enable);
4411
4412 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
4413
4414 static int __init video_init(struct ibm_init_struct *iibm)
4415 {
4416         int ivga;
4417
4418         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
4419
4420         TPACPI_ACPIHANDLE_INIT(vid);
4421         TPACPI_ACPIHANDLE_INIT(vid2);
4422
4423         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
4424                 /* G41, assume IVGA doesn't change */
4425                 vid_handle = vid2_handle;
4426
4427         if (!vid_handle)
4428                 /* video switching not supported on R30, R31 */
4429                 video_supported = TPACPI_VIDEO_NONE;
4430         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
4431                 /* 570 */
4432                 video_supported = TPACPI_VIDEO_570;
4433         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
4434                 /* 600e/x, 770e, 770x */
4435                 video_supported = TPACPI_VIDEO_770;
4436         else
4437                 /* all others */
4438                 video_supported = TPACPI_VIDEO_NEW;
4439
4440         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
4441                 str_supported(video_supported != TPACPI_VIDEO_NONE),
4442                 video_supported);
4443
4444         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
4445 }
4446
4447 static void video_exit(void)
4448 {
4449         dbg_printk(TPACPI_DBG_EXIT,
4450                    "restoring original video autoswitch mode\n");
4451         if (video_autosw_set(video_orig_autosw))
4452                 printk(TPACPI_ERR "error while trying to restore original "
4453                         "video autoswitch mode\n");
4454 }
4455
4456 static int video_outputsw_get(void)
4457 {
4458         int status = 0;
4459         int i;
4460
4461         switch (video_supported) {
4462         case TPACPI_VIDEO_570:
4463                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4464                                  TP_ACPI_VIDEO_570_PHSCMD))
4465                         return -EIO;
4466                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4467                 break;
4468         case TPACPI_VIDEO_770:
4469                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4470                         return -EIO;
4471                 if (i)
4472                         status |= TP_ACPI_VIDEO_S_LCD;
4473                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4474                         return -EIO;
4475                 if (i)
4476                         status |= TP_ACPI_VIDEO_S_CRT;
4477                 break;
4478         case TPACPI_VIDEO_NEW:
4479                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4480                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4481                         return -EIO;
4482                 if (i)
4483                         status |= TP_ACPI_VIDEO_S_CRT;
4484
4485                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4486                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4487                         return -EIO;
4488                 if (i)
4489                         status |= TP_ACPI_VIDEO_S_LCD;
4490                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4491                         return -EIO;
4492                 if (i)
4493                         status |= TP_ACPI_VIDEO_S_DVI;
4494                 break;
4495         default:
4496                 return -ENOSYS;
4497         }
4498
4499         return status;
4500 }
4501
4502 static int video_outputsw_set(int status)
4503 {
4504         int autosw;
4505         int res = 0;
4506
4507         switch (video_supported) {
4508         case TPACPI_VIDEO_570:
4509                 res = acpi_evalf(NULL, NULL,
4510                                  "\\_SB.PHS2", "vdd",
4511                                  TP_ACPI_VIDEO_570_PHS2CMD,
4512                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4513                 break;
4514         case TPACPI_VIDEO_770:
4515                 autosw = video_autosw_get();
4516                 if (autosw < 0)
4517                         return autosw;
4518
4519                 res = video_autosw_set(1);
4520                 if (res)
4521                         return res;
4522                 res = acpi_evalf(vid_handle, NULL,
4523                                  "ASWT", "vdd", status * 0x100, 0);
4524                 if (!autosw && video_autosw_set(autosw)) {
4525                         printk(TPACPI_ERR
4526                                "video auto-switch left enabled due to error\n");
4527                         return -EIO;
4528                 }
4529                 break;
4530         case TPACPI_VIDEO_NEW:
4531                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4532                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4533                 break;
4534         default:
4535                 return -ENOSYS;
4536         }
4537
4538         return (res)? 0 : -EIO;
4539 }
4540
4541 static int video_autosw_get(void)
4542 {
4543         int autosw = 0;
4544
4545         switch (video_supported) {
4546         case TPACPI_VIDEO_570:
4547                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4548                         return -EIO;
4549                 break;
4550         case TPACPI_VIDEO_770:
4551         case TPACPI_VIDEO_NEW:
4552                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4553                         return -EIO;
4554                 break;
4555         default:
4556                 return -ENOSYS;
4557         }
4558
4559         return autosw & 1;
4560 }
4561
4562 static int video_autosw_set(int enable)
4563 {
4564         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
4565                 return -EIO;
4566         return 0;
4567 }
4568
4569 static int video_outputsw_cycle(void)
4570 {
4571         int autosw = video_autosw_get();
4572         int res;
4573
4574         if (autosw < 0)
4575                 return autosw;
4576
4577         switch (video_supported) {
4578         case TPACPI_VIDEO_570:
4579                 res = video_autosw_set(1);
4580                 if (res)
4581                         return res;
4582                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4583                 break;
4584         case TPACPI_VIDEO_770:
4585         case TPACPI_VIDEO_NEW:
4586                 res = video_autosw_set(1);
4587                 if (res)
4588                         return res;
4589                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4590                 break;
4591         default:
4592                 return -ENOSYS;
4593         }
4594         if (!autosw && video_autosw_set(autosw)) {
4595                 printk(TPACPI_ERR
4596                        "video auto-switch left enabled due to error\n");
4597                 return -EIO;
4598         }
4599
4600         return (res)? 0 : -EIO;
4601 }
4602
4603 static int video_expand_toggle(void)
4604 {
4605         switch (video_supported) {
4606         case TPACPI_VIDEO_570:
4607                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
4608                         0 : -EIO;
4609         case TPACPI_VIDEO_770:
4610                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
4611                         0 : -EIO;
4612         case TPACPI_VIDEO_NEW:
4613                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
4614                         0 : -EIO;
4615         default:
4616                 return -ENOSYS;
4617         }
4618         /* not reached */
4619 }
4620
4621 static int video_read(struct seq_file *m)
4622 {
4623         int status, autosw;
4624
4625         if (video_supported == TPACPI_VIDEO_NONE) {
4626                 seq_printf(m, "status:\t\tnot supported\n");
4627                 return 0;
4628         }
4629
4630         status = video_outputsw_get();
4631         if (status < 0)
4632                 return status;
4633
4634         autosw = video_autosw_get();
4635         if (autosw < 0)
4636                 return autosw;
4637
4638         seq_printf(m, "status:\t\tsupported\n");
4639         seq_printf(m, "lcd:\t\t%s\n", enabled(status, 0));
4640         seq_printf(m, "crt:\t\t%s\n", enabled(status, 1));
4641         if (video_supported == TPACPI_VIDEO_NEW)
4642                 seq_printf(m, "dvi:\t\t%s\n", enabled(status, 3));
4643         seq_printf(m, "auto:\t\t%s\n", enabled(autosw, 0));
4644         seq_printf(m, "commands:\tlcd_enable, lcd_disable\n");
4645         seq_printf(m, "commands:\tcrt_enable, crt_disable\n");
4646         if (video_supported == TPACPI_VIDEO_NEW)
4647                 seq_printf(m, "commands:\tdvi_enable, dvi_disable\n");
4648         seq_printf(m, "commands:\tauto_enable, auto_disable\n");
4649         seq_printf(m, "commands:\tvideo_switch, expand_toggle\n");
4650
4651         return 0;
4652 }
4653
4654 static int video_write(char *buf)
4655 {
4656         char *cmd;
4657         int enable, disable, status;
4658         int res;
4659
4660         if (video_supported == TPACPI_VIDEO_NONE)
4661                 return -ENODEV;
4662
4663         enable = 0;
4664         disable = 0;
4665
4666         while ((cmd = next_cmd(&buf))) {
4667                 if (strlencmp(cmd, "lcd_enable") == 0) {
4668                         enable |= TP_ACPI_VIDEO_S_LCD;
4669                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
4670                         disable |= TP_ACPI_VIDEO_S_LCD;
4671                 } else if (strlencmp(cmd, "crt_enable") == 0) {
4672                         enable |= TP_ACPI_VIDEO_S_CRT;
4673                 } else if (strlencmp(cmd, "crt_disable") == 0) {
4674                         disable |= TP_ACPI_VIDEO_S_CRT;
4675                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4676                            strlencmp(cmd, "dvi_enable") == 0) {
4677                         enable |= TP_ACPI_VIDEO_S_DVI;
4678                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4679                            strlencmp(cmd, "dvi_disable") == 0) {
4680                         disable |= TP_ACPI_VIDEO_S_DVI;
4681                 } else if (strlencmp(cmd, "auto_enable") == 0) {
4682                         res = video_autosw_set(1);
4683                         if (res)
4684                                 return res;
4685                 } else if (strlencmp(cmd, "auto_disable") == 0) {
4686                         res = video_autosw_set(0);
4687                         if (res)
4688                                 return res;
4689                 } else if (strlencmp(cmd, "video_switch") == 0) {
4690                         res = video_outputsw_cycle();
4691                         if (res)
4692                                 return res;
4693                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
4694                         res = video_expand_toggle();
4695                         if (res)
4696                                 return res;
4697                 } else
4698                         return -EINVAL;
4699         }
4700
4701         if (enable || disable) {
4702                 status = video_outputsw_get();
4703                 if (status < 0)
4704                         return status;
4705                 res = video_outputsw_set((status & ~disable) | enable);
4706                 if (res)
4707                         return res;
4708         }
4709
4710         return 0;
4711 }
4712
4713 static struct ibm_struct video_driver_data = {
4714         .name = "video",
4715         .read = video_read,
4716         .write = video_write,
4717         .exit = video_exit,
4718 };
4719
4720 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
4721
4722 /*************************************************************************
4723  * Light (thinklight) subdriver
4724  */
4725
4726 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
4727 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
4728
4729 static int light_get_status(void)
4730 {
4731         int status = 0;
4732
4733         if (tp_features.light_status) {
4734                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
4735                         return -EIO;
4736                 return (!!status);
4737         }
4738
4739         return -ENXIO;
4740 }
4741
4742 static int light_set_status(int status)
4743 {
4744         int rc;
4745
4746         if (tp_features.light) {
4747                 if (cmos_handle) {
4748                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
4749                                         (status)?
4750                                                 TP_CMOS_THINKLIGHT_ON :
4751                                                 TP_CMOS_THINKLIGHT_OFF);
4752                 } else {
4753                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
4754                                         (status)? 1 : 0);
4755                 }
4756                 return (rc)? 0 : -EIO;
4757         }
4758
4759         return -ENXIO;
4760 }
4761
4762 static void light_set_status_worker(struct work_struct *work)
4763 {
4764         struct tpacpi_led_classdev *data =
4765                         container_of(work, struct tpacpi_led_classdev, work);
4766
4767         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4768                 light_set_status((data->new_state != TPACPI_LED_OFF));
4769 }
4770
4771 static void light_sysfs_set(struct led_classdev *led_cdev,
4772                         enum led_brightness brightness)
4773 {
4774         struct tpacpi_led_classdev *data =
4775                 container_of(led_cdev,
4776                              struct tpacpi_led_classdev,
4777                              led_classdev);
4778         data->new_state = (brightness != LED_OFF) ?
4779                                 TPACPI_LED_ON : TPACPI_LED_OFF;
4780         queue_work(tpacpi_wq, &data->work);
4781 }
4782
4783 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
4784 {
4785         return (light_get_status() == 1)? LED_FULL : LED_OFF;
4786 }
4787
4788 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
4789         .led_classdev = {
4790                 .name           = "tpacpi::thinklight",
4791                 .brightness_set = &light_sysfs_set,
4792                 .brightness_get = &light_sysfs_get,
4793         }
4794 };
4795
4796 static int __init light_init(struct ibm_init_struct *iibm)
4797 {
4798         int rc;
4799
4800         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
4801
4802         TPACPI_ACPIHANDLE_INIT(ledb);
4803         TPACPI_ACPIHANDLE_INIT(lght);
4804         TPACPI_ACPIHANDLE_INIT(cmos);
4805         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
4806
4807         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
4808         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
4809
4810         if (tp_features.light)
4811                 /* light status not supported on
4812                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
4813                 tp_features.light_status =
4814                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
4815
4816         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4817                 str_supported(tp_features.light),
4818                 str_supported(tp_features.light_status));
4819
4820         if (!tp_features.light)
4821                 return 1;
4822
4823         rc = led_classdev_register(&tpacpi_pdev->dev,
4824                                    &tpacpi_led_thinklight.led_classdev);
4825
4826         if (rc < 0) {
4827                 tp_features.light = 0;
4828                 tp_features.light_status = 0;
4829         } else  {
4830                 rc = 0;
4831         }
4832
4833         return rc;
4834 }
4835
4836 static void light_exit(void)
4837 {
4838         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4839         if (work_pending(&tpacpi_led_thinklight.work))
4840                 flush_workqueue(tpacpi_wq);
4841 }
4842
4843 static int light_read(struct seq_file *m)
4844 {
4845         int status;
4846
4847         if (!tp_features.light) {
4848                 seq_printf(m, "status:\t\tnot supported\n");
4849         } else if (!tp_features.light_status) {
4850                 seq_printf(m, "status:\t\tunknown\n");
4851                 seq_printf(m, "commands:\ton, off\n");
4852         } else {
4853                 status = light_get_status();
4854                 if (status < 0)
4855                         return status;
4856                 seq_printf(m, "status:\t\t%s\n", onoff(status, 0));
4857                 seq_printf(m, "commands:\ton, off\n");
4858         }
4859
4860         return 0;
4861 }
4862
4863 static int light_write(char *buf)
4864 {
4865         char *cmd;
4866         int newstatus = 0;
4867
4868         if (!tp_features.light)
4869                 return -ENODEV;
4870
4871         while ((cmd = next_cmd(&buf))) {
4872                 if (strlencmp(cmd, "on") == 0) {
4873                         newstatus = 1;
4874                 } else if (strlencmp(cmd, "off") == 0) {
4875                         newstatus = 0;
4876                 } else
4877                         return -EINVAL;
4878         }
4879
4880         return light_set_status(newstatus);
4881 }
4882
4883 static struct ibm_struct light_driver_data = {
4884         .name = "light",
4885         .read = light_read,
4886         .write = light_write,
4887         .exit = light_exit,
4888 };
4889
4890 /*************************************************************************
4891  * CMOS subdriver
4892  */
4893
4894 /* sysfs cmos_command -------------------------------------------------- */
4895 static ssize_t cmos_command_store(struct device *dev,
4896                             struct device_attribute *attr,
4897                             const char *buf, size_t count)
4898 {
4899         unsigned long cmos_cmd;
4900         int res;
4901
4902         if (parse_strtoul(buf, 21, &cmos_cmd))
4903                 return -EINVAL;
4904
4905         res = issue_thinkpad_cmos_command(cmos_cmd);
4906         return (res)? res : count;
4907 }
4908
4909 static struct device_attribute dev_attr_cmos_command =
4910         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4911
4912 /* --------------------------------------------------------------------- */
4913
4914 static int __init cmos_init(struct ibm_init_struct *iibm)
4915 {
4916         int res;
4917
4918         vdbg_printk(TPACPI_DBG_INIT,
4919                 "initializing cmos commands subdriver\n");
4920
4921         TPACPI_ACPIHANDLE_INIT(cmos);
4922
4923         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4924                 str_supported(cmos_handle != NULL));
4925
4926         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4927         if (res)
4928                 return res;
4929
4930         return (cmos_handle)? 0 : 1;
4931 }
4932
4933 static void cmos_exit(void)
4934 {
4935         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4936 }
4937
4938 static int cmos_read(struct seq_file *m)
4939 {
4940         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4941            R30, R31, T20-22, X20-21 */
4942         if (!cmos_handle)
4943                 seq_printf(m, "status:\t\tnot supported\n");
4944         else {
4945                 seq_printf(m, "status:\t\tsupported\n");
4946                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-21)\n");
4947         }
4948
4949         return 0;
4950 }
4951
4952 static int cmos_write(char *buf)
4953 {
4954         char *cmd;
4955         int cmos_cmd, res;
4956
4957         while ((cmd = next_cmd(&buf))) {
4958                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4959                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4960                         /* cmos_cmd set */
4961                 } else
4962                         return -EINVAL;
4963
4964                 res = issue_thinkpad_cmos_command(cmos_cmd);
4965                 if (res)
4966                         return res;
4967         }
4968
4969         return 0;
4970 }
4971
4972 static struct ibm_struct cmos_driver_data = {
4973         .name = "cmos",
4974         .read = cmos_read,
4975         .write = cmos_write,
4976         .exit = cmos_exit,
4977 };
4978
4979 /*************************************************************************
4980  * LED subdriver
4981  */
4982
4983 enum led_access_mode {
4984         TPACPI_LED_NONE = 0,
4985         TPACPI_LED_570, /* 570 */
4986         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4987         TPACPI_LED_NEW, /* all others */
4988 };
4989
4990 enum {  /* For TPACPI_LED_OLD */
4991         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4992         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4993         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4994 };
4995
4996 static enum led_access_mode led_supported;
4997
4998 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4999            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
5000                                 /* T20-22, X20-21 */
5001            "LED",               /* all others */
5002            );                   /* R30, R31 */
5003
5004 #define TPACPI_LED_NUMLEDS 16
5005 static struct tpacpi_led_classdev *tpacpi_leds;
5006 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
5007 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
5008         /* there's a limit of 19 chars + NULL before 2.6.26 */
5009         "tpacpi::power",
5010         "tpacpi:orange:batt",
5011         "tpacpi:green:batt",
5012         "tpacpi::dock_active",
5013         "tpacpi::bay_active",
5014         "tpacpi::dock_batt",
5015         "tpacpi::unknown_led",
5016         "tpacpi::standby",
5017         "tpacpi::dock_status1",
5018         "tpacpi::dock_status2",
5019         "tpacpi::unknown_led2",
5020         "tpacpi::unknown_led3",
5021         "tpacpi::thinkvantage",
5022 };
5023 #define TPACPI_SAFE_LEDS        0x1081U
5024
5025 static inline bool tpacpi_is_led_restricted(const unsigned int led)
5026 {
5027 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5028         return false;
5029 #else
5030         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
5031 #endif
5032 }
5033
5034 static int led_get_status(const unsigned int led)
5035 {
5036         int status;
5037         enum led_status_t led_s;
5038
5039         switch (led_supported) {
5040         case TPACPI_LED_570:
5041                 if (!acpi_evalf(ec_handle,
5042                                 &status, "GLED", "dd", 1 << led))
5043                         return -EIO;
5044                 led_s = (status == 0)?
5045                                 TPACPI_LED_OFF :
5046                                 ((status == 1)?
5047                                         TPACPI_LED_ON :
5048                                         TPACPI_LED_BLINK);
5049                 tpacpi_led_state_cache[led] = led_s;
5050                 return led_s;
5051         default:
5052                 return -ENXIO;
5053         }
5054
5055         /* not reached */
5056 }
5057
5058 static int led_set_status(const unsigned int led,
5059                           const enum led_status_t ledstatus)
5060 {
5061         /* off, on, blink. Index is led_status_t */
5062         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
5063         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
5064
5065         int rc = 0;
5066
5067         switch (led_supported) {
5068         case TPACPI_LED_570:
5069                 /* 570 */
5070                 if (unlikely(led > 7))
5071                         return -EINVAL;
5072                 if (unlikely(tpacpi_is_led_restricted(led)))
5073                         return -EPERM;
5074                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5075                                 (1 << led), led_sled_arg1[ledstatus]))
5076                         rc = -EIO;
5077                 break;
5078         case TPACPI_LED_OLD:
5079                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
5080                 if (unlikely(led > 7))
5081                         return -EINVAL;
5082                 if (unlikely(tpacpi_is_led_restricted(led)))
5083                         return -EPERM;
5084                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
5085                 if (rc >= 0)
5086                         rc = ec_write(TPACPI_LED_EC_HLBL,
5087                                       (ledstatus == TPACPI_LED_BLINK) << led);
5088                 if (rc >= 0)
5089                         rc = ec_write(TPACPI_LED_EC_HLCL,
5090                                       (ledstatus != TPACPI_LED_OFF) << led);
5091                 break;
5092         case TPACPI_LED_NEW:
5093                 /* all others */
5094                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
5095                         return -EINVAL;
5096                 if (unlikely(tpacpi_is_led_restricted(led)))
5097                         return -EPERM;
5098                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5099                                 led, led_led_arg1[ledstatus]))
5100                         rc = -EIO;
5101                 break;
5102         default:
5103                 rc = -ENXIO;
5104         }
5105
5106         if (!rc)
5107                 tpacpi_led_state_cache[led] = ledstatus;
5108
5109         return rc;
5110 }
5111
5112 static void led_set_status_worker(struct work_struct *work)
5113 {
5114         struct tpacpi_led_classdev *data =
5115                 container_of(work, struct tpacpi_led_classdev, work);
5116
5117         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
5118                 led_set_status(data->led, data->new_state);
5119 }
5120
5121 static void led_sysfs_set(struct led_classdev *led_cdev,
5122                         enum led_brightness brightness)
5123 {
5124         struct tpacpi_led_classdev *data = container_of(led_cdev,
5125                              struct tpacpi_led_classdev, led_classdev);
5126
5127         if (brightness == LED_OFF)
5128                 data->new_state = TPACPI_LED_OFF;
5129         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
5130                 data->new_state = TPACPI_LED_ON;
5131         else
5132                 data->new_state = TPACPI_LED_BLINK;
5133
5134         queue_work(tpacpi_wq, &data->work);
5135 }
5136
5137 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
5138                         unsigned long *delay_on, unsigned long *delay_off)
5139 {
5140         struct tpacpi_led_classdev *data = container_of(led_cdev,
5141                              struct tpacpi_led_classdev, led_classdev);
5142
5143         /* Can we choose the flash rate? */
5144         if (*delay_on == 0 && *delay_off == 0) {
5145                 /* yes. set them to the hardware blink rate (1 Hz) */
5146                 *delay_on = 500; /* ms */
5147                 *delay_off = 500; /* ms */
5148         } else if ((*delay_on != 500) || (*delay_off != 500))
5149                 return -EINVAL;
5150
5151         data->new_state = TPACPI_LED_BLINK;
5152         queue_work(tpacpi_wq, &data->work);
5153
5154         return 0;
5155 }
5156
5157 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5158 {
5159         int rc;
5160
5161         struct tpacpi_led_classdev *data = container_of(led_cdev,
5162                              struct tpacpi_led_classdev, led_classdev);
5163
5164         rc = led_get_status(data->led);
5165
5166         if (rc == TPACPI_LED_OFF || rc < 0)
5167                 rc = LED_OFF;   /* no error handling in led class :( */
5168         else
5169                 rc = LED_FULL;
5170
5171         return rc;
5172 }
5173
5174 static void led_exit(void)
5175 {
5176         unsigned int i;
5177
5178         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5179                 if (tpacpi_leds[i].led_classdev.name)
5180                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5181         }
5182
5183         kfree(tpacpi_leds);
5184 }
5185
5186 static int __init tpacpi_init_led(unsigned int led)
5187 {
5188         int rc;
5189
5190         tpacpi_leds[led].led = led;
5191
5192         /* LEDs with no name don't get registered */
5193         if (!tpacpi_led_names[led])
5194                 return 0;
5195
5196         tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set;
5197         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5198         if (led_supported == TPACPI_LED_570)
5199                 tpacpi_leds[led].led_classdev.brightness_get =
5200                                                 &led_sysfs_get;
5201
5202         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5203
5204         INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker);
5205
5206         rc = led_classdev_register(&tpacpi_pdev->dev,
5207                                 &tpacpi_leds[led].led_classdev);
5208         if (rc < 0)
5209                 tpacpi_leds[led].led_classdev.name = NULL;
5210
5211         return rc;
5212 }
5213
5214 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5215         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5216         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5217         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5218
5219         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5220         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5221         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5222         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5223         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5224         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5225         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5226         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5227
5228         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5229         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5230         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5231         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5232         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5233
5234         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5235         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5236         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5237         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5238
5239         /* (1) - may have excess leds enabled on MSB */
5240
5241         /* Defaults (order matters, keep last, don't reorder!) */
5242         { /* Lenovo */
5243           .vendor = PCI_VENDOR_ID_LENOVO,
5244           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5245           .quirks = 0x1fffU,
5246         },
5247         { /* IBM ThinkPads with no EC version string */
5248           .vendor = PCI_VENDOR_ID_IBM,
5249           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5250           .quirks = 0x00ffU,
5251         },
5252         { /* IBM ThinkPads with EC version string */
5253           .vendor = PCI_VENDOR_ID_IBM,
5254           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5255           .quirks = 0x00bfU,
5256         },
5257 };
5258
5259 #undef TPACPI_LEDQ_IBM
5260 #undef TPACPI_LEDQ_LNV
5261
5262 static int __init led_init(struct ibm_init_struct *iibm)
5263 {
5264         unsigned int i;
5265         int rc;
5266         unsigned long useful_leds;
5267
5268         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5269
5270         TPACPI_ACPIHANDLE_INIT(led);
5271
5272         if (!led_handle)
5273                 /* led not supported on R30, R31 */
5274                 led_supported = TPACPI_LED_NONE;
5275         else if (strlencmp(led_path, "SLED") == 0)
5276                 /* 570 */
5277                 led_supported = TPACPI_LED_570;
5278         else if (strlencmp(led_path, "SYSL") == 0)
5279                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5280                 led_supported = TPACPI_LED_OLD;
5281         else
5282                 /* all others */
5283                 led_supported = TPACPI_LED_NEW;
5284
5285         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5286                 str_supported(led_supported), led_supported);
5287
5288         if (led_supported == TPACPI_LED_NONE)
5289                 return 1;
5290
5291         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5292                               GFP_KERNEL);
5293         if (!tpacpi_leds) {
5294                 printk(TPACPI_ERR "Out of memory for LED data\n");
5295                 return -ENOMEM;
5296         }
5297
5298         useful_leds = tpacpi_check_quirks(led_useful_qtable,
5299                                           ARRAY_SIZE(led_useful_qtable));
5300
5301         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5302                 if (!tpacpi_is_led_restricted(i) &&
5303                     test_bit(i, &useful_leds)) {
5304                         rc = tpacpi_init_led(i);
5305                         if (rc < 0) {
5306                                 led_exit();
5307                                 return rc;
5308                         }
5309                 }
5310         }
5311
5312 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5313         printk(TPACPI_NOTICE
5314                 "warning: userspace override of important "
5315                 "firmware LEDs is enabled\n");
5316 #endif
5317         return 0;
5318 }
5319
5320 #define str_led_status(s) \
5321         ((s) == TPACPI_LED_OFF ? "off" : \
5322                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5323
5324 static int led_read(struct seq_file *m)
5325 {
5326         if (!led_supported) {
5327                 seq_printf(m, "status:\t\tnot supported\n");
5328                 return 0;
5329         }
5330         seq_printf(m, "status:\t\tsupported\n");
5331
5332         if (led_supported == TPACPI_LED_570) {
5333                 /* 570 */
5334                 int i, status;
5335                 for (i = 0; i < 8; i++) {
5336                         status = led_get_status(i);
5337                         if (status < 0)
5338                                 return -EIO;
5339                         seq_printf(m, "%d:\t\t%s\n",
5340                                        i, str_led_status(status));
5341                 }
5342         }
5343
5344         seq_printf(m, "commands:\t"
5345                        "<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5346
5347         return 0;
5348 }
5349
5350 static int led_write(char *buf)
5351 {
5352         char *cmd;
5353         int led, rc;
5354         enum led_status_t s;
5355
5356         if (!led_supported)
5357                 return -ENODEV;
5358
5359         while ((cmd = next_cmd(&buf))) {
5360                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15)
5361                         return -EINVAL;
5362
5363                 if (strstr(cmd, "off")) {
5364                         s = TPACPI_LED_OFF;
5365                 } else if (strstr(cmd, "on")) {
5366                         s = TPACPI_LED_ON;
5367                 } else if (strstr(cmd, "blink")) {
5368                         s = TPACPI_LED_BLINK;
5369                 } else {
5370                         return -EINVAL;
5371                 }
5372
5373                 rc = led_set_status(led, s);
5374                 if (rc < 0)
5375                         return rc;
5376         }
5377
5378         return 0;
5379 }
5380
5381 static struct ibm_struct led_driver_data = {
5382         .name = "led",
5383         .read = led_read,
5384         .write = led_write,
5385         .exit = led_exit,
5386 };
5387
5388 /*************************************************************************
5389  * Beep subdriver
5390  */
5391
5392 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
5393
5394 #define TPACPI_BEEP_Q1 0x0001
5395
5396 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
5397         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
5398         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
5399 };
5400
5401 static int __init beep_init(struct ibm_init_struct *iibm)
5402 {
5403         unsigned long quirks;
5404
5405         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
5406
5407         TPACPI_ACPIHANDLE_INIT(beep);
5408
5409         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
5410                 str_supported(beep_handle != NULL));
5411
5412         quirks = tpacpi_check_quirks(beep_quirk_table,
5413                                      ARRAY_SIZE(beep_quirk_table));
5414
5415         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
5416
5417         return (beep_handle)? 0 : 1;
5418 }
5419
5420 static int beep_read(struct seq_file *m)
5421 {
5422         if (!beep_handle)
5423                 seq_printf(m, "status:\t\tnot supported\n");
5424         else {
5425                 seq_printf(m, "status:\t\tsupported\n");
5426                 seq_printf(m, "commands:\t<cmd> (<cmd> is 0-17)\n");
5427         }
5428
5429         return 0;
5430 }
5431
5432 static int beep_write(char *buf)
5433 {
5434         char *cmd;
5435         int beep_cmd;
5436
5437         if (!beep_handle)
5438                 return -ENODEV;
5439
5440         while ((cmd = next_cmd(&buf))) {
5441                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
5442                     beep_cmd >= 0 && beep_cmd <= 17) {
5443                         /* beep_cmd set */
5444                 } else
5445                         return -EINVAL;
5446                 if (tp_features.beep_needs_two_args) {
5447                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
5448                                         beep_cmd, 0))
5449                                 return -EIO;
5450                 } else {
5451                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
5452                                         beep_cmd))
5453                                 return -EIO;
5454                 }
5455         }
5456
5457         return 0;
5458 }
5459
5460 static struct ibm_struct beep_driver_data = {
5461         .name = "beep",
5462         .read = beep_read,
5463         .write = beep_write,
5464 };
5465
5466 /*************************************************************************
5467  * Thermal subdriver
5468  */
5469
5470 enum thermal_access_mode {
5471         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
5472         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
5473         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
5474         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
5475         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
5476 };
5477
5478 enum { /* TPACPI_THERMAL_TPEC_* */
5479         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
5480         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
5481         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
5482
5483         TPACPI_THERMAL_SENSOR_NA = -128000, /* Sensor not available */
5484 };
5485
5486
5487 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
5488 struct ibm_thermal_sensors_struct {
5489         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
5490 };
5491
5492 static enum thermal_access_mode thermal_read_mode;
5493
5494 /* idx is zero-based */
5495 static int thermal_get_sensor(int idx, s32 *value)
5496 {
5497         int t;
5498         s8 tmp;
5499         char tmpi[5];
5500
5501         t = TP_EC_THERMAL_TMP0;
5502
5503         switch (thermal_read_mode) {
5504 #if TPACPI_MAX_THERMAL_SENSORS >= 16
5505         case TPACPI_THERMAL_TPEC_16:
5506                 if (idx >= 8 && idx <= 15) {
5507                         t = TP_EC_THERMAL_TMP8;
5508                         idx -= 8;
5509                 }
5510                 /* fallthrough */
5511 #endif
5512         case TPACPI_THERMAL_TPEC_8:
5513                 if (idx <= 7) {
5514                         if (!acpi_ec_read(t + idx, &tmp))
5515                                 return -EIO;
5516                         *value = tmp * 1000;
5517                         return 0;
5518                 }
5519                 break;
5520
5521         case TPACPI_THERMAL_ACPI_UPDT:
5522                 if (idx <= 7) {
5523                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5524                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
5525                                 return -EIO;
5526                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5527                                 return -EIO;
5528                         *value = (t - 2732) * 100;
5529                         return 0;
5530                 }
5531                 break;
5532
5533         case TPACPI_THERMAL_ACPI_TMP07:
5534                 if (idx <= 7) {
5535                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5536                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5537                                 return -EIO;
5538                         if (t > 127 || t < -127)
5539                                 t = TP_EC_THERMAL_TMP_NA;
5540                         *value = t * 1000;
5541                         return 0;
5542                 }
5543                 break;
5544
5545         case TPACPI_THERMAL_NONE:
5546         default:
5547                 return -ENOSYS;
5548         }
5549
5550         return -EINVAL;
5551 }
5552
5553 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
5554 {
5555         int res, i;
5556         int n;
5557
5558         n = 8;
5559         i = 0;
5560
5561         if (!s)
5562                 return -EINVAL;
5563
5564         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
5565                 n = 16;
5566
5567         for (i = 0 ; i < n; i++) {
5568                 res = thermal_get_sensor(i, &s->temp[i]);
5569                 if (res)
5570                         return res;
5571         }
5572
5573         return n;
5574 }
5575
5576 static void thermal_dump_all_sensors(void)
5577 {
5578         int n, i;
5579         struct ibm_thermal_sensors_struct t;
5580
5581         n = thermal_get_sensors(&t);
5582         if (n <= 0)
5583                 return;
5584
5585         printk(TPACPI_NOTICE
5586                 "temperatures (Celsius):");
5587
5588         for (i = 0; i < n; i++) {
5589                 if (t.temp[i] != TPACPI_THERMAL_SENSOR_NA)
5590                         printk(KERN_CONT " %d", (int)(t.temp[i] / 1000));
5591                 else
5592                         printk(KERN_CONT " N/A");
5593         }
5594
5595         printk(KERN_CONT "\n");
5596 }
5597
5598 /* sysfs temp##_input -------------------------------------------------- */
5599
5600 static ssize_t thermal_temp_input_show(struct device *dev,
5601                            struct device_attribute *attr,
5602                            char *buf)
5603 {
5604         struct sensor_device_attribute *sensor_attr =
5605                                         to_sensor_dev_attr(attr);
5606         int idx = sensor_attr->index;
5607         s32 value;
5608         int res;
5609
5610         res = thermal_get_sensor(idx, &value);
5611         if (res)
5612                 return res;
5613         if (value == TPACPI_THERMAL_SENSOR_NA)
5614                 return -ENXIO;
5615
5616         return snprintf(buf, PAGE_SIZE, "%d\n", value);
5617 }
5618
5619 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
5620          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
5621                      thermal_temp_input_show, NULL, _idxB)
5622
5623 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
5624         THERMAL_SENSOR_ATTR_TEMP(1, 0),
5625         THERMAL_SENSOR_ATTR_TEMP(2, 1),
5626         THERMAL_SENSOR_ATTR_TEMP(3, 2),
5627         THERMAL_SENSOR_ATTR_TEMP(4, 3),
5628         THERMAL_SENSOR_ATTR_TEMP(5, 4),
5629         THERMAL_SENSOR_ATTR_TEMP(6, 5),
5630         THERMAL_SENSOR_ATTR_TEMP(7, 6),
5631         THERMAL_SENSOR_ATTR_TEMP(8, 7),
5632         THERMAL_SENSOR_ATTR_TEMP(9, 8),
5633         THERMAL_SENSOR_ATTR_TEMP(10, 9),
5634         THERMAL_SENSOR_ATTR_TEMP(11, 10),
5635         THERMAL_SENSOR_ATTR_TEMP(12, 11),
5636         THERMAL_SENSOR_ATTR_TEMP(13, 12),
5637         THERMAL_SENSOR_ATTR_TEMP(14, 13),
5638         THERMAL_SENSOR_ATTR_TEMP(15, 14),
5639         THERMAL_SENSOR_ATTR_TEMP(16, 15),
5640 };
5641
5642 #define THERMAL_ATTRS(X) \
5643         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
5644
5645 static struct attribute *thermal_temp_input_attr[] = {
5646         THERMAL_ATTRS(8),
5647         THERMAL_ATTRS(9),
5648         THERMAL_ATTRS(10),
5649         THERMAL_ATTRS(11),
5650         THERMAL_ATTRS(12),
5651         THERMAL_ATTRS(13),
5652         THERMAL_ATTRS(14),
5653         THERMAL_ATTRS(15),
5654         THERMAL_ATTRS(0),
5655         THERMAL_ATTRS(1),
5656         THERMAL_ATTRS(2),
5657         THERMAL_ATTRS(3),
5658         THERMAL_ATTRS(4),
5659         THERMAL_ATTRS(5),
5660         THERMAL_ATTRS(6),
5661         THERMAL_ATTRS(7),
5662         NULL
5663 };
5664
5665 static const struct attribute_group thermal_temp_input16_group = {
5666         .attrs = thermal_temp_input_attr
5667 };
5668
5669 static const struct attribute_group thermal_temp_input8_group = {
5670         .attrs = &thermal_temp_input_attr[8]
5671 };
5672
5673 #undef THERMAL_SENSOR_ATTR_TEMP
5674 #undef THERMAL_ATTRS
5675
5676 /* --------------------------------------------------------------------- */
5677
5678 static int __init thermal_init(struct ibm_init_struct *iibm)
5679 {
5680         u8 t, ta1, ta2;
5681         int i;
5682         int acpi_tmp7;
5683         int res;
5684
5685         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5686
5687         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5688
5689         if (thinkpad_id.ec_model) {
5690                 /*
5691                  * Direct EC access mode: sensors at registers
5692                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5693                  * non-implemented, thermal sensors return 0x80 when
5694                  * not available
5695                  */
5696
5697                 ta1 = ta2 = 0;
5698                 for (i = 0; i < 8; i++) {
5699                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5700                                 ta1 |= t;
5701                         } else {
5702                                 ta1 = 0;
5703                                 break;
5704                         }
5705                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5706                                 ta2 |= t;
5707                         } else {
5708                                 ta1 = 0;
5709                                 break;
5710                         }
5711                 }
5712                 if (ta1 == 0) {
5713                         /* This is sheer paranoia, but we handle it anyway */
5714                         if (acpi_tmp7) {
5715                                 printk(TPACPI_ERR
5716                                        "ThinkPad ACPI EC access misbehaving, "
5717                                        "falling back to ACPI TMPx access "
5718                                        "mode\n");
5719                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5720                         } else {
5721                                 printk(TPACPI_ERR
5722                                        "ThinkPad ACPI EC access misbehaving, "
5723                                        "disabling thermal sensors access\n");
5724                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5725                         }
5726                 } else {
5727                         thermal_read_mode =
5728                             (ta2 != 0) ?
5729                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5730                 }
5731         } else if (acpi_tmp7) {
5732                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5733                         /* 600e/x, 770e, 770x */
5734                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5735                 } else {
5736                         /* Standard ACPI TMPx access, max 8 sensors */
5737                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5738                 }
5739         } else {
5740                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5741                 thermal_read_mode = TPACPI_THERMAL_NONE;
5742         }
5743
5744         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5745                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5746                 thermal_read_mode);
5747
5748         switch (thermal_read_mode) {
5749         case TPACPI_THERMAL_TPEC_16:
5750                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5751                                 &thermal_temp_input16_group);
5752                 if (res)
5753                         return res;
5754                 break;
5755         case TPACPI_THERMAL_TPEC_8:
5756         case TPACPI_THERMAL_ACPI_TMP07:
5757         case TPACPI_THERMAL_ACPI_UPDT:
5758                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5759                                 &thermal_temp_input8_group);
5760                 if (res)
5761                         return res;
5762                 break;
5763         case TPACPI_THERMAL_NONE:
5764         default:
5765                 return 1;
5766         }
5767
5768         return 0;
5769 }
5770
5771 static void thermal_exit(void)
5772 {
5773         switch (thermal_read_mode) {
5774         case TPACPI_THERMAL_TPEC_16:
5775                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5776                                    &thermal_temp_input16_group);
5777                 break;
5778         case TPACPI_THERMAL_TPEC_8:
5779         case TPACPI_THERMAL_ACPI_TMP07:
5780         case TPACPI_THERMAL_ACPI_UPDT:
5781                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5782                                    &thermal_temp_input8_group);
5783                 break;
5784         case TPACPI_THERMAL_NONE:
5785         default:
5786                 break;
5787         }
5788 }
5789
5790 static int thermal_read(struct seq_file *m)
5791 {
5792         int n, i;
5793         struct ibm_thermal_sensors_struct t;
5794
5795         n = thermal_get_sensors(&t);
5796         if (unlikely(n < 0))
5797                 return n;
5798
5799         seq_printf(m, "temperatures:\t");
5800
5801         if (n > 0) {
5802                 for (i = 0; i < (n - 1); i++)
5803                         seq_printf(m, "%d ", t.temp[i] / 1000);
5804                 seq_printf(m, "%d\n", t.temp[i] / 1000);
5805         } else
5806                 seq_printf(m, "not supported\n");
5807
5808         return 0;
5809 }
5810
5811 static struct ibm_struct thermal_driver_data = {
5812         .name = "thermal",
5813         .read = thermal_read,
5814         .exit = thermal_exit,
5815 };
5816
5817 /*************************************************************************
5818  * EC Dump subdriver
5819  */
5820
5821 static u8 ecdump_regs[256];
5822
5823 static int ecdump_read(struct seq_file *m)
5824 {
5825         int i, j;
5826         u8 v;
5827
5828         seq_printf(m, "EC      "
5829                        " +00 +01 +02 +03 +04 +05 +06 +07"
5830                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5831         for (i = 0; i < 256; i += 16) {
5832                 seq_printf(m, "EC 0x%02x:", i);
5833                 for (j = 0; j < 16; j++) {
5834                         if (!acpi_ec_read(i + j, &v))
5835                                 break;
5836                         if (v != ecdump_regs[i + j])
5837                                 seq_printf(m, " *%02x", v);
5838                         else
5839                                 seq_printf(m, "  %02x", v);
5840                         ecdump_regs[i + j] = v;
5841                 }
5842                 seq_putc(m, '\n');
5843                 if (j != 16)
5844                         break;
5845         }
5846
5847         /* These are way too dangerous to advertise openly... */
5848 #if 0
5849         seq_printf(m, "commands:\t0x<offset> 0x<value>"
5850                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5851         seq_printf(m, "commands:\t0x<offset> <value>  "
5852                        " (<offset> is 00-ff, <value> is 0-255)\n");
5853 #endif
5854         return 0;
5855 }
5856
5857 static int ecdump_write(char *buf)
5858 {
5859         char *cmd;
5860         int i, v;
5861
5862         while ((cmd = next_cmd(&buf))) {
5863                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5864                         /* i and v set */
5865                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5866                         /* i and v set */
5867                 } else
5868                         return -EINVAL;
5869                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5870                         if (!acpi_ec_write(i, v))
5871                                 return -EIO;
5872                 } else
5873                         return -EINVAL;
5874         }
5875
5876         return 0;
5877 }
5878
5879 static struct ibm_struct ecdump_driver_data = {
5880         .name = "ecdump",
5881         .read = ecdump_read,
5882         .write = ecdump_write,
5883         .flags.experimental = 1,
5884 };
5885
5886 /*************************************************************************
5887  * Backlight/brightness subdriver
5888  */
5889
5890 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5891
5892 /*
5893  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
5894  * CMOS NVRAM byte 0x5E, bits 0-3.
5895  *
5896  * EC HBRV (0x31) has the following layout
5897  *   Bit 7: unknown function
5898  *   Bit 6: unknown function
5899  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5900  *   Bit 4: must be set to zero to avoid problems
5901  *   Bit 3-0: backlight brightness level
5902  *
5903  * brightness_get_raw returns status data in the HBRV layout
5904  *
5905  * WARNING: The X61 has been verified to use HBRV for something else, so
5906  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
5907  * testing on the very early *60 Lenovo models...
5908  */
5909
5910 enum {
5911         TP_EC_BACKLIGHT = 0x31,
5912
5913         /* TP_EC_BACKLIGHT bitmasks */
5914         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5915         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5916         TP_EC_BACKLIGHT_MAPSW = 0x20,
5917 };
5918
5919 enum tpacpi_brightness_access_mode {
5920         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
5921         TPACPI_BRGHT_MODE_EC,           /* EC control */
5922         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
5923         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
5924         TPACPI_BRGHT_MODE_MAX
5925 };
5926
5927 static struct backlight_device *ibm_backlight_device;
5928
5929 static enum tpacpi_brightness_access_mode brightness_mode =
5930                 TPACPI_BRGHT_MODE_MAX;
5931
5932 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5933
5934 static struct mutex brightness_mutex;
5935
5936 /* NVRAM brightness access,
5937  * call with brightness_mutex held! */
5938 static unsigned int tpacpi_brightness_nvram_get(void)
5939 {
5940         u8 lnvram;
5941
5942         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5943                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5944                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5945         lnvram &= (tp_features.bright_16levels) ? 0x0f : 0x07;
5946
5947         return lnvram;
5948 }
5949
5950 static void tpacpi_brightness_checkpoint_nvram(void)
5951 {
5952         u8 lec = 0;
5953         u8 b_nvram;
5954
5955         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
5956                 return;
5957
5958         vdbg_printk(TPACPI_DBG_BRGHT,
5959                 "trying to checkpoint backlight level to NVRAM...\n");
5960
5961         if (mutex_lock_killable(&brightness_mutex) < 0)
5962                 return;
5963
5964         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5965                 goto unlock;
5966         lec &= TP_EC_BACKLIGHT_LVLMSK;
5967         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
5968
5969         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5970                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
5971                 /* NVRAM needs update */
5972                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
5973                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
5974                 b_nvram |= lec;
5975                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
5976                 dbg_printk(TPACPI_DBG_BRGHT,
5977                            "updated NVRAM backlight level to %u (0x%02x)\n",
5978                            (unsigned int) lec, (unsigned int) b_nvram);
5979         } else
5980                 vdbg_printk(TPACPI_DBG_BRGHT,
5981                            "NVRAM backlight level already is %u (0x%02x)\n",
5982                            (unsigned int) lec, (unsigned int) b_nvram);
5983
5984 unlock:
5985         mutex_unlock(&brightness_mutex);
5986 }
5987
5988
5989 /* call with brightness_mutex held! */
5990 static int tpacpi_brightness_get_raw(int *status)
5991 {
5992         u8 lec = 0;
5993
5994         switch (brightness_mode) {
5995         case TPACPI_BRGHT_MODE_UCMS_STEP:
5996                 *status = tpacpi_brightness_nvram_get();
5997                 return 0;
5998         case TPACPI_BRGHT_MODE_EC:
5999         case TPACPI_BRGHT_MODE_ECNVRAM:
6000                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6001                         return -EIO;
6002                 *status = lec;
6003                 return 0;
6004         default:
6005                 return -ENXIO;
6006         }
6007 }
6008
6009 /* call with brightness_mutex held! */
6010 /* do NOT call with illegal backlight level value */
6011 static int tpacpi_brightness_set_ec(unsigned int value)
6012 {
6013         u8 lec = 0;
6014
6015         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
6016                 return -EIO;
6017
6018         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
6019                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
6020                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
6021                 return -EIO;
6022
6023         return 0;
6024 }
6025
6026 /* call with brightness_mutex held! */
6027 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
6028 {
6029         int cmos_cmd, inc;
6030         unsigned int current_value, i;
6031
6032         current_value = tpacpi_brightness_nvram_get();
6033
6034         if (value == current_value)
6035                 return 0;
6036
6037         cmos_cmd = (value > current_value) ?
6038                         TP_CMOS_BRIGHTNESS_UP :
6039                         TP_CMOS_BRIGHTNESS_DOWN;
6040         inc = (value > current_value) ? 1 : -1;
6041
6042         for (i = current_value; i != value; i += inc)
6043                 if (issue_thinkpad_cmos_command(cmos_cmd))
6044                         return -EIO;
6045
6046         return 0;
6047 }
6048
6049 /* May return EINTR which can always be mapped to ERESTARTSYS */
6050 static int brightness_set(unsigned int value)
6051 {
6052         int res;
6053
6054         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
6055             value < 0)
6056                 return -EINVAL;
6057
6058         vdbg_printk(TPACPI_DBG_BRGHT,
6059                         "set backlight level to %d\n", value);
6060
6061         res = mutex_lock_killable(&brightness_mutex);
6062         if (res < 0)
6063                 return res;
6064
6065         switch (brightness_mode) {
6066         case TPACPI_BRGHT_MODE_EC:
6067         case TPACPI_BRGHT_MODE_ECNVRAM:
6068                 res = tpacpi_brightness_set_ec(value);
6069                 break;
6070         case TPACPI_BRGHT_MODE_UCMS_STEP:
6071                 res = tpacpi_brightness_set_ucmsstep(value);
6072                 break;
6073         default:
6074                 res = -ENXIO;
6075         }
6076
6077         mutex_unlock(&brightness_mutex);
6078         return res;
6079 }
6080
6081 /* sysfs backlight class ----------------------------------------------- */
6082
6083 static int brightness_update_status(struct backlight_device *bd)
6084 {
6085         unsigned int level =
6086                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
6087                  bd->props.power == FB_BLANK_UNBLANK) ?
6088                                 bd->props.brightness : 0;
6089
6090         dbg_printk(TPACPI_DBG_BRGHT,
6091                         "backlight: attempt to set level to %d\n",
6092                         level);
6093
6094         /* it is the backlight class's job (caller) to handle
6095          * EINTR and other errors properly */
6096         return brightness_set(level);
6097 }
6098
6099 static int brightness_get(struct backlight_device *bd)
6100 {
6101         int status, res;
6102
6103         res = mutex_lock_killable(&brightness_mutex);
6104         if (res < 0)
6105                 return 0;
6106
6107         res = tpacpi_brightness_get_raw(&status);
6108
6109         mutex_unlock(&brightness_mutex);
6110
6111         if (res < 0)
6112                 return 0;
6113
6114         return status & TP_EC_BACKLIGHT_LVLMSK;
6115 }
6116
6117 static void tpacpi_brightness_notify_change(void)
6118 {
6119         backlight_force_update(ibm_backlight_device,
6120                                BACKLIGHT_UPDATE_HOTKEY);
6121 }
6122
6123 static struct backlight_ops ibm_backlight_data = {
6124         .get_brightness = brightness_get,
6125         .update_status  = brightness_update_status,
6126 };
6127
6128 /* --------------------------------------------------------------------- */
6129
6130 /*
6131  * These are only useful for models that have only one possibility
6132  * of GPU.  If the BIOS model handles both ATI and Intel, don't use
6133  * these quirks.
6134  */
6135 #define TPACPI_BRGHT_Q_NOEC     0x0001  /* Must NOT use EC HBRV */
6136 #define TPACPI_BRGHT_Q_EC       0x0002  /* Should or must use EC HBRV */
6137 #define TPACPI_BRGHT_Q_ASK      0x8000  /* Ask for user report */
6138
6139 static const struct tpacpi_quirk brightness_quirk_table[] __initconst = {
6140         /* Models with ATI GPUs known to require ECNVRAM mode */
6141         TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC),      /* T43/p ATI */
6142
6143         /* Models with ATI GPUs that can use ECNVRAM */
6144         TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC),      /* R50,51 T40-42 */
6145         TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6146         TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_EC),      /* R52 */
6147         TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6148
6149         /* Models with Intel Extreme Graphics 2 */
6150         TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC),    /* X40 */
6151         TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6152         TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6153
6154         /* Models with Intel GMA900 */
6155         TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC),    /* T43, R52 */
6156         TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC),    /* X41 */
6157         TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC),    /* X41 Tablet */
6158 };
6159
6160 static int __init brightness_init(struct ibm_init_struct *iibm)
6161 {
6162         int b;
6163         unsigned long quirks;
6164
6165         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
6166
6167         mutex_init(&brightness_mutex);
6168
6169         quirks = tpacpi_check_quirks(brightness_quirk_table,
6170                                 ARRAY_SIZE(brightness_quirk_table));
6171
6172         /*
6173          * We always attempt to detect acpi support, so as to switch
6174          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
6175          * going to publish a backlight interface
6176          */
6177         b = tpacpi_check_std_acpi_brightness_support();
6178         if (b > 0) {
6179
6180                 if (acpi_video_backlight_support()) {
6181                         if (brightness_enable > 1) {
6182                                 printk(TPACPI_NOTICE
6183                                        "Standard ACPI backlight interface "
6184                                        "available, not loading native one.\n");
6185                                 return 1;
6186                         } else if (brightness_enable == 1) {
6187                                 printk(TPACPI_NOTICE
6188                                        "Backlight control force enabled, even if standard "
6189                                        "ACPI backlight interface is available\n");
6190                         }
6191                 } else {
6192                         if (brightness_enable > 1) {
6193                                 printk(TPACPI_NOTICE
6194                                        "Standard ACPI backlight interface not "
6195                                        "available, thinkpad_acpi native "
6196                                        "brightness control enabled\n");
6197                         }
6198                 }
6199         }
6200
6201         if (!brightness_enable) {
6202                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6203                            "brightness support disabled by "
6204                            "module parameter\n");
6205                 return 1;
6206         }
6207
6208         if (b > 16) {
6209                 printk(TPACPI_ERR
6210                        "Unsupported brightness interface, "
6211                        "please contact %s\n", TPACPI_MAIL);
6212                 return 1;
6213         }
6214         if (b == 16)
6215                 tp_features.bright_16levels = 1;
6216
6217         /*
6218          * Check for module parameter bogosity, note that we
6219          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6220          * able to detect "unspecified"
6221          */
6222         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6223                 return -EINVAL;
6224
6225         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6226         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6227             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6228                 if (quirks & TPACPI_BRGHT_Q_EC)
6229                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6230                 else
6231                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6232
6233                 dbg_printk(TPACPI_DBG_BRGHT,
6234                            "driver auto-selected brightness_mode=%d\n",
6235                            brightness_mode);
6236         }
6237
6238         /* Safety */
6239         if (thinkpad_id.vendor != PCI_VENDOR_ID_IBM &&
6240             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6241              brightness_mode == TPACPI_BRGHT_MODE_EC))
6242                 return -EINVAL;
6243
6244         if (tpacpi_brightness_get_raw(&b) < 0)
6245                 return 1;
6246
6247         if (tp_features.bright_16levels)
6248                 printk(TPACPI_INFO
6249                        "detected a 16-level brightness capable ThinkPad\n");
6250
6251         ibm_backlight_device = backlight_device_register(
6252                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
6253                                         &ibm_backlight_data);
6254         if (IS_ERR(ibm_backlight_device)) {
6255                 int rc = PTR_ERR(ibm_backlight_device);
6256                 ibm_backlight_device = NULL;
6257                 printk(TPACPI_ERR "Could not register backlight device\n");
6258                 return rc;
6259         }
6260         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6261                         "brightness is supported\n");
6262
6263         if (quirks & TPACPI_BRGHT_Q_ASK) {