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