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