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