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