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