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