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