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