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