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