thinkpad-acpi: hotkey event driver update
[linux-2.6.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 0x020500
26
27 /*
28  *  Changelog:
29  *  2007-10-20          changelog trimmed down
30  *
31  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
32  *                      drivers/misc.
33  *
34  *  2006-11-22  0.13    new maintainer
35  *                      changelog now lives in git commit history, and will
36  *                      not be updated further in-file.
37  *
38  *  2005-03-17  0.11    support for 600e, 770x
39  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
40  *
41  *  2005-01-16  0.9     use MODULE_VERSION
42  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
43  *                      fix parameter passing on module loading
44  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
45  *                          thanks to Jim Radford <radford@blackbean.org>
46  *  2004-11-08  0.8     fix init error case, don't return from a macro
47  *                          thanks to Chris Wright <chrisw@osdl.org>
48  */
49
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/init.h>
53 #include <linux/types.h>
54 #include <linux/string.h>
55 #include <linux/list.h>
56 #include <linux/mutex.h>
57 #include <linux/sched.h>
58 #include <linux/kthread.h>
59 #include <linux/freezer.h>
60 #include <linux/delay.h>
61
62 #include <linux/nvram.h>
63 #include <linux/proc_fs.h>
64 #include <linux/sysfs.h>
65 #include <linux/backlight.h>
66 #include <linux/fb.h>
67 #include <linux/platform_device.h>
68 #include <linux/hwmon.h>
69 #include <linux/hwmon-sysfs.h>
70 #include <linux/input.h>
71 #include <linux/leds.h>
72 #include <linux/rfkill.h>
73 #include <asm/uaccess.h>
74
75 #include <linux/dmi.h>
76 #include <linux/jiffies.h>
77 #include <linux/workqueue.h>
78
79 #include <acpi/acpi_drivers.h>
80
81 #include <linux/pci_ids.h>
82
83
84 /* ThinkPad CMOS commands */
85 #define TP_CMOS_VOLUME_DOWN     0
86 #define TP_CMOS_VOLUME_UP       1
87 #define TP_CMOS_VOLUME_MUTE     2
88 #define TP_CMOS_BRIGHTNESS_UP   4
89 #define TP_CMOS_BRIGHTNESS_DOWN 5
90 #define TP_CMOS_THINKLIGHT_ON   12
91 #define TP_CMOS_THINKLIGHT_OFF  13
92
93 /* NVRAM Addresses */
94 enum tp_nvram_addr {
95         TP_NVRAM_ADDR_HK2               = 0x57,
96         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
97         TP_NVRAM_ADDR_VIDEO             = 0x59,
98         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
99         TP_NVRAM_ADDR_MIXER             = 0x60,
100 };
101
102 /* NVRAM bit masks */
103 enum {
104         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
105         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
106         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
107         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
108         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
109         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
110         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
111         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
112         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
113         TP_NVRAM_MASK_MUTE              = 0x40,
114         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
115         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
116         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
117 };
118
119 /* ACPI HIDs */
120 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
121
122 /* Input IDs */
123 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
124 #define TPACPI_HKEY_INPUT_VERSION       0x4101
125
126 /* ACPI \WGSV commands */
127 enum {
128         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
129         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
130         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
131         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
132 };
133
134 /* TP_ACPI_WGSV_GET_STATE bits */
135 enum {
136         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
137         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
138         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
139         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
140         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
141         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
142         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
143         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
144         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
145         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
146 };
147
148 /****************************************************************************
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                 rfkill_destroy(tp_rfk->rfkill);
1282                 tpacpi_rfkill_switches[id] = NULL;
1283                 kfree(tp_rfk);
1284         }
1285 }
1286
1287 static void printk_deprecated_rfkill_attribute(const char * const what)
1288 {
1289         printk_deprecated_attribute(what,
1290                         "Please switch to generic rfkill before year 2010");
1291 }
1292
1293 /* sysfs <radio> enable ------------------------------------------------ */
1294 static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id,
1295                                             struct device_attribute *attr,
1296                                             char *buf)
1297 {
1298         int status;
1299
1300         printk_deprecated_rfkill_attribute(attr->attr.name);
1301
1302         /* This is in the ABI... */
1303         if (tpacpi_rfk_check_hwblock_state()) {
1304                 status = TPACPI_RFK_RADIO_OFF;
1305         } else {
1306                 status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1307                 if (status < 0)
1308                         return status;
1309         }
1310
1311         return snprintf(buf, PAGE_SIZE, "%d\n",
1312                         (status == TPACPI_RFK_RADIO_ON) ? 1 : 0);
1313 }
1314
1315 static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id,
1316                             struct device_attribute *attr,
1317                             const char *buf, size_t count)
1318 {
1319         unsigned long t;
1320         int res;
1321
1322         printk_deprecated_rfkill_attribute(attr->attr.name);
1323
1324         if (parse_strtoul(buf, 1, &t))
1325                 return -EINVAL;
1326
1327         tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t);
1328
1329         /* This is in the ABI... */
1330         if (tpacpi_rfk_check_hwblock_state() && !!t)
1331                 return -EPERM;
1332
1333         res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ?
1334                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF);
1335         tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1336
1337         return (res < 0) ? res : count;
1338 }
1339
1340 /* procfs -------------------------------------------------------------- */
1341 static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, char *p)
1342 {
1343         int len = 0;
1344
1345         if (id >= TPACPI_RFK_SW_MAX)
1346                 len += sprintf(p + len, "status:\t\tnot supported\n");
1347         else {
1348                 int status;
1349
1350                 /* This is in the ABI... */
1351                 if (tpacpi_rfk_check_hwblock_state()) {
1352                         status = TPACPI_RFK_RADIO_OFF;
1353                 } else {
1354                         status = tpacpi_rfk_update_swstate(
1355                                                 tpacpi_rfkill_switches[id]);
1356                         if (status < 0)
1357                                 return status;
1358                 }
1359
1360                 len += sprintf(p + len, "status:\t\t%s\n",
1361                                 (status == TPACPI_RFK_RADIO_ON) ?
1362                                         "enabled" : "disabled");
1363                 len += sprintf(p + len, "commands:\tenable, disable\n");
1364         }
1365
1366         return len;
1367 }
1368
1369 static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf)
1370 {
1371         char *cmd;
1372         int status = -1;
1373         int res = 0;
1374
1375         if (id >= TPACPI_RFK_SW_MAX)
1376                 return -ENODEV;
1377
1378         while ((cmd = next_cmd(&buf))) {
1379                 if (strlencmp(cmd, "enable") == 0)
1380                         status = TPACPI_RFK_RADIO_ON;
1381                 else if (strlencmp(cmd, "disable") == 0)
1382                         status = TPACPI_RFK_RADIO_OFF;
1383                 else
1384                         return -EINVAL;
1385         }
1386
1387         if (status != -1) {
1388                 tpacpi_disclose_usertask("procfs", "attempt to %s %s\n",
1389                                 (status == TPACPI_RFK_RADIO_ON) ?
1390                                                 "enable" : "disable",
1391                                 tpacpi_rfkill_names[id]);
1392                 res = (tpacpi_rfkill_switches[id]->ops->set_status)(status);
1393                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1394         }
1395
1396         return res;
1397 }
1398
1399 /*************************************************************************
1400  * thinkpad-acpi driver attributes
1401  */
1402
1403 /* interface_version --------------------------------------------------- */
1404 static ssize_t tpacpi_driver_interface_version_show(
1405                                 struct device_driver *drv,
1406                                 char *buf)
1407 {
1408         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
1409 }
1410
1411 static DRIVER_ATTR(interface_version, S_IRUGO,
1412                 tpacpi_driver_interface_version_show, NULL);
1413
1414 /* debug_level --------------------------------------------------------- */
1415 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
1416                                                 char *buf)
1417 {
1418         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
1419 }
1420
1421 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
1422                                                 const char *buf, size_t count)
1423 {
1424         unsigned long t;
1425
1426         if (parse_strtoul(buf, 0xffff, &t))
1427                 return -EINVAL;
1428
1429         dbg_level = t;
1430
1431         return count;
1432 }
1433
1434 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1435                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
1436
1437 /* version ------------------------------------------------------------- */
1438 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
1439                                                 char *buf)
1440 {
1441         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1442                         TPACPI_DESC, TPACPI_VERSION);
1443 }
1444
1445 static DRIVER_ATTR(version, S_IRUGO,
1446                 tpacpi_driver_version_show, NULL);
1447
1448 /* --------------------------------------------------------------------- */
1449
1450 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1451
1452 /* wlsw_emulstate ------------------------------------------------------ */
1453 static ssize_t tpacpi_driver_wlsw_emulstate_show(struct device_driver *drv,
1454                                                 char *buf)
1455 {
1456         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate);
1457 }
1458
1459 static ssize_t tpacpi_driver_wlsw_emulstate_store(struct device_driver *drv,
1460                                                 const char *buf, size_t count)
1461 {
1462         unsigned long t;
1463
1464         if (parse_strtoul(buf, 1, &t))
1465                 return -EINVAL;
1466
1467         if (tpacpi_wlsw_emulstate != !!t) {
1468                 tpacpi_wlsw_emulstate = !!t;
1469                 tpacpi_rfk_update_hwblock_state(!t);    /* negative logic */
1470         }
1471
1472         return count;
1473 }
1474
1475 static DRIVER_ATTR(wlsw_emulstate, S_IWUSR | S_IRUGO,
1476                 tpacpi_driver_wlsw_emulstate_show,
1477                 tpacpi_driver_wlsw_emulstate_store);
1478
1479 /* bluetooth_emulstate ------------------------------------------------- */
1480 static ssize_t tpacpi_driver_bluetooth_emulstate_show(
1481                                         struct device_driver *drv,
1482                                         char *buf)
1483 {
1484         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate);
1485 }
1486
1487 static ssize_t tpacpi_driver_bluetooth_emulstate_store(
1488                                         struct device_driver *drv,
1489                                         const char *buf, size_t count)
1490 {
1491         unsigned long t;
1492
1493         if (parse_strtoul(buf, 1, &t))
1494                 return -EINVAL;
1495
1496         tpacpi_bluetooth_emulstate = !!t;
1497
1498         return count;
1499 }
1500
1501 static DRIVER_ATTR(bluetooth_emulstate, S_IWUSR | S_IRUGO,
1502                 tpacpi_driver_bluetooth_emulstate_show,
1503                 tpacpi_driver_bluetooth_emulstate_store);
1504
1505 /* wwan_emulstate ------------------------------------------------- */
1506 static ssize_t tpacpi_driver_wwan_emulstate_show(
1507                                         struct device_driver *drv,
1508                                         char *buf)
1509 {
1510         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate);
1511 }
1512
1513 static ssize_t tpacpi_driver_wwan_emulstate_store(
1514                                         struct device_driver *drv,
1515                                         const char *buf, size_t count)
1516 {
1517         unsigned long t;
1518
1519         if (parse_strtoul(buf, 1, &t))
1520                 return -EINVAL;
1521
1522         tpacpi_wwan_emulstate = !!t;
1523
1524         return count;
1525 }
1526
1527 static DRIVER_ATTR(wwan_emulstate, S_IWUSR | S_IRUGO,
1528                 tpacpi_driver_wwan_emulstate_show,
1529                 tpacpi_driver_wwan_emulstate_store);
1530
1531 /* uwb_emulstate ------------------------------------------------- */
1532 static ssize_t tpacpi_driver_uwb_emulstate_show(
1533                                         struct device_driver *drv,
1534                                         char *buf)
1535 {
1536         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate);
1537 }
1538
1539 static ssize_t tpacpi_driver_uwb_emulstate_store(
1540                                         struct device_driver *drv,
1541                                         const char *buf, size_t count)
1542 {
1543         unsigned long t;
1544
1545         if (parse_strtoul(buf, 1, &t))
1546                 return -EINVAL;
1547
1548         tpacpi_uwb_emulstate = !!t;
1549
1550         return count;
1551 }
1552
1553 static DRIVER_ATTR(uwb_emulstate, S_IWUSR | S_IRUGO,
1554                 tpacpi_driver_uwb_emulstate_show,
1555                 tpacpi_driver_uwb_emulstate_store);
1556 #endif
1557
1558 /* --------------------------------------------------------------------- */
1559
1560 static struct driver_attribute *tpacpi_driver_attributes[] = {
1561         &driver_attr_debug_level, &driver_attr_version,
1562         &driver_attr_interface_version,
1563 };
1564
1565 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1566 {
1567         int i, res;
1568
1569         i = 0;
1570         res = 0;
1571         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1572                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1573                 i++;
1574         }
1575
1576 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1577         if (!res && dbg_wlswemul)
1578                 res = driver_create_file(drv, &driver_attr_wlsw_emulstate);
1579         if (!res && dbg_bluetoothemul)
1580                 res = driver_create_file(drv, &driver_attr_bluetooth_emulstate);
1581         if (!res && dbg_wwanemul)
1582                 res = driver_create_file(drv, &driver_attr_wwan_emulstate);
1583         if (!res && dbg_uwbemul)
1584                 res = driver_create_file(drv, &driver_attr_uwb_emulstate);
1585 #endif
1586
1587         return res;
1588 }
1589
1590 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1591 {
1592         int i;
1593
1594         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1595                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1596
1597 #ifdef THINKPAD_ACPI_DEBUGFACILITIES
1598         driver_remove_file(drv, &driver_attr_wlsw_emulstate);
1599         driver_remove_file(drv, &driver_attr_bluetooth_emulstate);
1600         driver_remove_file(drv, &driver_attr_wwan_emulstate);
1601         driver_remove_file(drv, &driver_attr_uwb_emulstate);
1602 #endif
1603 }
1604
1605 /*************************************************************************
1606  * Firmware Data
1607  */
1608
1609 /*
1610  * Table of recommended minimum BIOS versions
1611  *
1612  * Reasons for listing:
1613  *    1. Stable BIOS, listed because the unknown ammount of
1614  *       bugs and bad ACPI behaviour on older versions
1615  *
1616  *    2. BIOS or EC fw with known bugs that trigger on Linux
1617  *
1618  *    3. BIOS with known reduced functionality in older versions
1619  *
1620  *  We recommend the latest BIOS and EC version.
1621  *  We only support the latest BIOS and EC fw version as a rule.
1622  *
1623  *  Sources: IBM ThinkPad Public Web Documents (update changelogs),
1624  *  Information from users in ThinkWiki
1625  *
1626  *  WARNING: we use this table also to detect that the machine is
1627  *  a ThinkPad in some cases, so don't remove entries lightly.
1628  */
1629
1630 #define TPV_Q(__v, __id1, __id2, __bv1, __bv2)          \
1631         { .vendor       = (__v),                        \
1632           .bios         = TPID(__id1, __id2),           \
1633           .ec           = TPACPI_MATCH_ANY,             \
1634           .quirks       = TPACPI_MATCH_ANY << 16        \
1635                           | (__bv1) << 8 | (__bv2) }
1636
1637 #define TPV_Q_X(__v, __bid1, __bid2, __bv1, __bv2,      \
1638                 __eid1, __eid2, __ev1, __ev2)           \
1639         { .vendor       = (__v),                        \
1640           .bios         = TPID(__bid1, __bid2),         \
1641           .ec           = TPID(__eid1, __eid2),         \
1642           .quirks       = (__ev1) << 24 | (__ev2) << 16 \
1643                           | (__bv1) << 8 | (__bv2) }
1644
1645 #define TPV_QI0(__id1, __id2, __bv1, __bv2) \
1646         TPV_Q(PCI_VENDOR_ID_IBM, __id1, __id2, __bv1, __bv2)
1647
1648 #define TPV_QI1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1649         TPV_Q_X(PCI_VENDOR_ID_IBM, __id1, __id2,        \
1650                 __bv1, __bv2, __id1, __id2, __ev1, __ev2)
1651
1652 #define TPV_QI2(__bid1, __bid2, __bv1, __bv2,           \
1653                 __eid1, __eid2, __ev1, __ev2)           \
1654         TPV_Q_X(PCI_VENDOR_ID_IBM, __bid1, __bid2,      \
1655                 __bv1, __bv2, __eid1, __eid2, __ev1, __ev2)
1656
1657 #define TPV_QL0(__id1, __id2, __bv1, __bv2) \
1658         TPV_Q(PCI_VENDOR_ID_LENOVO, __id1, __id2, __bv1, __bv2)
1659
1660 #define TPV_QL1(__id1, __id2, __bv1, __bv2, __ev1, __ev2) \
1661         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __id1, __id2,     \
1662                 __bv1, __bv2, __id1, __id2, __ev1, __ev2)
1663
1664 #define TPV_QL2(__bid1, __bid2, __bv1, __bv2,           \
1665                 __eid1, __eid2, __ev1, __ev2)           \
1666         TPV_Q_X(PCI_VENDOR_ID_LENOVO, __bid1, __bid2,   \
1667                 __bv1, __bv2, __eid1, __eid2, __ev1, __ev2)
1668
1669 static const struct tpacpi_quirk tpacpi_bios_version_qtable[] __initconst = {
1670         /*  Numeric models ------------------ */
1671         /*      FW MODEL   BIOS VERS          */
1672         TPV_QI0('I', 'M',  '6', '5'),            /* 570 */
1673         TPV_QI0('I', 'U',  '2', '6'),            /* 570E */
1674         TPV_QI0('I', 'B',  '5', '4'),            /* 600 */
1675         TPV_QI0('I', 'H',  '4', '7'),            /* 600E */
1676         TPV_QI0('I', 'N',  '3', '6'),            /* 600E */
1677         TPV_QI0('I', 'T',  '5', '5'),            /* 600X */
1678         TPV_QI0('I', 'D',  '4', '8'),            /* 770, 770E, 770ED */
1679         TPV_QI0('I', 'I',  '4', '2'),            /* 770X */
1680         TPV_QI0('I', 'O',  '2', '3'),            /* 770Z */
1681
1682         /* A-series ------------------------- */
1683         /*      FW MODEL   BIOS VERS  EC VERS */
1684         TPV_QI0('I', 'W',  '5', '9'),            /* A20m */
1685         TPV_QI0('I', 'V',  '6', '9'),            /* A20p */
1686         TPV_QI0('1', '0',  '2', '6'),            /* A21e, A22e */
1687         TPV_QI0('K', 'U',  '3', '6'),            /* A21e */
1688         TPV_QI0('K', 'X',  '3', '6'),            /* A21m, A22m */
1689         TPV_QI0('K', 'Y',  '3', '8'),            /* A21p, A22p */
1690         TPV_QI0('1', 'B',  '1', '7'),            /* A22e */
1691         TPV_QI0('1', '3',  '2', '0'),            /* A22m */
1692         TPV_QI0('1', 'E',  '7', '3'),            /* A30/p (0) */
1693         TPV_QI1('1', 'G',  '4', '1',  '1', '7'), /* A31/p (0) */
1694         TPV_QI1('1', 'N',  '1', '6',  '0', '7'), /* A31/p (0) */
1695
1696         /* G-series ------------------------- */
1697         /*      FW MODEL   BIOS VERS          */
1698         TPV_QI0('1', 'T',  'A', '6'),            /* G40 */
1699         TPV_QI0('1', 'X',  '5', '7'),            /* G41 */
1700
1701         /* R-series, T-series --------------- */
1702         /*      FW MODEL   BIOS VERS  EC VERS */
1703         TPV_QI0('1', 'C',  'F', '0'),            /* R30 */
1704         TPV_QI0('1', 'F',  'F', '1'),            /* R31 */
1705         TPV_QI0('1', 'M',  '9', '7'),            /* R32 */
1706         TPV_QI0('1', 'O',  '6', '1'),            /* R40 */
1707         TPV_QI0('1', 'P',  '6', '5'),            /* R40 */
1708         TPV_QI0('1', 'S',  '7', '0'),            /* R40e */
1709         TPV_QI1('1', 'R',  'D', 'R',  '7', '1'), /* R50/p, R51,
1710                                                     T40/p, T41/p, T42/p (1) */
1711         TPV_QI1('1', 'V',  '7', '1',  '2', '8'), /* R50e, R51 (1) */
1712         TPV_QI1('7', '8',  '7', '1',  '0', '6'), /* R51e (1) */
1713         TPV_QI1('7', '6',  '6', '9',  '1', '6'), /* R52 (1) */
1714         TPV_QI1('7', '0',  '6', '9',  '2', '8'), /* R52, T43 (1) */
1715
1716         TPV_QI0('I', 'Y',  '6', '1'),            /* T20 */
1717         TPV_QI0('K', 'Z',  '3', '4'),            /* T21 */
1718         TPV_QI0('1', '6',  '3', '2'),            /* T22 */
1719         TPV_QI1('1', 'A',  '6', '4',  '2', '3'), /* T23 (0) */
1720         TPV_QI1('1', 'I',  '7', '1',  '2', '0'), /* T30 (0) */
1721         TPV_QI1('1', 'Y',  '6', '5',  '2', '9'), /* T43/p (1) */
1722
1723         TPV_QL1('7', '9',  'E', '3',  '5', '0'), /* T60/p */
1724         TPV_QL1('7', 'C',  'D', '2',  '2', '2'), /* R60, R60i */
1725         TPV_QL0('7', 'E',  'D', '0'),            /* R60e, R60i */
1726
1727         /*      BIOS FW    BIOS VERS  EC FW     EC VERS */
1728         TPV_QI2('1', 'W',  '9', '0',  '1', 'V', '2', '8'), /* R50e (1) */
1729         TPV_QL2('7', 'I',  '3', '4',  '7', '9', '5', '0'), /* T60/p wide */
1730
1731         /* X-series ------------------------- */
1732         /*      FW MODEL   BIOS VERS  EC VERS */
1733         TPV_QI0('I', 'Z',  '9', 'D'),            /* X20, X21 */
1734         TPV_QI0('1', 'D',  '7', '0'),            /* X22, X23, X24 */
1735         TPV_QI1('1', 'K',  '4', '8',  '1', '8'), /* X30 (0) */
1736         TPV_QI1('1', 'Q',  '9', '7',  '2', '3'), /* X31, X32 (0) */
1737         TPV_QI1('1', 'U',  'D', '3',  'B', '2'), /* X40 (0) */
1738         TPV_QI1('7', '4',  '6', '4',  '2', '7'), /* X41 (0) */
1739         TPV_QI1('7', '5',  '6', '0',  '2', '0'), /* X41t (0) */
1740
1741         TPV_QL0('7', 'B',  'D', '7'),            /* X60/s */
1742         TPV_QL0('7', 'J',  '3', '0'),            /* X60t */
1743
1744         /* (0) - older versions lack DMI EC fw string and functionality */
1745         /* (1) - older versions known to lack functionality */
1746 };
1747
1748 #undef TPV_QL1
1749 #undef TPV_QL0
1750 #undef TPV_QI2
1751 #undef TPV_QI1
1752 #undef TPV_QI0
1753 #undef TPV_Q_X
1754 #undef TPV_Q
1755
1756 static void __init tpacpi_check_outdated_fw(void)
1757 {
1758         unsigned long fwvers;
1759         u16 ec_version, bios_version;
1760
1761         fwvers = tpacpi_check_quirks(tpacpi_bios_version_qtable,
1762                                 ARRAY_SIZE(tpacpi_bios_version_qtable));
1763
1764         if (!fwvers)
1765                 return;
1766
1767         bios_version = fwvers & 0xffffU;
1768         ec_version = (fwvers >> 16) & 0xffffU;
1769
1770         /* note that unknown versions are set to 0x0000 and we use that */
1771         if ((bios_version > thinkpad_id.bios_release) ||
1772             (ec_version > thinkpad_id.ec_release &&
1773                                 ec_version != TPACPI_MATCH_ANY)) {
1774                 /*
1775                  * The changelogs would let us track down the exact
1776                  * reason, but it is just too much of a pain to track
1777                  * it.  We only list BIOSes that are either really
1778                  * broken, or really stable to begin with, so it is
1779                  * best if the user upgrades the firmware anyway.
1780                  */
1781                 printk(TPACPI_WARN
1782                         "WARNING: Outdated ThinkPad BIOS/EC firmware\n");
1783                 printk(TPACPI_WARN
1784                         "WARNING: This firmware may be missing critical bug "
1785                         "fixes and/or important features\n");
1786         }
1787 }
1788
1789 static bool __init tpacpi_is_fw_known(void)
1790 {
1791         return tpacpi_check_quirks(tpacpi_bios_version_qtable,
1792                         ARRAY_SIZE(tpacpi_bios_version_qtable)) != 0;
1793 }
1794
1795 /****************************************************************************
1796  ****************************************************************************
1797  *
1798  * Subdrivers
1799  *
1800  ****************************************************************************
1801  ****************************************************************************/
1802
1803 /*************************************************************************
1804  * thinkpad-acpi init subdriver
1805  */
1806
1807 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
1808 {
1809         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
1810         printk(TPACPI_INFO "%s\n", TPACPI_URL);
1811
1812         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
1813                 (thinkpad_id.bios_version_str) ?
1814                         thinkpad_id.bios_version_str : "unknown",
1815                 (thinkpad_id.ec_version_str) ?
1816                         thinkpad_id.ec_version_str : "unknown");
1817
1818         if (thinkpad_id.vendor && thinkpad_id.model_str)
1819                 printk(TPACPI_INFO "%s %s, model %s\n",
1820                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
1821                                 "IBM" : ((thinkpad_id.vendor ==
1822                                                 PCI_VENDOR_ID_LENOVO) ?
1823                                         "Lenovo" : "Unknown vendor"),
1824                         thinkpad_id.model_str,
1825                         (thinkpad_id.nummodel_str) ?
1826                                 thinkpad_id.nummodel_str : "unknown");
1827
1828         tpacpi_check_outdated_fw();
1829         return 0;
1830 }
1831
1832 static int thinkpad_acpi_driver_read(char *p)
1833 {
1834         int len = 0;
1835
1836         len += sprintf(p + len, "driver:\t\t%s\n", TPACPI_DESC);
1837         len += sprintf(p + len, "version:\t%s\n", TPACPI_VERSION);
1838
1839         return len;
1840 }
1841
1842 static struct ibm_struct thinkpad_acpi_driver_data = {
1843         .name = "driver",
1844         .read = thinkpad_acpi_driver_read,
1845 };
1846
1847 /*************************************************************************
1848  * Hotkey subdriver
1849  */
1850
1851 /*
1852  * ThinkPad firmware event model
1853  *
1854  * The ThinkPad firmware has two main event interfaces: normal ACPI
1855  * notifications (which follow the ACPI standard), and a private event
1856  * interface.
1857  *
1858  * The private event interface also issues events for the hotkeys.  As
1859  * the driver gained features, the event handling code ended up being
1860  * built around the hotkey subdriver.  This will need to be refactored
1861  * to a more formal event API eventually.
1862  *
1863  * Some "hotkeys" are actually supposed to be used as event reports,
1864  * such as "brightness has changed", "volume has changed", depending on
1865  * the ThinkPad model and how the firmware is operating.
1866  *
1867  * Unlike other classes, hotkey-class events have mask/unmask control on
1868  * non-ancient firmware.  However, how it behaves changes a lot with the
1869  * firmware model and version.
1870  */
1871
1872 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1873         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1874         TP_ACPI_HOTKEYSCAN_FNF2,
1875         TP_ACPI_HOTKEYSCAN_FNF3,
1876         TP_ACPI_HOTKEYSCAN_FNF4,
1877         TP_ACPI_HOTKEYSCAN_FNF5,
1878         TP_ACPI_HOTKEYSCAN_FNF6,
1879         TP_ACPI_HOTKEYSCAN_FNF7,
1880         TP_ACPI_HOTKEYSCAN_FNF8,
1881         TP_ACPI_HOTKEYSCAN_FNF9,
1882         TP_ACPI_HOTKEYSCAN_FNF10,
1883         TP_ACPI_HOTKEYSCAN_FNF11,
1884         TP_ACPI_HOTKEYSCAN_FNF12,
1885         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1886         TP_ACPI_HOTKEYSCAN_FNINSERT,
1887         TP_ACPI_HOTKEYSCAN_FNDELETE,
1888         TP_ACPI_HOTKEYSCAN_FNHOME,
1889         TP_ACPI_HOTKEYSCAN_FNEND,
1890         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1891         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1892         TP_ACPI_HOTKEYSCAN_FNSPACE,
1893         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1894         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1895         TP_ACPI_HOTKEYSCAN_MUTE,
1896         TP_ACPI_HOTKEYSCAN_THINKPAD,
1897 };
1898
1899 enum {  /* Keys/events available through NVRAM polling */
1900         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1901         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1902 };
1903
1904 enum {  /* Positions of some of the keys in hotkey masks */
1905         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1906         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1907         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1908         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1909         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1910         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1911         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1912         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1913         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1914         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1915         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1916 };
1917
1918 enum {  /* NVRAM to ACPI HKEY group map */
1919         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1920                                           TP_ACPI_HKEY_ZOOM_MASK |
1921                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1922                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1923         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1924                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1925         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1926                                           TP_ACPI_HKEY_VOLDWN_MASK |
1927                                           TP_ACPI_HKEY_MUTE_MASK,
1928 };
1929
1930 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1931 struct tp_nvram_state {
1932        u16 thinkpad_toggle:1;
1933        u16 zoom_toggle:1;
1934        u16 display_toggle:1;
1935        u16 thinklight_toggle:1;
1936        u16 hibernate_toggle:1;
1937        u16 displayexp_toggle:1;
1938        u16 display_state:1;
1939        u16 brightness_toggle:1;
1940        u16 volume_toggle:1;
1941        u16 mute:1;
1942
1943        u8 brightness_level;
1944        u8 volume_level;
1945 };
1946
1947 /* kthread for the hotkey poller */
1948 static struct task_struct *tpacpi_hotkey_task;
1949
1950 /* Acquired while the poller kthread is running, use to sync start/stop */
1951 static struct mutex hotkey_thread_mutex;
1952
1953 /*
1954  * Acquire mutex to write poller control variables as an
1955  * atomic block.
1956  *
1957  * Increment hotkey_config_change when changing them if you
1958  * want the kthread to forget old state.
1959  *
1960  * See HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
1961  */
1962 static struct mutex hotkey_thread_data_mutex;
1963 static unsigned int hotkey_config_change;
1964
1965 /*
1966  * hotkey poller control variables
1967  *
1968  * Must be atomic or readers will also need to acquire mutex
1969  *
1970  * HOTKEY_CONFIG_CRITICAL_START/HOTKEY_CONFIG_CRITICAL_END
1971  * should be used only when the changes need to be taken as
1972  * a block, OR when one needs to force the kthread to forget
1973  * old state.
1974  */
1975 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
1976 static unsigned int hotkey_poll_freq = 10; /* Hz */
1977
1978 #define HOTKEY_CONFIG_CRITICAL_START \
1979         do { \
1980                 mutex_lock(&hotkey_thread_data_mutex); \
1981                 hotkey_config_change++; \
1982         } while (0);
1983 #define HOTKEY_CONFIG_CRITICAL_END \
1984         mutex_unlock(&hotkey_thread_data_mutex);
1985
1986 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1987
1988 #define hotkey_source_mask 0U
1989 #define HOTKEY_CONFIG_CRITICAL_START
1990 #define HOTKEY_CONFIG_CRITICAL_END
1991
1992 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1993
1994 static struct mutex hotkey_mutex;
1995
1996 static enum {   /* Reasons for waking up */
1997         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
1998         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
1999         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
2000 } hotkey_wakeup_reason;
2001
2002 static int hotkey_autosleep_ack;
2003
2004 static u32 hotkey_orig_mask;            /* events the BIOS had enabled */
2005 static u32 hotkey_all_mask;             /* all events supported in fw */
2006 static u32 hotkey_reserved_mask;        /* events better left disabled */
2007 static u32 hotkey_driver_mask;          /* events needed by the driver */
2008 static u32 hotkey_user_mask;            /* events visible to userspace */
2009 static u32 hotkey_acpi_mask;            /* events enabled in firmware */
2010
2011 static unsigned int hotkey_report_mode;
2012
2013 static u16 *hotkey_keycode_map;
2014
2015 static struct attribute_set *hotkey_dev_attributes;
2016
2017 /* HKEY.MHKG() return bits */
2018 #define TP_HOTKEY_TABLET_MASK (1 << 3)
2019
2020 static int hotkey_get_wlsw(void)
2021 {
2022         int status;
2023
2024         if (!tp_features.hotkey_wlsw)
2025                 return -ENODEV;
2026
2027 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2028         if (dbg_wlswemul)
2029                 return (tpacpi_wlsw_emulstate) ?
2030                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2031 #endif
2032
2033         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
2034                 return -EIO;
2035
2036         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2037 }
2038
2039 static int hotkey_get_tablet_mode(int *status)
2040 {
2041         int s;
2042
2043         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
2044                 return -EIO;
2045
2046         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
2047         return 0;
2048 }
2049
2050 /*
2051  * Reads current event mask from firmware, and updates
2052  * hotkey_acpi_mask accordingly.  Also resets any bits
2053  * from hotkey_user_mask that are unavailable to be
2054  * delivered (shadow requirement of the userspace ABI).
2055  *
2056  * Call with hotkey_mutex held
2057  */
2058 static int hotkey_mask_get(void)
2059 {
2060         if (tp_features.hotkey_mask) {
2061                 u32 m = 0;
2062
2063                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
2064                         return -EIO;
2065
2066                 hotkey_acpi_mask = m;
2067         } else {
2068                 /* no mask support doesn't mean no event support... */
2069                 hotkey_acpi_mask = hotkey_all_mask;
2070         }
2071
2072         /* sync userspace-visible mask */
2073         hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask);
2074
2075         return 0;
2076 }
2077
2078 void static hotkey_mask_warn_incomplete_mask(void)
2079 {
2080         /* log only what the user can fix... */
2081         const u32 wantedmask = hotkey_driver_mask &
2082                 ~(hotkey_acpi_mask | hotkey_source_mask) &
2083                 (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK);
2084
2085         if (wantedmask)
2086                 printk(TPACPI_NOTICE
2087                         "required events 0x%08x not enabled!\n",
2088                         wantedmask);
2089 }
2090
2091 /*
2092  * Set the firmware mask when supported
2093  *
2094  * Also calls hotkey_mask_get to update hotkey_acpi_mask.
2095  *
2096  * NOTE: does not set bits in hotkey_user_mask, but may reset them.
2097  *
2098  * Call with hotkey_mutex held
2099  */
2100 static int hotkey_mask_set(u32 mask)
2101 {
2102         int i;
2103         int rc = 0;
2104
2105         const u32 fwmask = mask & ~hotkey_source_mask;
2106
2107         if (tp_features.hotkey_mask) {
2108                 for (i = 0; i < 32; i++) {
2109                         if (!acpi_evalf(hkey_handle,
2110                                         NULL, "MHKM", "vdd", i + 1,
2111                                         !!(mask & (1 << i)))) {
2112                                 rc = -EIO;
2113                                 break;
2114                         }
2115                 }
2116         }
2117
2118         /*
2119          * We *must* make an inconditional call to hotkey_mask_get to
2120          * refresh hotkey_acpi_mask and update hotkey_user_mask
2121          *
2122          * Take the opportunity to also log when we cannot _enable_
2123          * a given event.
2124          */
2125         if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) {
2126                 printk(TPACPI_NOTICE
2127                        "asked for hotkey mask 0x%08x, but "
2128                        "firmware forced it to 0x%08x\n",
2129                        fwmask, hotkey_acpi_mask);
2130         }
2131
2132         hotkey_mask_warn_incomplete_mask();
2133
2134         return rc;
2135 }
2136
2137 /*
2138  * Sets hotkey_user_mask and tries to set the firmware mask
2139  *
2140  * Call with hotkey_mutex held
2141  */
2142 static int hotkey_user_mask_set(const u32 mask)
2143 {
2144         int rc;
2145
2146         /* Give people a chance to notice they are doing something that
2147          * is bound to go boom on their users sooner or later */
2148         if (!tp_warned.hotkey_mask_ff &&
2149             (mask == 0xffff || mask == 0xffffff ||
2150              mask == 0xffffffff)) {
2151                 tp_warned.hotkey_mask_ff = 1;
2152                 printk(TPACPI_NOTICE
2153                        "setting the hotkey mask to 0x%08x is likely "
2154                        "not the best way to go about it\n", mask);
2155                 printk(TPACPI_NOTICE
2156                        "please consider using the driver defaults, "
2157                        "and refer to up-to-date thinkpad-acpi "
2158                        "documentation\n");
2159         }
2160
2161         /* Try to enable what the user asked for, plus whatever we need.
2162          * this syncs everything but won't enable bits in hotkey_user_mask */
2163         rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask);
2164
2165         /* Enable the available bits in hotkey_user_mask */
2166         hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask);
2167
2168         return rc;
2169 }
2170
2171 static int hotkey_status_get(int *status)
2172 {
2173         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
2174                 return -EIO;
2175
2176         return 0;
2177 }
2178
2179 static int hotkey_status_set(bool enable)
2180 {
2181         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
2182                 return -EIO;
2183
2184         return 0;
2185 }
2186
2187 static void tpacpi_input_send_tabletsw(void)
2188 {
2189         int state;
2190
2191         if (tp_features.hotkey_tablet &&
2192             !hotkey_get_tablet_mode(&state)) {
2193                 mutex_lock(&tpacpi_inputdev_send_mutex);
2194
2195                 input_report_switch(tpacpi_inputdev,
2196                                     SW_TABLET_MODE, !!state);
2197                 input_sync(tpacpi_inputdev);
2198
2199                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2200         }
2201 }
2202
2203 /* Do NOT call without validating scancode first */
2204 static void tpacpi_input_send_key(const unsigned int scancode)
2205 {
2206         const unsigned int keycode = hotkey_keycode_map[scancode];
2207
2208         if (keycode != KEY_RESERVED) {
2209                 mutex_lock(&tpacpi_inputdev_send_mutex);
2210
2211                 input_report_key(tpacpi_inputdev, keycode, 1);
2212                 if (keycode == KEY_UNKNOWN)
2213                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2214                                     scancode);
2215                 input_sync(tpacpi_inputdev);
2216
2217                 input_report_key(tpacpi_inputdev, keycode, 0);
2218                 if (keycode == KEY_UNKNOWN)
2219                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2220                                     scancode);
2221                 input_sync(tpacpi_inputdev);
2222
2223                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2224         }
2225 }
2226
2227 /* Do NOT call without validating scancode first */
2228 static void tpacpi_input_send_key_masked(const unsigned int scancode)
2229 {
2230         if (hotkey_user_mask & (1 << scancode))
2231                 tpacpi_input_send_key(scancode);
2232 }
2233
2234 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2235 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
2236
2237 /* Do NOT call without validating scancode first */
2238 static void tpacpi_hotkey_send_key(unsigned int scancode)
2239 {
2240         tpacpi_input_send_key_masked(scancode);
2241         if (hotkey_report_mode < 2) {
2242                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
2243                                                 0x80, 0x1001 + scancode);
2244         }
2245 }
2246
2247 static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m)
2248 {
2249         u8 d;
2250
2251         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
2252                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
2253                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
2254                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
2255                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
2256                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
2257         }
2258         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
2259                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
2260                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2261         }
2262         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2263                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2264                 n->displayexp_toggle =
2265                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2266         }
2267         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2268                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2269                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2270                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2271                 n->brightness_toggle =
2272                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2273         }
2274         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2275                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2276                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2277                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2278                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2279                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2280         }
2281 }
2282
2283 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2284                                            struct tp_nvram_state *newn,
2285                                            const u32 event_mask)
2286 {
2287
2288 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2289         do { \
2290                 if ((event_mask & (1 << __scancode)) && \
2291                     oldn->__member != newn->__member) \
2292                         tpacpi_hotkey_send_key(__scancode); \
2293         } while (0)
2294
2295 #define TPACPI_MAY_SEND_KEY(__scancode) \
2296         do { \
2297                 if (event_mask & (1 << __scancode)) \
2298                         tpacpi_hotkey_send_key(__scancode); \
2299         } while (0)
2300
2301         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2302         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2303         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2304         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2305
2306         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2307
2308         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2309
2310         /* handle volume */
2311         if (oldn->volume_toggle != newn->volume_toggle) {
2312                 if (oldn->mute != newn->mute) {
2313                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2314                 }
2315                 if (oldn->volume_level > newn->volume_level) {
2316                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2317                 } else if (oldn->volume_level < newn->volume_level) {
2318                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2319                 } else if (oldn->mute == newn->mute) {
2320                         /* repeated key presses that didn't change state */
2321                         if (newn->mute) {
2322                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2323                         } else if (newn->volume_level != 0) {
2324                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2325                         } else {
2326                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2327                         }
2328                 }
2329         }
2330
2331         /* handle brightness */
2332         if (oldn->brightness_toggle != newn->brightness_toggle) {
2333                 if (oldn->brightness_level < newn->brightness_level) {
2334                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2335                 } else if (oldn->brightness_level > newn->brightness_level) {
2336                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2337                 } else {
2338                         /* repeated key presses that didn't change state */
2339                         if (newn->brightness_level != 0) {
2340                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2341                         } else {
2342                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2343                         }
2344                 }
2345         }
2346
2347 #undef TPACPI_COMPARE_KEY
2348 #undef TPACPI_MAY_SEND_KEY
2349 }
2350
2351 /*
2352  * Polling driver
2353  *
2354  * We track all events in hotkey_source_mask all the time, since
2355  * most of them are edge-based.  We only issue those requested by
2356  * hotkey_user_mask or hotkey_driver_mask, though.
2357  */
2358 static int hotkey_kthread(void *data)
2359 {
2360         struct tp_nvram_state s[2];
2361         u32 poll_mask, event_mask;
2362         unsigned int si, so;
2363         unsigned long t;
2364         unsigned int change_detector, must_reset;
2365         unsigned int poll_freq;
2366
2367         mutex_lock(&hotkey_thread_mutex);
2368
2369         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2370                 goto exit;
2371
2372         set_freezable();
2373
2374         so = 0;
2375         si = 1;
2376         t = 0;
2377
2378         /* Initial state for compares */
2379         mutex_lock(&hotkey_thread_data_mutex);
2380         change_detector = hotkey_config_change;
2381         poll_mask = hotkey_source_mask;
2382         event_mask = hotkey_source_mask &
2383                         (hotkey_driver_mask | hotkey_user_mask);
2384         poll_freq = hotkey_poll_freq;
2385         mutex_unlock(&hotkey_thread_data_mutex);
2386         hotkey_read_nvram(&s[so], poll_mask);
2387
2388         while (!kthread_should_stop()) {
2389                 if (t == 0) {
2390                         if (likely(poll_freq))
2391                                 t = 1000/poll_freq;
2392                         else
2393                                 t = 100;        /* should never happen... */
2394                 }
2395                 t = msleep_interruptible(t);
2396                 if (unlikely(kthread_should_stop()))
2397                         break;
2398                 must_reset = try_to_freeze();
2399                 if (t > 0 && !must_reset)
2400                         continue;
2401
2402                 mutex_lock(&hotkey_thread_data_mutex);
2403                 if (must_reset || hotkey_config_change != change_detector) {
2404                         /* forget old state on thaw or config change */
2405                         si = so;
2406                         t = 0;
2407                         change_detector = hotkey_config_change;
2408                 }
2409                 poll_mask = hotkey_source_mask;
2410                 event_mask = hotkey_source_mask &
2411                                 (hotkey_driver_mask | hotkey_user_mask);
2412                 poll_freq = hotkey_poll_freq;
2413                 mutex_unlock(&hotkey_thread_data_mutex);
2414
2415                 if (likely(poll_mask)) {
2416                         hotkey_read_nvram(&s[si], poll_mask);
2417                         if (likely(si != so)) {
2418                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2419                                                                 event_mask);
2420                         }
2421                 }
2422
2423                 so = si;
2424                 si ^= 1;
2425         }
2426
2427 exit:
2428         mutex_unlock(&hotkey_thread_mutex);
2429         return 0;
2430 }
2431
2432 /* call with hotkey_mutex held */
2433 static void hotkey_poll_stop_sync(void)
2434 {
2435         if (tpacpi_hotkey_task) {
2436                 if (frozen(tpacpi_hotkey_task) ||
2437                     freezing(tpacpi_hotkey_task))
2438                         thaw_process(tpacpi_hotkey_task);
2439
2440                 kthread_stop(tpacpi_hotkey_task);
2441                 tpacpi_hotkey_task = NULL;
2442                 mutex_lock(&hotkey_thread_mutex);
2443                 /* at this point, the thread did exit */
2444                 mutex_unlock(&hotkey_thread_mutex);
2445         }
2446 }
2447
2448 /* call with hotkey_mutex held */
2449 static void hotkey_poll_setup(bool may_warn)
2450 {
2451         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2452         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2453
2454         if (hotkey_poll_freq > 0 &&
2455             (poll_driver_mask ||
2456              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2457                 if (!tpacpi_hotkey_task) {
2458                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2459                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2460                         if (IS_ERR(tpacpi_hotkey_task)) {
2461                                 tpacpi_hotkey_task = NULL;
2462                                 printk(TPACPI_ERR
2463                                        "could not create kernel thread "
2464                                        "for hotkey polling\n");
2465                         }
2466                 }
2467         } else {
2468                 hotkey_poll_stop_sync();
2469                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2470                     hotkey_poll_freq == 0) {
2471                         printk(TPACPI_NOTICE
2472                                 "hot keys 0x%08x and/or events 0x%08x "
2473                                 "require polling, which is currently "
2474                                 "disabled\n",
2475                                 poll_user_mask, poll_driver_mask);
2476                 }
2477         }
2478 }
2479
2480 static void hotkey_poll_setup_safe(bool may_warn)
2481 {
2482         mutex_lock(&hotkey_mutex);
2483         hotkey_poll_setup(may_warn);
2484         mutex_unlock(&hotkey_mutex);
2485 }
2486
2487 /* call with hotkey_mutex held */
2488 static void hotkey_poll_set_freq(unsigned int freq)
2489 {
2490         if (!freq)
2491                 hotkey_poll_stop_sync();
2492
2493         hotkey_poll_freq = freq;
2494 }
2495
2496 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2497
2498 static void hotkey_poll_setup_safe(bool __unused)
2499 {
2500 }
2501
2502 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2503
2504 static int hotkey_inputdev_open(struct input_dev *dev)
2505 {
2506         switch (tpacpi_lifecycle) {
2507         case TPACPI_LIFE_INIT:
2508                 /*
2509                  * hotkey_init will call hotkey_poll_setup_safe
2510                  * at the appropriate moment
2511                  */
2512                 return 0;
2513         case TPACPI_LIFE_EXITING:
2514                 return -EBUSY;
2515         case TPACPI_LIFE_RUNNING:
2516                 hotkey_poll_setup_safe(false);
2517                 return 0;
2518         }
2519
2520         /* Should only happen if tpacpi_lifecycle is corrupt */
2521         BUG();
2522         return -EBUSY;
2523 }
2524
2525 static void hotkey_inputdev_close(struct input_dev *dev)
2526 {
2527         /* disable hotkey polling when possible */
2528         if (tpacpi_lifecycle == TPACPI_LIFE_RUNNING &&
2529             !(hotkey_source_mask & hotkey_driver_mask))
2530                 hotkey_poll_setup_safe(false);
2531 }
2532
2533 /* sysfs hotkey enable ------------------------------------------------- */
2534 static ssize_t hotkey_enable_show(struct device *dev,
2535                            struct device_attribute *attr,
2536                            char *buf)
2537 {
2538         int res, status;
2539
2540         printk_deprecated_attribute("hotkey_enable",
2541                         "Hotkey reporting is always enabled");
2542
2543         res = hotkey_status_get(&status);
2544         if (res)
2545                 return res;
2546
2547         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2548 }
2549
2550 static ssize_t hotkey_enable_store(struct device *dev,
2551                             struct device_attribute *attr,
2552                             const char *buf, size_t count)
2553 {
2554         unsigned long t;
2555
2556         printk_deprecated_attribute("hotkey_enable",
2557                         "Hotkeys can be disabled through hotkey_mask");
2558
2559         if (parse_strtoul(buf, 1, &t))
2560                 return -EINVAL;
2561
2562         if (t == 0)
2563                 return -EPERM;
2564
2565         return count;
2566 }
2567
2568 static struct device_attribute dev_attr_hotkey_enable =
2569         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2570                 hotkey_enable_show, hotkey_enable_store);
2571
2572 /* sysfs hotkey mask --------------------------------------------------- */
2573 static ssize_t hotkey_mask_show(struct device *dev,
2574                            struct device_attribute *attr,
2575                            char *buf)
2576 {
2577         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2578 }
2579
2580 static ssize_t hotkey_mask_store(struct device *dev,
2581                             struct device_attribute *attr,
2582                             const char *buf, size_t count)
2583 {
2584         unsigned long t;
2585         int res;
2586
2587         if (parse_strtoul(buf, 0xffffffffUL, &t))
2588                 return -EINVAL;
2589
2590         if (mutex_lock_killable(&hotkey_mutex))
2591                 return -ERESTARTSYS;
2592
2593         res = hotkey_user_mask_set(t);
2594
2595 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2596         hotkey_poll_setup(true);
2597 #endif
2598
2599         mutex_unlock(&hotkey_mutex);
2600
2601         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2602
2603         return (res) ? res : count;
2604 }
2605
2606 static struct device_attribute dev_attr_hotkey_mask =
2607         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2608                 hotkey_mask_show, hotkey_mask_store);
2609
2610 /* sysfs hotkey bios_enabled ------------------------------------------- */
2611 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2612                            struct device_attribute *attr,
2613                            char *buf)
2614 {
2615         return sprintf(buf, "0\n");
2616 }
2617
2618 static struct device_attribute dev_attr_hotkey_bios_enabled =
2619         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2620
2621 /* sysfs hotkey bios_mask ---------------------------------------------- */
2622 static ssize_t hotkey_bios_mask_show(struct device *dev,
2623                            struct device_attribute *attr,
2624                            char *buf)
2625 {
2626         printk_deprecated_attribute("hotkey_bios_mask",
2627                         "This attribute is useless.");
2628         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2629 }
2630
2631 static struct device_attribute dev_attr_hotkey_bios_mask =
2632         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2633
2634 /* sysfs hotkey all_mask ----------------------------------------------- */
2635 static ssize_t hotkey_all_mask_show(struct device *dev,
2636                            struct device_attribute *attr,
2637                            char *buf)
2638 {
2639         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2640                                 hotkey_all_mask | hotkey_source_mask);
2641 }
2642
2643 static struct device_attribute dev_attr_hotkey_all_mask =
2644         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2645
2646 /* sysfs hotkey recommended_mask --------------------------------------- */
2647 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2648                                             struct device_attribute *attr,
2649                                             char *buf)
2650 {
2651         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2652                         (hotkey_all_mask | hotkey_source_mask)
2653                         & ~hotkey_reserved_mask);
2654 }
2655
2656 static struct device_attribute dev_attr_hotkey_recommended_mask =
2657         __ATTR(hotkey_recommended_mask, S_IRUGO,
2658                 hotkey_recommended_mask_show, NULL);
2659
2660 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2661
2662 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2663 static ssize_t hotkey_source_mask_show(struct device *dev,
2664                            struct device_attribute *attr,
2665                            char *buf)
2666 {
2667         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2668 }
2669
2670 static ssize_t hotkey_source_mask_store(struct device *dev,
2671                             struct device_attribute *attr,
2672                             const char *buf, size_t count)
2673 {
2674         unsigned long t;
2675         u32 r_ev;
2676         int rc;
2677
2678         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2679                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2680                 return -EINVAL;
2681
2682         if (mutex_lock_killable(&hotkey_mutex))
2683                 return -ERESTARTSYS;
2684
2685         HOTKEY_CONFIG_CRITICAL_START
2686         hotkey_source_mask = t;
2687         HOTKEY_CONFIG_CRITICAL_END
2688
2689         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2690                         ~hotkey_source_mask);
2691         hotkey_poll_setup(true);
2692
2693         /* check if events needed by the driver got disabled */
2694         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2695                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2696
2697         mutex_unlock(&hotkey_mutex);
2698
2699         if (rc < 0)
2700                 printk(TPACPI_ERR "hotkey_source_mask: failed to update the"
2701                         "firmware event mask!\n");
2702
2703         if (r_ev)
2704                 printk(TPACPI_NOTICE "hotkey_source_mask: "
2705                         "some important events were disabled: "
2706                         "0x%04x\n", r_ev);
2707
2708         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2709
2710         return (rc < 0) ? rc : count;
2711 }
2712
2713 static struct device_attribute dev_attr_hotkey_source_mask =
2714         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2715                 hotkey_source_mask_show, hotkey_source_mask_store);
2716
2717 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2718 static ssize_t hotkey_poll_freq_show(struct device *dev,
2719                            struct device_attribute *attr,
2720                            char *buf)
2721 {
2722         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2723 }
2724
2725 static ssize_t hotkey_poll_freq_store(struct device *dev,
2726                             struct device_attribute *attr,
2727                             const char *buf, size_t count)
2728 {
2729         unsigned long t;
2730
2731         if (parse_strtoul(buf, 25, &t))
2732                 return -EINVAL;
2733
2734         if (mutex_lock_killable(&hotkey_mutex))
2735                 return -ERESTARTSYS;
2736
2737         hotkey_poll_set_freq(t);
2738         hotkey_poll_setup(true);
2739
2740         mutex_unlock(&hotkey_mutex);
2741
2742         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2743
2744         return count;
2745 }
2746
2747 static struct device_attribute dev_attr_hotkey_poll_freq =
2748         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2749                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2750
2751 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2752
2753 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2754 static ssize_t hotkey_radio_sw_show(struct device *dev,
2755                            struct device_attribute *attr,
2756                            char *buf)
2757 {
2758         int res;
2759         res = hotkey_get_wlsw();
2760         if (res < 0)
2761                 return res;
2762
2763         /* Opportunistic update */
2764         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2765
2766         return snprintf(buf, PAGE_SIZE, "%d\n",
2767                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2768 }
2769
2770 static struct device_attribute dev_attr_hotkey_radio_sw =
2771         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
2772
2773 static void hotkey_radio_sw_notify_change(void)
2774 {
2775         if (tp_features.hotkey_wlsw)
2776                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2777                              "hotkey_radio_sw");
2778 }
2779
2780 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2781 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2782                            struct device_attribute *attr,
2783                            char *buf)
2784 {
2785         int res, s;
2786         res = hotkey_get_tablet_mode(&s);
2787         if (res < 0)
2788                 return res;
2789
2790         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2791 }
2792
2793 static struct device_attribute dev_attr_hotkey_tablet_mode =
2794         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2795
2796 static void hotkey_tablet_mode_notify_change(void)
2797 {
2798         if (tp_features.hotkey_tablet)
2799                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2800                              "hotkey_tablet_mode");
2801 }
2802
2803 /* sysfs hotkey report_mode -------------------------------------------- */
2804 static ssize_t hotkey_report_mode_show(struct device *dev,
2805                            struct device_attribute *attr,
2806                            char *buf)
2807 {
2808         return snprintf(buf, PAGE_SIZE, "%d\n",
2809                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2810 }
2811
2812 static struct device_attribute dev_attr_hotkey_report_mode =
2813         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2814
2815 /* sysfs wakeup reason (pollable) -------------------------------------- */
2816 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2817                            struct device_attribute *attr,
2818                            char *buf)
2819 {
2820         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2821 }
2822
2823 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2824         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2825
2826 static void hotkey_wakeup_reason_notify_change(void)
2827 {
2828         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2829                      "wakeup_reason");
2830 }
2831
2832 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2833 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2834                            struct device_attribute *attr,
2835                            char *buf)
2836 {
2837         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2838 }
2839
2840 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2841         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2842                hotkey_wakeup_hotunplug_complete_show, NULL);
2843
2844 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2845 {
2846         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2847                      "wakeup_hotunplug_complete");
2848 }
2849
2850 /* --------------------------------------------------------------------- */
2851
2852 static struct attribute *hotkey_attributes[] __initdata = {
2853         &dev_attr_hotkey_enable.attr,
2854         &dev_attr_hotkey_bios_enabled.attr,
2855         &dev_attr_hotkey_bios_mask.attr,
2856         &dev_attr_hotkey_report_mode.attr,
2857         &dev_attr_hotkey_wakeup_reason.attr,
2858         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2859         &dev_attr_hotkey_mask.attr,
2860         &dev_attr_hotkey_all_mask.attr,
2861         &dev_attr_hotkey_recommended_mask.attr,
2862 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2863         &dev_attr_hotkey_source_mask.attr,
2864         &dev_attr_hotkey_poll_freq.attr,
2865 #endif
2866 };
2867
2868 /*
2869  * Sync both the hw and sw blocking state of all switches
2870  */
2871 static void tpacpi_send_radiosw_update(void)
2872 {
2873         int wlsw;
2874
2875         /*
2876          * We must sync all rfkill controllers *before* issuing any
2877          * rfkill input events, or we will race the rfkill core input
2878          * handler.
2879          *
2880          * tpacpi_inputdev_send_mutex works as a syncronization point
2881          * for the above.
2882          *
2883          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2884          */
2885
2886         wlsw = hotkey_get_wlsw();
2887
2888         /* Sync hw blocking state first if it is hw-blocked */
2889         if (wlsw == TPACPI_RFK_RADIO_OFF)
2890                 tpacpi_rfk_update_hwblock_state(true);
2891
2892         /* Sync sw blocking state */
2893         tpacpi_rfk_update_swstate_all();
2894
2895         /* Sync hw blocking state last if it is hw-unblocked */
2896         if (wlsw == TPACPI_RFK_RADIO_ON)
2897                 tpacpi_rfk_update_hwblock_state(false);
2898
2899         /* Issue rfkill input event for WLSW switch */
2900         if (!(wlsw < 0)) {
2901                 mutex_lock(&tpacpi_inputdev_send_mutex);
2902
2903                 input_report_switch(tpacpi_inputdev,
2904                                     SW_RFKILL_ALL, (wlsw > 0));
2905                 input_sync(tpacpi_inputdev);
2906
2907                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2908         }
2909
2910         /*
2911          * this can be unconditional, as we will poll state again
2912          * if userspace uses the notify to read data
2913          */
2914         hotkey_radio_sw_notify_change();
2915 }
2916
2917 static void hotkey_exit(void)
2918 {
2919 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2920         mutex_lock(&hotkey_mutex);
2921         hotkey_poll_stop_sync();
2922         mutex_unlock(&hotkey_mutex);
2923 #endif
2924
2925         if (hotkey_dev_attributes)
2926                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
2927
2928         kfree(hotkey_keycode_map);
2929
2930         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
2931                    "restoring original HKEY status and mask\n");
2932         /* yes, there is a bitwise or below, we want the
2933          * functions to be called even if one of them fail */
2934         if (((tp_features.hotkey_mask &&
2935               hotkey_mask_set(hotkey_orig_mask)) |
2936              hotkey_status_set(false)) != 0)
2937                 printk(TPACPI_ERR
2938                        "failed to restore hot key mask "
2939                        "to BIOS defaults\n");
2940 }
2941
2942 static void __init hotkey_unmap(const unsigned int scancode)
2943 {
2944         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
2945                 clear_bit(hotkey_keycode_map[scancode],
2946                           tpacpi_inputdev->keybit);
2947                 hotkey_keycode_map[scancode] = KEY_RESERVED;
2948         }
2949 }
2950
2951 /*
2952  * HKEY quirks:
2953  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
2954  */
2955
2956 #define TPACPI_HK_Q_INIMASK     0x0001
2957
2958 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
2959         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
2960         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
2961         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
2962         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
2963         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
2964         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
2965         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
2966         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
2967         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
2968         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
2969         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
2970         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
2971         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
2972         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
2973         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
2974         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
2975         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
2976         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
2977         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
2978 };
2979
2980 static int __init hotkey_init(struct ibm_init_struct *iibm)
2981 {
2982         /* Requirements for changing the default keymaps:
2983          *
2984          * 1. Many of the keys are mapped to KEY_RESERVED for very
2985          *    good reasons.  Do not change them unless you have deep
2986          *    knowledge on the IBM and Lenovo ThinkPad firmware for
2987          *    the various ThinkPad models.  The driver behaves
2988          *    differently for KEY_RESERVED: such keys have their
2989          *    hot key mask *unset* in mask_recommended, and also
2990          *    in the initial hot key mask programmed into the
2991          *    firmware at driver load time, which means the firm-
2992          *    ware may react very differently if you change them to
2993          *    something else;
2994          *
2995          * 2. You must be subscribed to the linux-thinkpad and
2996          *    ibm-acpi-devel mailing lists, and you should read the
2997          *    list archives since 2007 if you want to change the
2998          *    keymaps.  This requirement exists so that you will
2999          *    know the past history of problems with the thinkpad-
3000          *    acpi driver keymaps, and also that you will be
3001          *    listening to any bug reports;
3002          *
3003          * 3. Do not send thinkpad-acpi specific patches directly to
3004          *    for merging, *ever*.  Send them to the linux-acpi
3005          *    mailinglist for comments.  Merging is to be done only
3006          *    through acpi-test and the ACPI maintainer.
3007          *
3008          * If the above is too much to ask, don't change the keymap.
3009          * Ask the thinkpad-acpi maintainer to do it, instead.
3010          */
3011         static u16 ibm_keycode_map[] __initdata = {
3012                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3013                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
3014                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3015                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3016
3017                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3018                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3019                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3020                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3021
3022                 /* brightness: firmware always reacts to them */
3023                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3024                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3025
3026                 /* Thinklight: firmware always react to it */
3027                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3028
3029                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3030                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3031
3032                 /* Volume: firmware always react to it and reprograms
3033                  * the built-in *extra* mixer.  Never map it to control
3034                  * another mixer by default. */
3035                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3036                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3037                 KEY_RESERVED,   /* 0x16: MUTE */
3038
3039                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3040
3041                 /* (assignments unknown, please report if found) */
3042                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3043                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3044         };
3045         static u16 lenovo_keycode_map[] __initdata = {
3046                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3047                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3048                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3049                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3050
3051                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3052                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3053                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3054                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3055
3056                 /* These should be enabled --only-- when ACPI video
3057                  * is disabled (i.e. in "vendor" mode), and are handled
3058                  * in a special way by the init code */
3059                 KEY_BRIGHTNESSUP,       /* 0x0F: FN+HOME (brightness up) */
3060                 KEY_BRIGHTNESSDOWN,     /* 0x10: FN+END (brightness down) */
3061
3062                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3063
3064                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3065                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3066
3067                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
3068                  * react to it and reprograms the built-in *extra* mixer.
3069                  * Never map it to control another mixer by default.
3070                  *
3071                  * T60?, T61, R60?, R61: firmware and EC tries to send
3072                  * these over the regular keyboard, so these are no-ops,
3073                  * but there are still weird bugs re. MUTE, so do not
3074                  * change unless you get test reports from all Lenovo
3075                  * models.  May cause the BIOS to interfere with the
3076                  * HDA mixer.
3077                  */
3078                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3079                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3080                 KEY_RESERVED,   /* 0x16: MUTE */
3081
3082                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3083
3084                 /* (assignments unknown, please report if found) */
3085                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3086                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3087         };
3088
3089 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
3090 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
3091 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
3092
3093         int res, i;
3094         int status;
3095         int hkeyv;
3096
3097         unsigned long quirks;
3098
3099         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3100                         "initializing hotkey subdriver\n");
3101
3102         BUG_ON(!tpacpi_inputdev);
3103         BUG_ON(tpacpi_inputdev->open != NULL ||
3104                tpacpi_inputdev->close != NULL);
3105
3106         TPACPI_ACPIHANDLE_INIT(hkey);
3107         mutex_init(&hotkey_mutex);
3108
3109 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3110         mutex_init(&hotkey_thread_mutex);
3111         mutex_init(&hotkey_thread_data_mutex);
3112 #endif
3113
3114         /* hotkey not supported on 570 */
3115         tp_features.hotkey = hkey_handle != NULL;
3116
3117         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3118                 "hotkeys are %s\n",
3119                 str_supported(tp_features.hotkey));
3120
3121         if (!tp_features.hotkey)
3122                 return 1;
3123
3124         quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable,
3125                                      ARRAY_SIZE(tpacpi_hotkey_qtable));
3126
3127         tpacpi_disable_brightness_delay();
3128
3129         /* MUST have enough space for all attributes to be added to
3130          * hotkey_dev_attributes */
3131         hotkey_dev_attributes = create_attr_set(
3132                                         ARRAY_SIZE(hotkey_attributes) + 2,
3133                                         NULL);
3134         if (!hotkey_dev_attributes)
3135                 return -ENOMEM;
3136         res = add_many_to_attr_set(hotkey_dev_attributes,
3137                         hotkey_attributes,
3138                         ARRAY_SIZE(hotkey_attributes));
3139         if (res)
3140                 goto err_exit;
3141
3142         /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p,
3143            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
3144            for HKEY interface version 0x100 */
3145         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
3146                 if ((hkeyv >> 8) != 1) {
3147                         printk(TPACPI_ERR "unknown version of the "
3148                                "HKEY interface: 0x%x\n", hkeyv);
3149                         printk(TPACPI_ERR "please report this to %s\n",
3150                                TPACPI_MAIL);
3151                 } else {
3152                         /*
3153                          * MHKV 0x100 in A31, R40, R40e,
3154                          * T4x, X31, and later
3155                          */
3156                         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3157                                 "firmware HKEY interface version: 0x%x\n",
3158                                 hkeyv);
3159
3160                         /* Paranoia check AND init hotkey_all_mask */
3161                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3162                                         "MHKA", "qd")) {
3163                                 printk(TPACPI_ERR
3164                                        "missing MHKA handler, "
3165                                        "please report this to %s\n",
3166                                        TPACPI_MAIL);
3167                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3168                                 hotkey_all_mask = 0x080cU;
3169                         } else {
3170                                 tp_features.hotkey_mask = 1;
3171                         }
3172                 }
3173         }
3174
3175         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3176                 "hotkey masks are %s\n",
3177                 str_supported(tp_features.hotkey_mask));
3178
3179         /* Init hotkey_all_mask if not initialized yet */
3180         if (!tp_features.hotkey_mask && !hotkey_all_mask &&
3181             (quirks & TPACPI_HK_Q_INIMASK))
3182                 hotkey_all_mask = 0x080cU;  /* FN+F12, FN+F4, FN+F3 */
3183
3184         /* Init hotkey_acpi_mask and hotkey_orig_mask */
3185         if (tp_features.hotkey_mask) {
3186                 /* hotkey_source_mask *must* be zero for
3187                  * the first hotkey_mask_get to return hotkey_orig_mask */
3188                 res = hotkey_mask_get();
3189                 if (res)
3190                         goto err_exit;
3191
3192                 hotkey_orig_mask = hotkey_acpi_mask;
3193         } else {
3194                 hotkey_orig_mask = hotkey_all_mask;
3195                 hotkey_acpi_mask = hotkey_all_mask;
3196         }
3197
3198 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3199         if (dbg_wlswemul) {
3200                 tp_features.hotkey_wlsw = 1;
3201                 printk(TPACPI_INFO
3202                         "radio switch emulation enabled\n");
3203         } else
3204 #endif
3205         /* Not all thinkpads have a hardware radio switch */
3206         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
3207                 tp_features.hotkey_wlsw = 1;
3208                 printk(TPACPI_INFO
3209                         "radio switch found; radios are %s\n",
3210                         enabled(status, 0));
3211         }
3212         if (tp_features.hotkey_wlsw)
3213                 res = add_to_attr_set(hotkey_dev_attributes,
3214                                 &dev_attr_hotkey_radio_sw.attr);
3215
3216         /* For X41t, X60t, X61t Tablets... */
3217         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
3218                 tp_features.hotkey_tablet = 1;
3219                 printk(TPACPI_INFO
3220                         "possible tablet mode switch found; "
3221                         "ThinkPad in %s mode\n",
3222                         (status & TP_HOTKEY_TABLET_MASK)?
3223                                 "tablet" : "laptop");
3224                 res = add_to_attr_set(hotkey_dev_attributes,
3225                                 &dev_attr_hotkey_tablet_mode.attr);
3226         }
3227
3228         if (!res)
3229                 res = register_attr_set_with_sysfs(
3230                                 hotkey_dev_attributes,
3231                                 &tpacpi_pdev->dev.kobj);
3232         if (res)
3233                 goto err_exit;
3234
3235         /* Set up key map */
3236
3237         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
3238                                         GFP_KERNEL);
3239         if (!hotkey_keycode_map) {
3240                 printk(TPACPI_ERR
3241                         "failed to allocate memory for key map\n");
3242                 res = -ENOMEM;
3243                 goto err_exit;
3244         }
3245
3246         if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
3247                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3248                            "using Lenovo default hot key map\n");
3249                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
3250                         TPACPI_HOTKEY_MAP_SIZE);
3251         } else {
3252                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3253                            "using IBM default hot key map\n");
3254                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
3255                         TPACPI_HOTKEY_MAP_SIZE);
3256         }
3257
3258         set_bit(EV_KEY, tpacpi_inputdev->evbit);
3259         set_bit(EV_MSC, tpacpi_inputdev->evbit);
3260         set_bit(MSC_SCAN, tpacpi_inputdev->mscbit);
3261         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
3262         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
3263         tpacpi_inputdev->keycode = hotkey_keycode_map;
3264         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
3265                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
3266                         set_bit(hotkey_keycode_map[i],
3267                                 tpacpi_inputdev->keybit);
3268                 } else {
3269                         if (i < sizeof(hotkey_reserved_mask)*8)
3270                                 hotkey_reserved_mask |= 1 << i;
3271                 }
3272         }
3273
3274         if (tp_features.hotkey_wlsw) {
3275                 set_bit(EV_SW, tpacpi_inputdev->evbit);
3276                 set_bit(SW_RFKILL_ALL, tpacpi_inputdev->swbit);
3277         }
3278         if (tp_features.hotkey_tablet) {
3279                 set_bit(EV_SW, tpacpi_inputdev->evbit);
3280                 set_bit(SW_TABLET_MODE, tpacpi_inputdev->swbit);
3281         }
3282
3283         /* Do not issue duplicate brightness change events to
3284          * userspace */
3285         if (!tp_features.bright_acpimode)
3286                 /* update bright_acpimode... */
3287                 tpacpi_check_std_acpi_brightness_support();
3288
3289         if (tp_features.bright_acpimode && acpi_video_backlight_support()) {
3290                 printk(TPACPI_INFO
3291                        "This ThinkPad has standard ACPI backlight "
3292                        "brightness control, supported by the ACPI "
3293                        "video driver\n");
3294                 printk(TPACPI_NOTICE
3295                        "Disabling thinkpad-acpi brightness events "
3296                        "by default...\n");
3297
3298                 /* Disable brightness up/down on Lenovo thinkpads when
3299                  * ACPI is handling them, otherwise it is plain impossible
3300                  * for userspace to do something even remotely sane */
3301                 hotkey_reserved_mask |=
3302                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
3303                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
3304                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME);
3305                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND);
3306         }
3307
3308 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3309         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
3310                                 & ~hotkey_all_mask
3311                                 & ~hotkey_reserved_mask;
3312
3313         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3314                     "hotkey source mask 0x%08x, polling freq %u\n",
3315                     hotkey_source_mask, hotkey_poll_freq);
3316 #endif
3317
3318         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3319                         "enabling firmware HKEY event interface...\n");
3320         res = hotkey_status_set(true);
3321         if (res) {
3322                 hotkey_exit();
3323                 return res;
3324         }
3325         res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask)
3326                                | hotkey_driver_mask)
3327                               & ~hotkey_source_mask);
3328         if (res < 0 && res != -ENXIO) {
3329                 hotkey_exit();
3330                 return res;
3331         }
3332         hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask)
3333                                 & ~hotkey_reserved_mask;
3334         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3335                 "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n",
3336                 hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask);
3337
3338         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3339                         "legacy ibm/hotkey event reporting over procfs %s\n",
3340                         (hotkey_report_mode < 2) ?
3341                                 "enabled" : "disabled");
3342
3343         tpacpi_inputdev->open = &hotkey_inputdev_open;
3344         tpacpi_inputdev->close = &hotkey_inputdev_close;
3345
3346         hotkey_poll_setup_safe(true);
3347         tpacpi_send_radiosw_update();
3348         tpacpi_input_send_tabletsw();
3349
3350         return 0;
3351
3352 err_exit:
3353         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3354         hotkey_dev_attributes = NULL;
3355
3356         return (res < 0)? res : 1;
3357 }
3358
3359 static bool hotkey_notify_hotkey(const u32 hkey,
3360                                  bool *send_acpi_ev,
3361                                  bool *ignore_acpi_ev)
3362 {
3363         /* 0x1000-0x1FFF: key presses */
3364         unsigned int scancode = hkey & 0xfff;
3365         *send_acpi_ev = true;
3366         *ignore_acpi_ev = false;
3367
3368         if (scancode > 0 && scancode < 0x21) {
3369                 scancode--;
3370                 if (!(hotkey_source_mask & (1 << scancode))) {
3371                         tpacpi_input_send_key_masked(scancode);
3372                         *send_acpi_ev = false;
3373                 } else {
3374                         *ignore_acpi_ev = true;
3375                 }
3376                 return true;
3377         }
3378         return false;
3379 }
3380
3381 static bool hotkey_notify_wakeup(const u32 hkey,
3382                                  bool *send_acpi_ev,
3383                                  bool *ignore_acpi_ev)
3384 {
3385         /* 0x2000-0x2FFF: Wakeup reason */
3386         *send_acpi_ev = true;
3387         *ignore_acpi_ev = false;
3388
3389         switch (hkey) {
3390         case 0x2304: /* suspend, undock */
3391         case 0x2404: /* hibernation, undock */
3392                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3393                 *ignore_acpi_ev = true;
3394                 break;
3395
3396         case 0x2305: /* suspend, bay eject */
3397         case 0x2405: /* hibernation, bay eject */
3398                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3399                 *ignore_acpi_ev = true;
3400                 break;
3401
3402         case 0x2313: /* Battery on critical low level (S3) */
3403         case 0x2413: /* Battery on critical low level (S4) */
3404                 printk(TPACPI_ALERT
3405                         "EMERGENCY WAKEUP: battery almost empty\n");
3406                 /* how to auto-heal: */
3407                 /* 2313: woke up from S3, go to S4/S5 */
3408                 /* 2413: woke up from S4, go to S5 */
3409                 break;
3410
3411         default:
3412                 return false;
3413         }
3414
3415         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3416                 printk(TPACPI_INFO
3417                        "woke up due to a hot-unplug "
3418                        "request...\n");
3419                 hotkey_wakeup_reason_notify_change();
3420         }
3421         return true;
3422 }
3423
3424 static bool hotkey_notify_usrevent(const u32 hkey,
3425                                  bool *send_acpi_ev,
3426                                  bool *ignore_acpi_ev)
3427 {
3428         /* 0x5000-0x5FFF: human interface helpers */
3429         *send_acpi_ev = true;
3430         *ignore_acpi_ev = false;
3431
3432         switch (hkey) {
3433         case 0x500b: /* X61t: tablet pen inserted into bay */
3434         case 0x500c: /* X61t: tablet pen removed from bay */
3435                 return true;
3436
3437         case 0x5009: /* X41t-X61t: swivel up (tablet mode) */
3438         case 0x500a: /* X41t-X61t: swivel down (normal mode) */
3439                 tpacpi_input_send_tabletsw();
3440                 hotkey_tablet_mode_notify_change();
3441                 *send_acpi_ev = false;
3442                 return true;
3443
3444         case 0x5001: /* Lid close */
3445         case 0x5002: /* Lid open */
3446         case 0x5010: /* brightness control */
3447                 /* do not propagate these events */
3448                 *ignore_acpi_ev = true;
3449                 return true;
3450
3451         default:
3452                 return false;
3453         }
3454 }
3455
3456 static bool hotkey_notify_thermal(const u32 hkey,
3457                                  bool *send_acpi_ev,
3458                                  bool *ignore_acpi_ev)
3459 {
3460         /* 0x6000-0x6FFF: thermal alarms */
3461         *send_acpi_ev = true;
3462         *ignore_acpi_ev = false;
3463
3464         switch (hkey) {
3465         case 0x6011:
3466                 printk(TPACPI_CRIT
3467                         "THERMAL ALARM: battery is too hot!\n");
3468                 /* recommended action: warn user through gui */
3469                 return true;
3470         case 0x6012:
3471                 printk(TPACPI_ALERT
3472                         "THERMAL EMERGENCY: battery is extremely hot!\n");
3473                 /* recommended action: immediate sleep/hibernate */
3474                 return true;
3475         case 0x6021:
3476                 printk(TPACPI_CRIT
3477                         "THERMAL ALARM: "
3478                         "a sensor reports something is too hot!\n");
3479                 /* recommended action: warn user through gui, that */
3480                 /* some internal component is too hot */
3481                 return true;
3482         case 0x6022:
3483                 printk(TPACPI_ALERT
3484                         "THERMAL EMERGENCY: "
3485                         "a sensor reports something is extremely hot!\n");
3486                 /* recommended action: immediate sleep/hibernate */
3487                 return true;
3488         case 0x6030:
3489                 printk(TPACPI_INFO
3490                         "EC reports that Thermal Table has changed\n");
3491                 /* recommended action: do nothing, we don't have
3492                  * Lenovo ATM information */
3493                 return true;
3494         default:
3495                 printk(TPACPI_ALERT
3496                          "THERMAL ALERT: unknown thermal alarm received\n");
3497                 return false;
3498         }
3499 }
3500
3501 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3502 {
3503         u32 hkey;
3504         bool send_acpi_ev;
3505         bool ignore_acpi_ev;
3506         bool known_ev;
3507
3508         if (event != 0x80) {
3509                 printk(TPACPI_ERR
3510                        "unknown HKEY notification event %d\n", event);
3511                 /* forward it to userspace, maybe it knows how to handle it */
3512                 acpi_bus_generate_netlink_event(
3513                                         ibm->acpi->device->pnp.device_class,
3514                                         dev_name(&ibm->acpi->device->dev),
3515                                         event, 0);
3516                 return;
3517         }
3518
3519         while (1) {
3520                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
3521                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
3522                         return;
3523                 }
3524
3525                 if (hkey == 0) {
3526                         /* queue empty */
3527                         return;
3528                 }
3529
3530                 send_acpi_ev = true;
3531                 ignore_acpi_ev = false;
3532
3533                 switch (hkey >> 12) {
3534                 case 1:
3535                         /* 0x1000-0x1FFF: key presses */
3536                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
3537                                                  &ignore_acpi_ev);
3538                         break;
3539                 case 2:
3540                         /* 0x2000-0x2FFF: Wakeup reason */
3541                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
3542                                                  &ignore_acpi_ev);
3543                         break;
3544                 case 3:
3545                         /* 0x3000-0x3FFF: bay-related wakeups */
3546                         if (hkey == 0x3003) {
3547                                 hotkey_autosleep_ack = 1;
3548                                 printk(TPACPI_INFO
3549                                        "bay ejected\n");
3550                                 hotkey_wakeup_hotunplug_complete_notify_change();
3551                                 known_ev = true;
3552                         } else {
3553                                 known_ev = false;
3554                         }
3555                         break;
3556                 case 4:
3557                         /* 0x4000-0x4FFF: dock-related wakeups */
3558                         if (hkey == 0x4003) {
3559                                 hotkey_autosleep_ack = 1;
3560                                 printk(TPACPI_INFO
3561                                        "undocked\n");
3562                                 hotkey_wakeup_hotunplug_complete_notify_change();
3563                                 known_ev = true;
3564                         } else {
3565                                 known_ev = false;
3566                         }
3567                         break;
3568                 case 5:
3569                         /* 0x5000-0x5FFF: human interface helpers */
3570                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
3571                                                  &ignore_acpi_ev);
3572                         break;
3573                 case 6:
3574                         /* 0x6000-0x6FFF: thermal alarms */
3575                         known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev,
3576                                                  &ignore_acpi_ev);
3577                         break;
3578                 case 7:
3579                         /* 0x7000-0x7FFF: misc */
3580                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
3581                                 tpacpi_send_radiosw_update();
3582                                 send_acpi_ev = 0;
3583                                 known_ev = true;
3584                                 break;
3585                         }
3586                         /* fallthrough to default */
3587                 default:
3588                         known_ev = false;
3589                 }
3590                 if (!known_ev) {
3591                         printk(TPACPI_NOTICE
3592                                "unhandled HKEY event 0x%04x\n", hkey);
3593                         printk(TPACPI_NOTICE
3594                                "please report the conditions when this "
3595                                "event happened to %s\n", TPACPI_MAIL);
3596                 }
3597
3598                 /* Legacy events */
3599                 if (!ignore_acpi_ev &&
3600                     (send_acpi_ev || hotkey_report_mode < 2)) {
3601                         acpi_bus_generate_proc_event(ibm->acpi->device,
3602                                                      event, hkey);
3603                 }
3604
3605                 /* netlink events */
3606                 if (!ignore_acpi_ev && send_acpi_ev) {
3607                         acpi_bus_generate_netlink_event(
3608                                         ibm->acpi->device->pnp.device_class,
3609                                         dev_name(&ibm->acpi->device->dev),
3610                                         event, hkey);
3611                 }
3612         }
3613 }
3614
3615 static void hotkey_suspend(pm_message_t state)
3616 {
3617         /* Do these on suspend, we get the events on early resume! */
3618         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
3619         hotkey_autosleep_ack = 0;
3620 }
3621
3622 static void hotkey_resume(void)
3623 {
3624         tpacpi_disable_brightness_delay();
3625
3626         if (hotkey_status_set(true) < 0 ||
3627             hotkey_mask_set(hotkey_acpi_mask) < 0)
3628                 printk(TPACPI_ERR
3629                        "error while attempting to reset the event "
3630                        "firmware interface\n");
3631
3632         tpacpi_send_radiosw_update();
3633         hotkey_tablet_mode_notify_change();
3634         hotkey_wakeup_reason_notify_change();
3635         hotkey_wakeup_hotunplug_complete_notify_change();
3636         hotkey_poll_setup_safe(false);
3637 }
3638
3639 /* procfs -------------------------------------------------------------- */
3640 static int hotkey_read(char *p)
3641 {
3642         int res, status;
3643         int len = 0;
3644
3645         if (!tp_features.hotkey) {
3646                 len += sprintf(p + len, "status:\t\tnot supported\n");
3647                 return len;
3648         }
3649
3650         if (mutex_lock_killable(&hotkey_mutex))
3651                 return -ERESTARTSYS;
3652         res = hotkey_status_get(&status);
3653         if (!res)
3654                 res = hotkey_mask_get();
3655         mutex_unlock(&hotkey_mutex);
3656         if (res)
3657                 return res;
3658
3659         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
3660         if (hotkey_all_mask) {
3661                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_user_mask);
3662                 len += sprintf(p + len,
3663                                "commands:\tenable, disable, reset, <mask>\n");
3664         } else {
3665                 len += sprintf(p + len, "mask:\t\tnot supported\n");
3666                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
3667         }
3668
3669         return len;
3670 }
3671
3672 static void hotkey_enabledisable_warn(bool enable)
3673 {
3674         tpacpi_log_usertask("procfs hotkey enable/disable");
3675         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
3676                         TPACPI_WARN
3677                         "hotkey enable/disable functionality has been "
3678                         "removed from the driver.  Hotkeys are always "
3679                         "enabled\n"))
3680                 printk(TPACPI_ERR
3681                         "Please remove the hotkey=enable module "
3682                         "parameter, it is deprecated.  Hotkeys are always "
3683                         "enabled\n");
3684 }
3685
3686 static int hotkey_write(char *buf)
3687 {
3688         int res;
3689         u32 mask;
3690         char *cmd;
3691
3692         if (!tp_features.hotkey)
3693                 return -ENODEV;
3694
3695         if (mutex_lock_killable(&hotkey_mutex))
3696                 return -ERESTARTSYS;
3697
3698         mask = hotkey_user_mask;
3699
3700         res = 0;
3701         while ((cmd = next_cmd(&buf))) {
3702                 if (strlencmp(cmd, "enable") == 0) {
3703                         hotkey_enabledisable_warn(1);
3704                 } else if (strlencmp(cmd, "disable") == 0) {
3705                         hotkey_enabledisable_warn(0);
3706                         res = -EPERM;
3707                 } else if (strlencmp(cmd, "reset") == 0) {
3708                         mask = (hotkey_all_mask | hotkey_source_mask)
3709                                 & ~hotkey_reserved_mask;
3710                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
3711                         /* mask set */
3712                 } else if (sscanf(cmd, "%x", &mask) == 1) {
3713                         /* mask set */
3714                 } else {
3715                         res = -EINVAL;
3716                         goto errexit;
3717                 }
3718         }
3719
3720         if (!res) {
3721                 tpacpi_disclose_usertask("procfs hotkey",
3722                         "set mask to 0x%08x\n", mask);
3723                 res = hotkey_user_mask_set(mask);
3724         }
3725
3726 errexit:
3727         mutex_unlock(&hotkey_mutex);
3728         return res;
3729 }
3730
3731 static const struct acpi_device_id ibm_htk_device_ids[] = {
3732         {TPACPI_ACPI_HKEY_HID, 0},
3733         {"", 0},
3734 };
3735
3736 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
3737         .hid = ibm_htk_device_ids,
3738         .notify = hotkey_notify,
3739         .handle = &hkey_handle,
3740         .type = ACPI_DEVICE_NOTIFY,
3741 };
3742
3743 static struct ibm_struct hotkey_driver_data = {
3744         .name = "hotkey",
3745         .read = hotkey_read,
3746         .write = hotkey_write,
3747         .exit = hotkey_exit,
3748         .resume = hotkey_resume,
3749         .suspend = hotkey_suspend,
3750         .acpi = &ibm_hotkey_acpidriver,
3751 };
3752
3753 /*************************************************************************
3754  * Bluetooth subdriver
3755  */
3756
3757 enum {
3758         /* ACPI GBDC/SBDC bits */
3759         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
3760         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
3761         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
3762                                                    off / last state */
3763 };
3764
3765 enum {
3766         /* ACPI \BLTH commands */
3767         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
3768         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
3769         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
3770         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
3771         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
3772 };
3773
3774 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
3775
3776 static void bluetooth_suspend(pm_message_t state)
3777 {
3778         /* Try to make sure radio will resume powered off */
3779         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3780                    TP_ACPI_BLTH_PWR_OFF_ON_RESUME))
3781                 vdbg_printk(TPACPI_DBG_RFKILL,
3782                         "bluetooth power down on resume request failed\n");
3783 }
3784
3785 static int bluetooth_get_status(void)
3786 {
3787         int status;
3788
3789 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3790         if (dbg_bluetoothemul)
3791                 return (tpacpi_bluetooth_emulstate) ?
3792                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3793 #endif
3794
3795         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
3796                 return -EIO;
3797
3798         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
3799                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3800 }
3801
3802 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
3803 {
3804         int status;
3805
3806         vdbg_printk(TPACPI_DBG_RFKILL,
3807                 "will attempt to %s bluetooth\n",
3808                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3809
3810 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3811         if (dbg_bluetoothemul) {
3812                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
3813                 return 0;
3814         }
3815 #endif
3816
3817         /* We make sure to keep TP_ACPI_BLUETOOTH_RESUMECTRL off */
3818         if (state == TPACPI_RFK_RADIO_ON)
3819                 status = TP_ACPI_BLUETOOTH_RADIOSSW;
3820         else
3821                 status = 0;
3822
3823         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
3824                 return -EIO;
3825
3826         return 0;
3827 }
3828
3829 /* sysfs bluetooth enable ---------------------------------------------- */
3830 static ssize_t bluetooth_enable_show(struct device *dev,
3831                            struct device_attribute *attr,
3832                            char *buf)
3833 {
3834         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
3835                         attr, buf);
3836 }
3837
3838 static ssize_t bluetooth_enable_store(struct device *dev,
3839                             struct device_attribute *attr,
3840                             const char *buf, size_t count)
3841 {
3842         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
3843                                 attr, buf, count);
3844 }
3845
3846 static struct device_attribute dev_attr_bluetooth_enable =
3847         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
3848                 bluetooth_enable_show, bluetooth_enable_store);
3849
3850 /* --------------------------------------------------------------------- */
3851
3852 static struct attribute *bluetooth_attributes[] = {
3853         &dev_attr_bluetooth_enable.attr,
3854         NULL
3855 };
3856
3857 static const struct attribute_group bluetooth_attr_group = {
3858         .attrs = bluetooth_attributes,
3859 };
3860
3861 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
3862         .get_status = bluetooth_get_status,
3863         .set_status = bluetooth_set_status,
3864 };
3865
3866 static void bluetooth_shutdown(void)
3867 {
3868         /* Order firmware to save current state to NVRAM */
3869         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3870                         TP_ACPI_BLTH_SAVE_STATE))
3871                 printk(TPACPI_NOTICE
3872                         "failed to save bluetooth state to NVRAM\n");
3873         else
3874                 vdbg_printk(TPACPI_DBG_RFKILL,
3875                         "bluestooth state saved to NVRAM\n");
3876 }
3877
3878 static void bluetooth_exit(void)
3879 {
3880         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3881                         &bluetooth_attr_group);
3882
3883         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3884
3885         bluetooth_shutdown();
3886 }
3887
3888 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3889 {
3890         int res;
3891         int status = 0;
3892
3893         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3894                         "initializing bluetooth subdriver\n");
3895
3896         TPACPI_ACPIHANDLE_INIT(hkey);
3897
3898         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3899            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
3900         tp_features.bluetooth = hkey_handle &&
3901             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
3902
3903         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3904                 "bluetooth is %s, status 0x%02x\n",
3905                 str_supported(tp_features.bluetooth),
3906                 status);
3907
3908 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3909         if (dbg_bluetoothemul) {
3910                 tp_features.bluetooth = 1;
3911                 printk(TPACPI_INFO
3912                         "bluetooth switch emulation enabled\n");
3913         } else
3914 #endif
3915         if (tp_features.bluetooth &&
3916             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
3917                 /* no bluetooth hardware present in system */
3918                 tp_features.bluetooth = 0;
3919                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3920                            "bluetooth hardware not installed\n");
3921         }
3922
3923         if (!tp_features.bluetooth)
3924                 return 1;
3925
3926         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
3927                                 &bluetooth_tprfk_ops,
3928                                 RFKILL_TYPE_BLUETOOTH,
3929                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
3930                                 true);
3931         if (res)
3932                 return res;
3933
3934         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3935                                 &bluetooth_attr_group);
3936         if (res) {
3937                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3938                 return res;
3939         }
3940
3941         return 0;
3942 }
3943
3944 /* procfs -------------------------------------------------------------- */
3945 static int bluetooth_read(char *p)
3946 {
3947         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, p);
3948 }
3949
3950 static int bluetooth_write(char *buf)
3951 {
3952         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
3953 }
3954
3955 static struct ibm_struct bluetooth_driver_data = {
3956         .name = "bluetooth",
3957         .read = bluetooth_read,
3958         .write = bluetooth_write,
3959         .exit = bluetooth_exit,
3960         .suspend = bluetooth_suspend,
3961         .shutdown = bluetooth_shutdown,
3962 };
3963
3964 /*************************************************************************
3965  * Wan subdriver
3966  */
3967
3968 enum {
3969         /* ACPI GWAN/SWAN bits */
3970         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
3971         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
3972         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
3973                                                    off / last state */
3974 };
3975
3976 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
3977
3978 static void wan_suspend(pm_message_t state)
3979 {
3980         /* Try to make sure radio will resume powered off */
3981         if (!acpi_evalf(NULL, NULL, "\\WGSV", "qvd",
3982                    TP_ACPI_WGSV_PWR_OFF_ON_RESUME))
3983                 vdbg_printk(TPACPI_DBG_RFKILL,
3984                         "WWAN power down on resume request failed\n");
3985 }
3986
3987 static int wan_get_status(void)
3988 {
3989         int status;
3990
3991 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3992         if (dbg_wwanemul)
3993                 return (tpacpi_wwan_emulstate) ?
3994                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3995 #endif
3996
3997         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
3998                 return -EIO;
3999
4000         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
4001                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4002 }
4003
4004 static int wan_set_status(enum tpacpi_rfkill_state state)
4005 {
4006         int status;
4007
4008         vdbg_printk(TPACPI_DBG_RFKILL,
4009                 "will attempt to %s wwan\n",
4010                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4011
4012 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4013         if (dbg_wwanemul) {
4014                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
4015                 return 0;
4016         }
4017 #endif
4018
4019         /* We make sure to keep TP_ACPI_WANCARD_RESUMECTRL off */
4020         if (state == TPACPI_RFK_RADIO_ON)
4021                 status = TP_ACPI_WANCARD_RADIOSSW;
4022         else
4023                 status = 0;
4024
4025         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
4026                 return -EIO;
4027
4028         return 0;
4029 }
4030
4031 /* sysfs wan enable ---------------------------------------------------- */
4032 static ssize_t wan_enable_show(struct device *dev,
4033                            struct device_attribute *attr,
4034                            char *buf)
4035 {
4036         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
4037                         attr, buf);
4038 }
4039
4040 static ssize_t wan_enable_store(struct device *dev,
4041                             struct device_attribute *attr,
4042                             const char *buf, size_t count)
4043 {
4044         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
4045                         attr, buf, count);
4046 }
4047
4048 static struct device_attribute dev_attr_wan_enable =
4049         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
4050                 wan_enable_show, wan_enable_store);
4051
4052 /* --------------------------------------------------------------------- */
4053
4054 static struct attribute *wan_attributes[] = {
4055         &dev_attr_wan_enable.attr,
4056         NULL
4057 };
4058
4059 static const struct attribute_group wan_attr_group = {
4060         .attrs = wan_attributes,
4061 };
4062
4063 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
4064         .get_status = wan_get_status,
4065         .set_status = wan_set_status,
4066 };
4067
4068 static void wan_shutdown(void)
4069 {
4070         /* Order firmware to save current state to NVRAM */
4071         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
4072                         TP_ACPI_WGSV_SAVE_STATE))
4073                 printk(TPACPI_NOTICE
4074                         "failed to save WWAN state to NVRAM\n");
4075         else
4076                 vdbg_printk(TPACPI_DBG_RFKILL,
4077                         "WWAN state saved to NVRAM\n");
4078 }
4079
4080 static void wan_exit(void)
4081 {
4082         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4083                 &wan_attr_group);
4084
4085         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4086
4087         wan_shutdown();
4088 }
4089
4090 static int __init wan_init(struct ibm_init_struct *iibm)
4091 {
4092         int res;
4093         int status = 0;
4094
4095         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4096                         "initializing wan subdriver\n");
4097
4098         TPACPI_ACPIHANDLE_INIT(hkey);
4099
4100         tp_features.wan = hkey_handle &&
4101             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
4102
4103         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4104                 "wan is %s, status 0x%02x\n",
4105                 str_supported(tp_features.wan),
4106                 status);
4107
4108 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4109         if (dbg_wwanemul) {
4110                 tp_features.wan = 1;
4111                 printk(TPACPI_INFO
4112                         "wwan switch emulation enabled\n");
4113         } else
4114 #endif
4115         if (tp_features.wan &&
4116             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
4117                 /* no wan hardware present in system */
4118                 tp_features.wan = 0;
4119                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4120                            "wan hardware not installed\n");
4121         }
4122
4123         if (!tp_features.wan)
4124                 return 1;
4125
4126         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
4127                                 &wan_tprfk_ops,
4128                                 RFKILL_TYPE_WWAN,
4129                                 TPACPI_RFK_WWAN_SW_NAME,
4130                                 true);
4131         if (res)
4132                 return res;
4133
4134         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4135                                 &wan_attr_group);
4136
4137         if (res) {
4138                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4139                 return res;
4140         }
4141
4142         return 0;
4143 }
4144
4145 /* procfs -------------------------------------------------------------- */
4146 static int wan_read(char *p)
4147 {
4148         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, p);
4149 }
4150
4151 static int wan_write(char *buf)
4152 {
4153         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
4154 }
4155
4156 static struct ibm_struct wan_driver_data = {
4157         .name = "wan",
4158         .read = wan_read,
4159         .write = wan_write,
4160         .exit = wan_exit,
4161         .suspend = wan_suspend,
4162         .shutdown = wan_shutdown,
4163 };
4164
4165 /*************************************************************************
4166  * UWB subdriver
4167  */
4168
4169 enum {
4170         /* ACPI GUWB/SUWB bits */
4171         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
4172         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
4173 };
4174
4175 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
4176
4177 static int uwb_get_status(void)
4178 {
4179         int status;
4180
4181 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4182         if (dbg_uwbemul)
4183                 return (tpacpi_uwb_emulstate) ?
4184                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4185 #endif
4186
4187         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
4188                 return -EIO;
4189
4190         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
4191                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4192 }
4193
4194 static int uwb_set_status(enum tpacpi_rfkill_state state)
4195 {
4196         int status;
4197
4198         vdbg_printk(TPACPI_DBG_RFKILL,
4199                 "will attempt to %s UWB\n",
4200                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4201
4202 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4203         if (dbg_uwbemul) {
4204                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
4205                 return 0;
4206         }
4207 #endif
4208
4209         if (state == TPACPI_RFK_RADIO_ON)
4210                 status = TP_ACPI_UWB_RADIOSSW;
4211         else
4212                 status = 0;
4213
4214         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
4215                 return -EIO;
4216
4217         return 0;
4218 }
4219
4220 /* --------------------------------------------------------------------- */
4221
4222 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
4223         .get_status = uwb_get_status,
4224         .set_status = uwb_set_status,
4225 };
4226
4227 static void uwb_exit(void)
4228 {
4229         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
4230 }
4231
4232 static int __init uwb_init(struct ibm_init_struct *iibm)
4233 {
4234         int res;
4235         int status = 0;
4236
4237         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4238                         "initializing uwb subdriver\n");
4239
4240         TPACPI_ACPIHANDLE_INIT(hkey);
4241
4242         tp_features.uwb = hkey_handle &&
4243             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
4244
4245         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4246                 "uwb is %s, status 0x%02x\n",
4247                 str_supported(tp_features.uwb),
4248                 status);
4249
4250 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4251         if (dbg_uwbemul) {
4252                 tp_features.uwb = 1;
4253                 printk(TPACPI_INFO
4254                         "uwb switch emulation enabled\n");
4255         } else
4256 #endif
4257         if (tp_features.uwb &&
4258             !(status & TP_ACPI_UWB_HWPRESENT)) {
4259                 /* no uwb hardware present in system */
4260                 tp_features.uwb = 0;
4261                 dbg_printk(TPACPI_DBG_INIT,
4262                            "uwb hardware not installed\n");
4263         }
4264
4265         if (!tp_features.uwb)
4266                 return 1;
4267
4268         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
4269                                 &uwb_tprfk_ops,
4270                                 RFKILL_TYPE_UWB,
4271                                 TPACPI_RFK_UWB_SW_NAME,
4272                                 false);
4273         return res;
4274 }
4275
4276 static struct ibm_struct uwb_driver_data = {
4277         .name = "uwb",
4278         .exit = uwb_exit,
4279         .flags.experimental = 1,
4280 };
4281
4282 /*************************************************************************
4283  * Video subdriver
4284  */
4285
4286 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
4287
4288 enum video_access_mode {
4289         TPACPI_VIDEO_NONE = 0,
4290         TPACPI_VIDEO_570,       /* 570 */
4291         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
4292         TPACPI_VIDEO_NEW,       /* all others */
4293 };
4294
4295 enum {  /* video status flags, based on VIDEO_570 */
4296         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
4297         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
4298         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
4299 };
4300
4301 enum {  /* TPACPI_VIDEO_570 constants */
4302         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
4303         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
4304                                                  * video_status_flags */
4305         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
4306         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
4307 };
4308
4309 static enum video_access_mode video_supported;
4310 static int video_orig_autosw;
4311
4312 static int video_autosw_get(void);
4313 static int video_autosw_set(int enable);
4314
4315 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
4316
4317 static int __init video_init(struct ibm_init_struct *iibm)
4318 {
4319         int ivga;
4320
4321         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
4322
4323         TPACPI_ACPIHANDLE_INIT(vid);
4324         TPACPI_ACPIHANDLE_INIT(vid2);
4325
4326         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
4327                 /* G41, assume IVGA doesn't change */
4328                 vid_handle = vid2_handle;
4329
4330         if (!vid_handle)
4331                 /* video switching not supported on R30, R31 */
4332                 video_supported = TPACPI_VIDEO_NONE;
4333         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
4334                 /* 570 */
4335                 video_supported = TPACPI_VIDEO_570;
4336         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
4337                 /* 600e/x, 770e, 770x */
4338                 video_supported = TPACPI_VIDEO_770;
4339         else
4340                 /* all others */
4341                 video_supported = TPACPI_VIDEO_NEW;
4342
4343         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
4344                 str_supported(video_supported != TPACPI_VIDEO_NONE),
4345                 video_supported);
4346
4347         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
4348 }
4349
4350 static void video_exit(void)
4351 {
4352         dbg_printk(TPACPI_DBG_EXIT,
4353                    "restoring original video autoswitch mode\n");
4354         if (video_autosw_set(video_orig_autosw))
4355                 printk(TPACPI_ERR "error while trying to restore original "
4356                         "video autoswitch mode\n");
4357 }
4358
4359 static int video_outputsw_get(void)
4360 {
4361         int status = 0;
4362         int i;
4363
4364         switch (video_supported) {
4365         case TPACPI_VIDEO_570:
4366                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4367                                  TP_ACPI_VIDEO_570_PHSCMD))
4368                         return -EIO;
4369                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4370                 break;
4371         case TPACPI_VIDEO_770:
4372                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4373                         return -EIO;
4374                 if (i)
4375                         status |= TP_ACPI_VIDEO_S_LCD;
4376                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4377                         return -EIO;
4378                 if (i)
4379                         status |= TP_ACPI_VIDEO_S_CRT;
4380                 break;
4381         case TPACPI_VIDEO_NEW:
4382                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4383                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4384                         return -EIO;
4385                 if (i)
4386                         status |= TP_ACPI_VIDEO_S_CRT;
4387
4388                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4389                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4390                         return -EIO;
4391                 if (i)
4392                         status |= TP_ACPI_VIDEO_S_LCD;
4393                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4394                         return -EIO;
4395                 if (i)
4396                         status |= TP_ACPI_VIDEO_S_DVI;
4397                 break;
4398         default:
4399                 return -ENOSYS;
4400         }
4401
4402         return status;
4403 }
4404
4405 static int video_outputsw_set(int status)
4406 {
4407         int autosw;
4408         int res = 0;
4409
4410         switch (video_supported) {
4411         case TPACPI_VIDEO_570:
4412                 res = acpi_evalf(NULL, NULL,
4413                                  "\\_SB.PHS2", "vdd",
4414                                  TP_ACPI_VIDEO_570_PHS2CMD,
4415                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4416                 break;
4417         case TPACPI_VIDEO_770:
4418                 autosw = video_autosw_get();
4419                 if (autosw < 0)
4420                         return autosw;
4421
4422                 res = video_autosw_set(1);
4423                 if (res)
4424                         return res;
4425                 res = acpi_evalf(vid_handle, NULL,
4426                                  "ASWT", "vdd", status * 0x100, 0);
4427                 if (!autosw && video_autosw_set(autosw)) {
4428                         printk(TPACPI_ERR
4429                                "video auto-switch left enabled due to error\n");
4430                         return -EIO;
4431                 }
4432                 break;
4433         case TPACPI_VIDEO_NEW:
4434                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4435                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4436                 break;
4437         default:
4438                 return -ENOSYS;
4439         }
4440
4441         return (res)? 0 : -EIO;
4442 }
4443
4444 static int video_autosw_get(void)
4445 {
4446         int autosw = 0;
4447
4448         switch (video_supported) {
4449         case TPACPI_VIDEO_570:
4450                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4451                         return -EIO;
4452                 break;
4453         case TPACPI_VIDEO_770:
4454         case TPACPI_VIDEO_NEW:
4455                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4456                         return -EIO;
4457                 break;
4458         default:
4459                 return -ENOSYS;
4460         }
4461
4462         return autosw & 1;
4463 }
4464
4465 static int video_autosw_set(int enable)
4466 {
4467         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
4468                 return -EIO;
4469         return 0;
4470 }
4471
4472 static int video_outputsw_cycle(void)
4473 {
4474         int autosw = video_autosw_get();
4475         int res;
4476
4477         if (autosw < 0)
4478                 return autosw;
4479
4480         switch (video_supported) {
4481         case TPACPI_VIDEO_570:
4482                 res = video_autosw_set(1);
4483                 if (res)
4484                         return res;
4485                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4486                 break;
4487         case TPACPI_VIDEO_770:
4488         case TPACPI_VIDEO_NEW:
4489                 res = video_autosw_set(1);
4490                 if (res)
4491                         return res;
4492                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4493                 break;
4494         default:
4495                 return -ENOSYS;
4496         }
4497         if (!autosw && video_autosw_set(autosw)) {
4498                 printk(TPACPI_ERR
4499                        "video auto-switch left enabled due to error\n");
4500                 return -EIO;
4501         }
4502
4503         return (res)? 0 : -EIO;
4504 }
4505
4506 static int video_expand_toggle(void)
4507 {
4508         switch (video_supported) {
4509         case TPACPI_VIDEO_570:
4510                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
4511                         0 : -EIO;
4512         case TPACPI_VIDEO_770:
4513                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
4514                         0 : -EIO;
4515         case TPACPI_VIDEO_NEW:
4516                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
4517                         0 : -EIO;
4518         default:
4519                 return -ENOSYS;
4520         }
4521         /* not reached */
4522 }
4523
4524 static int video_read(char *p)
4525 {
4526         int status, autosw;
4527         int len = 0;
4528
4529         if (video_supported == TPACPI_VIDEO_NONE) {
4530                 len += sprintf(p + len, "status:\t\tnot supported\n");
4531                 return len;
4532         }
4533
4534         status = video_outputsw_get();
4535         if (status < 0)
4536                 return status;
4537
4538         autosw = video_autosw_get();
4539         if (autosw < 0)
4540                 return autosw;
4541
4542         len += sprintf(p + len, "status:\t\tsupported\n");
4543         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
4544         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
4545         if (video_supported == TPACPI_VIDEO_NEW)
4546                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
4547         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
4548         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
4549         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
4550         if (video_supported == TPACPI_VIDEO_NEW)
4551                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
4552         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
4553         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
4554
4555         return len;
4556 }
4557
4558 static int video_write(char *buf)
4559 {
4560         char *cmd;
4561         int enable, disable, status;
4562         int res;
4563
4564         if (video_supported == TPACPI_VIDEO_NONE)
4565                 return -ENODEV;
4566
4567         enable = 0;
4568         disable = 0;
4569
4570         while ((cmd = next_cmd(&buf))) {
4571                 if (strlencmp(cmd, "lcd_enable") == 0) {
4572                         enable |= TP_ACPI_VIDEO_S_LCD;
4573                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
4574                         disable |= TP_ACPI_VIDEO_S_LCD;
4575                 } else if (strlencmp(cmd, "crt_enable") == 0) {
4576                         enable |= TP_ACPI_VIDEO_S_CRT;
4577                 } else if (strlencmp(cmd, "crt_disable") == 0) {
4578                         disable |= TP_ACPI_VIDEO_S_CRT;
4579                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4580                            strlencmp(cmd, "dvi_enable") == 0) {
4581                         enable |= TP_ACPI_VIDEO_S_DVI;
4582                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4583                            strlencmp(cmd, "dvi_disable") == 0) {
4584                         disable |= TP_ACPI_VIDEO_S_DVI;
4585                 } else if (strlencmp(cmd, "auto_enable") == 0) {
4586                         res = video_autosw_set(1);
4587                         if (res)
4588                                 return res;
4589                 } else if (strlencmp(cmd, "auto_disable") == 0) {
4590                         res = video_autosw_set(0);
4591                         if (res)
4592                                 return res;
4593                 } else if (strlencmp(cmd, "video_switch") == 0) {
4594                         res = video_outputsw_cycle();
4595                         if (res)
4596                                 return res;
4597                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
4598                         res = video_expand_toggle();
4599                         if (res)
4600                                 return res;
4601                 } else
4602                         return -EINVAL;
4603         }
4604
4605         if (enable || disable) {
4606                 status = video_outputsw_get();
4607                 if (status < 0)
4608                         return status;
4609                 res = video_outputsw_set((status & ~disable) | enable);
4610                 if (res)
4611                         return res;
4612         }
4613
4614         return 0;
4615 }
4616
4617 static struct ibm_struct video_driver_data = {
4618         .name = "video",
4619         .read = video_read,
4620         .write = video_write,
4621         .exit = video_exit,
4622 };
4623
4624 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
4625
4626 /*************************************************************************
4627  * Light (thinklight) subdriver
4628  */
4629
4630 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
4631 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
4632
4633 static int light_get_status(void)
4634 {
4635         int status = 0;
4636
4637         if (tp_features.light_status) {
4638                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
4639                         return -EIO;
4640                 return (!!status);
4641         }
4642
4643         return -ENXIO;
4644 }
4645
4646 static int light_set_status(int status)
4647 {
4648         int rc;
4649
4650         if (tp_features.light) {
4651                 if (cmos_handle) {
4652                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
4653                                         (status)?
4654                                                 TP_CMOS_THINKLIGHT_ON :
4655                                                 TP_CMOS_THINKLIGHT_OFF);
4656                 } else {
4657                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
4658                                         (status)? 1 : 0);
4659                 }
4660                 return (rc)? 0 : -EIO;
4661         }
4662
4663         return -ENXIO;
4664 }
4665
4666 static void light_set_status_worker(struct work_struct *work)
4667 {
4668         struct tpacpi_led_classdev *data =
4669                         container_of(work, struct tpacpi_led_classdev, work);
4670
4671         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4672                 light_set_status((data->new_state != TPACPI_LED_OFF));
4673 }
4674
4675 static void light_sysfs_set(struct led_classdev *led_cdev,
4676                         enum led_brightness brightness)
4677 {
4678         struct tpacpi_led_classdev *data =
4679                 container_of(led_cdev,
4680                              struct tpacpi_led_classdev,
4681                              led_classdev);
4682         data->new_state = (brightness != LED_OFF) ?
4683                                 TPACPI_LED_ON : TPACPI_LED_OFF;
4684         queue_work(tpacpi_wq, &data->work);
4685 }
4686
4687 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
4688 {
4689         return (light_get_status() == 1)? LED_FULL : LED_OFF;
4690 }
4691
4692 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
4693         .led_classdev = {
4694                 .name           = "tpacpi::thinklight",
4695                 .brightness_set = &light_sysfs_set,
4696                 .brightness_get = &light_sysfs_get,
4697         }
4698 };
4699
4700 static int __init light_init(struct ibm_init_struct *iibm)
4701 {
4702         int rc;
4703
4704         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
4705
4706         TPACPI_ACPIHANDLE_INIT(ledb);
4707         TPACPI_ACPIHANDLE_INIT(lght);
4708         TPACPI_ACPIHANDLE_INIT(cmos);
4709         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
4710
4711         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
4712         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
4713
4714         if (tp_features.light)
4715                 /* light status not supported on
4716                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
4717                 tp_features.light_status =
4718                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
4719
4720         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4721                 str_supported(tp_features.light),
4722                 str_supported(tp_features.light_status));
4723
4724         if (!tp_features.light)
4725                 return 1;
4726
4727         rc = led_classdev_register(&tpacpi_pdev->dev,
4728                                    &tpacpi_led_thinklight.led_classdev);
4729
4730         if (rc < 0) {
4731                 tp_features.light = 0;
4732                 tp_features.light_status = 0;
4733         } else  {
4734                 rc = 0;
4735         }
4736
4737         return rc;
4738 }
4739
4740 static void light_exit(void)
4741 {
4742         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4743         if (work_pending(&tpacpi_led_thinklight.work))
4744                 flush_workqueue(tpacpi_wq);
4745 }
4746
4747 static int light_read(char *p)
4748 {
4749         int len = 0;
4750         int status;
4751
4752         if (!tp_features.light) {
4753                 len += sprintf(p + len, "status:\t\tnot supported\n");
4754         } else if (!tp_features.light_status) {
4755                 len += sprintf(p + len, "status:\t\tunknown\n");
4756                 len += sprintf(p + len, "commands:\ton, off\n");
4757         } else {
4758                 status = light_get_status();
4759                 if (status < 0)
4760                         return status;
4761                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
4762                 len += sprintf(p + len, "commands:\ton, off\n");
4763         }
4764
4765         return len;
4766 }
4767
4768 static int light_write(char *buf)
4769 {
4770         char *cmd;
4771         int newstatus = 0;
4772
4773         if (!tp_features.light)
4774                 return -ENODEV;
4775
4776         while ((cmd = next_cmd(&buf))) {
4777                 if (strlencmp(cmd, "on") == 0) {
4778                         newstatus = 1;
4779                 } else if (strlencmp(cmd, "off") == 0) {
4780                         newstatus = 0;
4781                 } else
4782                         return -EINVAL;
4783         }
4784
4785         return light_set_status(newstatus);
4786 }
4787
4788 static struct ibm_struct light_driver_data = {
4789         .name = "light",
4790         .read = light_read,
4791         .write = light_write,
4792         .exit = light_exit,
4793 };
4794
4795 /*************************************************************************
4796  * CMOS subdriver
4797  */
4798
4799 /* sysfs cmos_command -------------------------------------------------- */
4800 static ssize_t cmos_command_store(struct device *dev,
4801                             struct device_attribute *attr,
4802                             const char *buf, size_t count)
4803 {
4804         unsigned long cmos_cmd;
4805         int res;
4806
4807         if (parse_strtoul(buf, 21, &cmos_cmd))
4808                 return -EINVAL;
4809
4810         res = issue_thinkpad_cmos_command(cmos_cmd);
4811         return (res)? res : count;
4812 }
4813
4814 static struct device_attribute dev_attr_cmos_command =
4815         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4816
4817 /* --------------------------------------------------------------------- */
4818
4819 static int __init cmos_init(struct ibm_init_struct *iibm)
4820 {
4821         int res;
4822
4823         vdbg_printk(TPACPI_DBG_INIT,
4824                 "initializing cmos commands subdriver\n");
4825
4826         TPACPI_ACPIHANDLE_INIT(cmos);
4827
4828         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4829                 str_supported(cmos_handle != NULL));
4830
4831         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4832         if (res)
4833                 return res;
4834
4835         return (cmos_handle)? 0 : 1;
4836 }
4837
4838 static void cmos_exit(void)
4839 {
4840         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4841 }
4842
4843 static int cmos_read(char *p)
4844 {
4845         int len = 0;
4846
4847         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4848            R30, R31, T20-22, X20-21 */
4849         if (!cmos_handle)
4850                 len += sprintf(p + len, "status:\t\tnot supported\n");
4851         else {
4852                 len += sprintf(p + len, "status:\t\tsupported\n");
4853                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
4854         }
4855
4856         return len;
4857 }
4858
4859 static int cmos_write(char *buf)
4860 {
4861         char *cmd;
4862         int cmos_cmd, res;
4863
4864         while ((cmd = next_cmd(&buf))) {
4865                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4866                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4867                         /* cmos_cmd set */
4868                 } else
4869                         return -EINVAL;
4870
4871                 res = issue_thinkpad_cmos_command(cmos_cmd);
4872                 if (res)
4873                         return res;
4874         }
4875
4876         return 0;
4877 }
4878
4879 static struct ibm_struct cmos_driver_data = {
4880         .name = "cmos",
4881         .read = cmos_read,
4882         .write = cmos_write,
4883         .exit = cmos_exit,
4884 };
4885
4886 /*************************************************************************
4887  * LED subdriver
4888  */
4889
4890 enum led_access_mode {
4891         TPACPI_LED_NONE = 0,
4892         TPACPI_LED_570, /* 570 */
4893         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4894         TPACPI_LED_NEW, /* all others */
4895 };
4896
4897 enum {  /* For TPACPI_LED_OLD */
4898         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4899         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4900         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4901 };
4902
4903 static enum led_access_mode led_supported;
4904
4905 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4906            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4907                                 /* T20-22, X20-21 */
4908            "LED",               /* all others */
4909            );                   /* R30, R31 */
4910
4911 #define TPACPI_LED_NUMLEDS 16
4912 static struct tpacpi_led_classdev *tpacpi_leds;
4913 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4914 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4915         /* there's a limit of 19 chars + NULL before 2.6.26 */
4916         "tpacpi::power",
4917         "tpacpi:orange:batt",
4918         "tpacpi:green:batt",
4919         "tpacpi::dock_active",
4920         "tpacpi::bay_active",
4921         "tpacpi::dock_batt",
4922         "tpacpi::unknown_led",
4923         "tpacpi::standby",
4924         "tpacpi::dock_status1",
4925         "tpacpi::dock_status2",
4926         "tpacpi::unknown_led2",
4927         "tpacpi::unknown_led3",
4928         "tpacpi::thinkvantage",
4929 };
4930 #define TPACPI_SAFE_LEDS        0x1081U
4931
4932 static inline bool tpacpi_is_led_restricted(const unsigned int led)
4933 {
4934 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
4935         return false;
4936 #else
4937         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
4938 #endif
4939 }
4940
4941 static int led_get_status(const unsigned int led)
4942 {
4943         int status;
4944         enum led_status_t led_s;
4945
4946         switch (led_supported) {
4947         case TPACPI_LED_570:
4948                 if (!acpi_evalf(ec_handle,
4949                                 &status, "GLED", "dd", 1 << led))
4950                         return -EIO;
4951                 led_s = (status == 0)?
4952                                 TPACPI_LED_OFF :
4953                                 ((status == 1)?
4954                                         TPACPI_LED_ON :
4955                                         TPACPI_LED_BLINK);
4956                 tpacpi_led_state_cache[led] = led_s;
4957                 return led_s;
4958         default:
4959                 return -ENXIO;
4960         }
4961
4962         /* not reached */
4963 }
4964
4965 static int led_set_status(const unsigned int led,
4966                           const enum led_status_t ledstatus)
4967 {
4968         /* off, on, blink. Index is led_status_t */
4969         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
4970         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
4971
4972         int rc = 0;
4973
4974         switch (led_supported) {
4975         case TPACPI_LED_570:
4976                 /* 570 */
4977                 if (unlikely(led > 7))
4978                         return -EINVAL;
4979                 if (unlikely(tpacpi_is_led_restricted(led)))
4980                         return -EPERM;
4981                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4982                                 (1 << led), led_sled_arg1[ledstatus]))
4983                         rc = -EIO;
4984                 break;
4985         case TPACPI_LED_OLD:
4986                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
4987                 if (unlikely(led > 7))
4988                         return -EINVAL;
4989                 if (unlikely(tpacpi_is_led_restricted(led)))
4990                         return -EPERM;
4991                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
4992                 if (rc >= 0)
4993                         rc = ec_write(TPACPI_LED_EC_HLBL,
4994                                       (ledstatus == TPACPI_LED_BLINK) << led);
4995                 if (rc >= 0)
4996                         rc = ec_write(TPACPI_LED_EC_HLCL,
4997                                       (ledstatus != TPACPI_LED_OFF) << led);
4998                 break;
4999         case TPACPI_LED_NEW:
5000                 /* all others */
5001                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
5002                         return -EINVAL;
5003                 if (unlikely(tpacpi_is_led_restricted(led)))
5004                         return -EPERM;
5005                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5006                                 led, led_led_arg1[ledstatus]))
5007                         rc = -EIO;
5008                 break;
5009         default:
5010                 rc = -ENXIO;
5011         }
5012
5013         if (!rc)
5014                 tpacpi_led_state_cache[led] = ledstatus;
5015
5016         return rc;
5017 }
5018
5019 static void led_set_status_worker(struct work_struct *work)
5020 {
5021         struct tpacpi_led_classdev *data =
5022                 container_of(work, struct tpacpi_led_classdev, work);
5023
5024         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
5025                 led_set_status(data->led, data->new_state);
5026 }
5027
5028 static void led_sysfs_set(struct led_classdev *led_cdev,
5029                         enum led_brightness brightness)
5030 {
5031         struct tpacpi_led_classdev *data = container_of(led_cdev,
5032                              struct tpacpi_led_classdev, led_classdev);
5033
5034         if (brightness == LED_OFF)
5035                 data->new_state = TPACPI_LED_OFF;
5036         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
5037                 data->new_state = TPACPI_LED_ON;
5038         else
5039                 data->new_state = TPACPI_LED_BLINK;
5040
5041         queue_work(tpacpi_wq, &data->work);
5042 }
5043
5044 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
5045                         unsigned long *delay_on, unsigned long *delay_off)
5046 {
5047         struct tpacpi_led_classdev *data = container_of(led_cdev,
5048                              struct tpacpi_led_classdev, led_classdev);
5049
5050         /* Can we choose the flash rate? */
5051         if (*delay_on == 0 && *delay_off == 0) {
5052                 /* yes. set them to the hardware blink rate (1 Hz) */
5053                 *delay_on = 500; /* ms */
5054                 *delay_off = 500; /* ms */
5055         } else if ((*delay_on != 500) || (*delay_off != 500))
5056                 return -EINVAL;
5057
5058         data->new_state = TPACPI_LED_BLINK;
5059         queue_work(tpacpi_wq, &data->work);
5060
5061         return 0;
5062 }
5063
5064 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5065 {
5066         int rc;
5067
5068         struct tpacpi_led_classdev *data = container_of(led_cdev,
5069                              struct tpacpi_led_classdev, led_classdev);
5070
5071         rc = led_get_status(data->led);
5072
5073         if (rc == TPACPI_LED_OFF || rc < 0)
5074                 rc = LED_OFF;   /* no error handling in led class :( */
5075         else
5076                 rc = LED_FULL;
5077
5078         return rc;
5079 }
5080
5081 static void led_exit(void)
5082 {
5083         unsigned int i;
5084
5085         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5086                 if (tpacpi_leds[i].led_classdev.name)
5087                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5088         }
5089
5090         kfree(tpacpi_leds);
5091 }
5092
5093 static int __init tpacpi_init_led(unsigned int led)
5094 {
5095         int rc;
5096
5097         tpacpi_leds[led].led = led;
5098
5099         /* LEDs with no name don't get registered */
5100         if (!tpacpi_led_names[led])
5101                 return 0;
5102
5103         tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set;
5104         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5105         if (led_supported == TPACPI_LED_570)
5106                 tpacpi_leds[led].led_classdev.brightness_get =
5107                                                 &led_sysfs_get;
5108
5109         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5110
5111         INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker);
5112
5113         rc = led_classdev_register(&tpacpi_pdev->dev,
5114                                 &tpacpi_leds[led].led_classdev);
5115         if (rc < 0)
5116                 tpacpi_leds[led].led_classdev.name = NULL;
5117
5118         return rc;
5119 }
5120
5121 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5122         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5123         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5124         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5125
5126         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5127         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5128         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5129         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5130         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5131         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5132         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5133         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5134
5135         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5136         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5137         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5138         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5139         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5140
5141         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5142         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5143         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5144         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5145
5146         /* (1) - may have excess leds enabled on MSB */
5147
5148         /* Defaults (order matters, keep last, don't reorder!) */
5149         { /* Lenovo */
5150           .vendor = PCI_VENDOR_ID_LENOVO,
5151           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5152           .quirks = 0x1fffU,
5153         },
5154         { /* IBM ThinkPads with no EC version string */
5155           .vendor = PCI_VENDOR_ID_IBM,
5156           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5157           .quirks = 0x00ffU,
5158         },
5159         { /* IBM ThinkPads with EC version string */
5160           .vendor = PCI_VENDOR_ID_IBM,
5161           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5162           .quirks = 0x00bfU,
5163         },
5164 };
5165
5166 #undef TPACPI_LEDQ_IBM
5167 #undef TPACPI_LEDQ_LNV
5168
5169 static int __init led_init(struct ibm_init_struct *iibm)
5170 {
5171         unsigned int i;
5172         int rc;
5173         unsigned long useful_leds;
5174
5175         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5176
5177         TPACPI_ACPIHANDLE_INIT(led);
5178
5179         if (!led_handle)
5180                 /* led not supported on R30, R31 */
5181                 led_supported = TPACPI_LED_NONE;
5182         else if (strlencmp(led_path, "SLED") == 0)
5183                 /* 570 */
5184                 led_supported = TPACPI_LED_570;
5185         else if (strlencmp(led_path, "SYSL") == 0)
5186                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5187                 led_supported = TPACPI_LED_OLD;
5188         else
5189                 /* all others */
5190                 led_supported = TPACPI_LED_NEW;
5191
5192         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5193                 str_supported(led_supported), led_supported);
5194
5195         if (led_supported == TPACPI_LED_NONE)
5196                 return 1;
5197
5198         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5199                               GFP_KERNEL);
5200         if (!tpacpi_leds) {
5201                 printk(TPACPI_ERR "Out of memory for LED data\n");
5202                 return -ENOMEM;
5203         }
5204
5205         useful_leds = tpacpi_check_quirks(led_useful_qtable,
5206                                           ARRAY_SIZE(led_useful_qtable));
5207
5208         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5209                 if (!tpacpi_is_led_restricted(i) &&
5210                     test_bit(i, &useful_leds)) {
5211                         rc = tpacpi_init_led(i);
5212                         if (rc < 0) {
5213                                 led_exit();
5214                                 return rc;
5215                         }
5216                 }
5217         }
5218
5219 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5220         printk(TPACPI_NOTICE
5221                 "warning: userspace override of important "
5222                 "firmware LEDs is enabled\n");
5223 #endif
5224         return 0;
5225 }
5226
5227 #define str_led_status(s) \
5228         ((s) == TPACPI_LED_OFF ? "off" : \
5229                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5230
5231 static int led_read(char *p)
5232 {
5233         int len = 0;
5234
5235         if (!led_supported) {
5236                 len += sprintf(p + len, "status:\t\tnot supported\n");
5237                 return len;
5238         }
5239         len += sprintf(p + len, "status:\t\tsupported\n");
5240
5241         if (led_supported == TPACPI_LED_570) {
5242                 /* 570 */
5243                 int i, status;
5244                 for (i = 0; i < 8; i++) {
5245                         status = led_get_status(i);
5246                         if (status < 0)
5247                                 return -EIO;
5248                         len += sprintf(p + len, "%d:\t\t%s\n",
5249                                        i, str_led_status(status));
5250                 }
5251         }
5252
5253         len += sprintf(p + len, "commands:\t"
5254                        "<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5255
5256         return len;
5257 }
5258
5259 static int led_write(char *buf)
5260 {
5261         char *cmd;
5262         int led, rc;
5263         enum led_status_t s;
5264
5265         if (!led_supported)
5266                 return -ENODEV;
5267
5268         while ((cmd = next_cmd(&buf))) {
5269                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15)
5270                         return -EINVAL;
5271
5272                 if (strstr(cmd, "off")) {
5273                         s = TPACPI_LED_OFF;
5274                 } else if (strstr(cmd, "on")) {
5275                         s = TPACPI_LED_ON;
5276                 } else if (strstr(cmd, "blink")) {
5277                         s = TPACPI_LED_BLINK;
5278                 } else {
5279                         return -EINVAL;
5280                 }
5281
5282                 rc = led_set_status(led, s);
5283                 if (rc < 0)
5284                         return rc;
5285         }
5286
5287         return 0;
5288 }
5289
5290 static struct ibm_struct led_driver_data = {
5291         .name = "led",
5292         .read = led_read,
5293         .write = led_write,
5294         .exit = led_exit,
5295 };
5296
5297 /*************************************************************************
5298  * Beep subdriver
5299  */
5300
5301 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
5302
5303 #define TPACPI_BEEP_Q1 0x0001
5304
5305 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
5306         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
5307         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
5308 };
5309
5310 static int __init beep_init(struct ibm_init_struct *iibm)
5311 {
5312         unsigned long quirks;
5313
5314         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
5315
5316         TPACPI_ACPIHANDLE_INIT(beep);
5317
5318         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
5319                 str_supported(beep_handle != NULL));
5320
5321         quirks = tpacpi_check_quirks(beep_quirk_table,
5322                                      ARRAY_SIZE(beep_quirk_table));
5323
5324         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
5325
5326         return (beep_handle)? 0 : 1;
5327 }
5328
5329 static int beep_read(char *p)
5330 {
5331         int len = 0;
5332
5333         if (!beep_handle)
5334                 len += sprintf(p + len, "status:\t\tnot supported\n");
5335         else {
5336                 len += sprintf(p + len, "status:\t\tsupported\n");
5337                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
5338         }
5339
5340         return len;
5341 }
5342
5343 static int beep_write(char *buf)
5344 {
5345         char *cmd;
5346         int beep_cmd;
5347
5348         if (!beep_handle)
5349                 return -ENODEV;
5350
5351         while ((cmd = next_cmd(&buf))) {
5352                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
5353                     beep_cmd >= 0 && beep_cmd <= 17) {
5354                         /* beep_cmd set */
5355                 } else
5356                         return -EINVAL;
5357                 if (tp_features.beep_needs_two_args) {
5358                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
5359                                         beep_cmd, 0))
5360                                 return -EIO;
5361                 } else {
5362                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
5363                                         beep_cmd))
5364                                 return -EIO;
5365                 }
5366         }
5367
5368         return 0;
5369 }
5370
5371 static struct ibm_struct beep_driver_data = {
5372         .name = "beep",
5373         .read = beep_read,
5374         .write = beep_write,
5375 };
5376
5377 /*************************************************************************
5378  * Thermal subdriver
5379  */
5380
5381 enum thermal_access_mode {
5382         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
5383         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
5384         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
5385         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
5386         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
5387 };
5388
5389 enum { /* TPACPI_THERMAL_TPEC_* */
5390         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
5391         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
5392         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
5393 };
5394
5395 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
5396 struct ibm_thermal_sensors_struct {
5397         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
5398 };
5399
5400 static enum thermal_access_mode thermal_read_mode;
5401
5402 /* idx is zero-based */
5403 static int thermal_get_sensor(int idx, s32 *value)
5404 {
5405         int t;
5406         s8 tmp;
5407         char tmpi[5];
5408
5409         t = TP_EC_THERMAL_TMP0;
5410
5411         switch (thermal_read_mode) {
5412 #if TPACPI_MAX_THERMAL_SENSORS >= 16
5413         case TPACPI_THERMAL_TPEC_16:
5414                 if (idx >= 8 && idx <= 15) {
5415                         t = TP_EC_THERMAL_TMP8;
5416                         idx -= 8;
5417                 }
5418                 /* fallthrough */
5419 #endif
5420         case TPACPI_THERMAL_TPEC_8:
5421                 if (idx <= 7) {
5422                         if (!acpi_ec_read(t + idx, &tmp))
5423                                 return -EIO;
5424                         *value = tmp * 1000;
5425                         return 0;
5426                 }
5427                 break;
5428
5429         case TPACPI_THERMAL_ACPI_UPDT:
5430                 if (idx <= 7) {
5431                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5432                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
5433                                 return -EIO;
5434                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5435                                 return -EIO;
5436                         *value = (t - 2732) * 100;
5437                         return 0;
5438                 }
5439                 break;
5440
5441         case TPACPI_THERMAL_ACPI_TMP07:
5442                 if (idx <= 7) {
5443                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5444                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5445                                 return -EIO;
5446                         if (t > 127 || t < -127)
5447                                 t = TP_EC_THERMAL_TMP_NA;
5448                         *value = t * 1000;
5449                         return 0;
5450                 }
5451                 break;
5452
5453         case TPACPI_THERMAL_NONE:
5454         default:
5455                 return -ENOSYS;
5456         }
5457
5458         return -EINVAL;
5459 }
5460
5461 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
5462 {
5463         int res, i;
5464         int n;
5465
5466         n = 8;
5467         i = 0;
5468
5469         if (!s)
5470                 return -EINVAL;
5471
5472         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
5473                 n = 16;
5474
5475         for (i = 0 ; i < n; i++) {
5476                 res = thermal_get_sensor(i, &s->temp[i]);
5477                 if (res)
5478                         return res;
5479         }
5480
5481         return n;
5482 }
5483
5484 /* sysfs temp##_input -------------------------------------------------- */
5485
5486 static ssize_t thermal_temp_input_show(struct device *dev,
5487                            struct device_attribute *attr,
5488                            char *buf)
5489 {
5490         struct sensor_device_attribute *sensor_attr =
5491                                         to_sensor_dev_attr(attr);
5492         int idx = sensor_attr->index;
5493         s32 value;
5494         int res;
5495
5496         res = thermal_get_sensor(idx, &value);
5497         if (res)
5498                 return res;
5499         if (value == TP_EC_THERMAL_TMP_NA * 1000)
5500                 return -ENXIO;
5501
5502         return snprintf(buf, PAGE_SIZE, "%d\n", value);
5503 }
5504
5505 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
5506          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
5507                      thermal_temp_input_show, NULL, _idxB)
5508
5509 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
5510         THERMAL_SENSOR_ATTR_TEMP(1, 0),
5511         THERMAL_SENSOR_ATTR_TEMP(2, 1),
5512         THERMAL_SENSOR_ATTR_TEMP(3, 2),
5513         THERMAL_SENSOR_ATTR_TEMP(4, 3),
5514         THERMAL_SENSOR_ATTR_TEMP(5, 4),
5515         THERMAL_SENSOR_ATTR_TEMP(6, 5),
5516         THERMAL_SENSOR_ATTR_TEMP(7, 6),
5517         THERMAL_SENSOR_ATTR_TEMP(8, 7),
5518         THERMAL_SENSOR_ATTR_TEMP(9, 8),
5519         THERMAL_SENSOR_ATTR_TEMP(10, 9),
5520         THERMAL_SENSOR_ATTR_TEMP(11, 10),
5521         THERMAL_SENSOR_ATTR_TEMP(12, 11),
5522         THERMAL_SENSOR_ATTR_TEMP(13, 12),
5523         THERMAL_SENSOR_ATTR_TEMP(14, 13),
5524         THERMAL_SENSOR_ATTR_TEMP(15, 14),
5525         THERMAL_SENSOR_ATTR_TEMP(16, 15),
5526 };
5527
5528 #define THERMAL_ATTRS(X) \
5529         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
5530
5531 static struct attribute *thermal_temp_input_attr[] = {
5532         THERMAL_ATTRS(8),
5533         THERMAL_ATTRS(9),
5534         THERMAL_ATTRS(10),
5535         THERMAL_ATTRS(11),
5536         THERMAL_ATTRS(12),
5537         THERMAL_ATTRS(13),
5538         THERMAL_ATTRS(14),
5539         THERMAL_ATTRS(15),
5540         THERMAL_ATTRS(0),
5541         THERMAL_ATTRS(1),
5542         THERMAL_ATTRS(2),
5543         THERMAL_ATTRS(3),
5544         THERMAL_ATTRS(4),
5545         THERMAL_ATTRS(5),
5546         THERMAL_ATTRS(6),
5547         THERMAL_ATTRS(7),
5548         NULL
5549 };
5550
5551 static const struct attribute_group thermal_temp_input16_group = {
5552         .attrs = thermal_temp_input_attr
5553 };
5554
5555 static const struct attribute_group thermal_temp_input8_group = {
5556         .attrs = &thermal_temp_input_attr[8]
5557 };
5558
5559 #undef THERMAL_SENSOR_ATTR_TEMP
5560 #undef THERMAL_ATTRS
5561
5562 /* --------------------------------------------------------------------- */
5563
5564 static int __init thermal_init(struct ibm_init_struct *iibm)
5565 {
5566         u8 t, ta1, ta2;
5567         int i;
5568         int acpi_tmp7;
5569         int res;
5570
5571         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5572
5573         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5574
5575         if (thinkpad_id.ec_model) {
5576                 /*
5577                  * Direct EC access mode: sensors at registers
5578                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5579                  * non-implemented, thermal sensors return 0x80 when
5580                  * not available
5581                  */
5582
5583                 ta1 = ta2 = 0;
5584                 for (i = 0; i < 8; i++) {
5585                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5586                                 ta1 |= t;
5587                         } else {
5588                                 ta1 = 0;
5589                                 break;
5590                         }
5591                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5592                                 ta2 |= t;
5593                         } else {
5594                                 ta1 = 0;
5595                                 break;
5596                         }
5597                 }
5598                 if (ta1 == 0) {
5599                         /* This is sheer paranoia, but we handle it anyway */
5600                         if (acpi_tmp7) {
5601                                 printk(TPACPI_ERR
5602                                        "ThinkPad ACPI EC access misbehaving, "
5603                                        "falling back to ACPI TMPx access "
5604                                        "mode\n");
5605                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5606                         } else {
5607                                 printk(TPACPI_ERR
5608                                        "ThinkPad ACPI EC access misbehaving, "
5609                                        "disabling thermal sensors access\n");
5610                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5611                         }
5612                 } else {
5613                         thermal_read_mode =
5614                             (ta2 != 0) ?
5615                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5616                 }
5617         } else if (acpi_tmp7) {
5618                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5619                         /* 600e/x, 770e, 770x */
5620                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5621                 } else {
5622                         /* Standard ACPI TMPx access, max 8 sensors */
5623                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5624                 }
5625         } else {
5626                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5627                 thermal_read_mode = TPACPI_THERMAL_NONE;
5628         }
5629
5630         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5631                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5632                 thermal_read_mode);
5633
5634         switch (thermal_read_mode) {
5635         case TPACPI_THERMAL_TPEC_16:
5636                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5637                                 &thermal_temp_input16_group);
5638                 if (res)
5639                         return res;
5640                 break;
5641         case TPACPI_THERMAL_TPEC_8:
5642         case TPACPI_THERMAL_ACPI_TMP07:
5643         case TPACPI_THERMAL_ACPI_UPDT:
5644                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5645                                 &thermal_temp_input8_group);
5646                 if (res)
5647                         return res;
5648                 break;
5649         case TPACPI_THERMAL_NONE:
5650         default:
5651                 return 1;
5652         }
5653
5654         return 0;
5655 }
5656
5657 static void thermal_exit(void)
5658 {
5659         switch (thermal_read_mode) {
5660         case TPACPI_THERMAL_TPEC_16:
5661                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5662                                    &thermal_temp_input16_group);
5663                 break;
5664         case TPACPI_THERMAL_TPEC_8:
5665         case TPACPI_THERMAL_ACPI_TMP07:
5666         case TPACPI_THERMAL_ACPI_UPDT:
5667                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5668                                    &thermal_temp_input16_group);
5669                 break;
5670         case TPACPI_THERMAL_NONE:
5671         default:
5672                 break;
5673         }
5674 }
5675
5676 static int thermal_read(char *p)
5677 {
5678         int len = 0;
5679         int n, i;
5680         struct ibm_thermal_sensors_struct t;
5681
5682         n = thermal_get_sensors(&t);
5683         if (unlikely(n < 0))
5684                 return n;
5685
5686         len += sprintf(p + len, "temperatures:\t");
5687
5688         if (n > 0) {
5689                 for (i = 0; i < (n - 1); i++)
5690                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
5691                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
5692         } else
5693                 len += sprintf(p + len, "not supported\n");
5694
5695         return len;
5696 }
5697
5698 static struct ibm_struct thermal_driver_data = {
5699         .name = "thermal",
5700         .read = thermal_read,
5701         .exit = thermal_exit,
5702 };
5703
5704 /*************************************************************************
5705  * EC Dump subdriver
5706  */
5707
5708 static u8 ecdump_regs[256];
5709
5710 static int ecdump_read(char *p)
5711 {
5712         int len = 0;
5713         int i, j;
5714         u8 v;
5715
5716         len += sprintf(p + len, "EC      "
5717                        " +00 +01 +02 +03 +04 +05 +06 +07"
5718                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5719         for (i = 0; i < 256; i += 16) {
5720                 len += sprintf(p + len, "EC 0x%02x:", i);
5721                 for (j = 0; j < 16; j++) {
5722                         if (!acpi_ec_read(i + j, &v))
5723                                 break;
5724                         if (v != ecdump_regs[i + j])
5725                                 len += sprintf(p + len, " *%02x", v);
5726                         else
5727                                 len += sprintf(p + len, "  %02x", v);
5728                         ecdump_regs[i + j] = v;
5729                 }
5730                 len += sprintf(p + len, "\n");
5731                 if (j != 16)
5732                         break;
5733         }
5734
5735         /* These are way too dangerous to advertise openly... */
5736 #if 0
5737         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
5738                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5739         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
5740                        " (<offset> is 00-ff, <value> is 0-255)\n");
5741 #endif
5742         return len;
5743 }
5744
5745 static int ecdump_write(char *buf)
5746 {
5747         char *cmd;
5748         int i, v;
5749
5750         while ((cmd = next_cmd(&buf))) {
5751                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5752                         /* i and v set */
5753                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5754                         /* i and v set */
5755                 } else
5756                         return -EINVAL;
5757                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5758                         if (!acpi_ec_write(i, v))
5759                                 return -EIO;
5760                 } else
5761                         return -EINVAL;
5762         }
5763
5764         return 0;
5765 }
5766
5767 static struct ibm_struct ecdump_driver_data = {
5768         .name = "ecdump",
5769         .read = ecdump_read,
5770         .write = ecdump_write,
5771         .flags.experimental = 1,
5772 };
5773
5774 /*************************************************************************
5775  * Backlight/brightness subdriver
5776  */
5777
5778 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5779
5780 /*
5781  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
5782  * CMOS NVRAM byte 0x5E, bits 0-3.
5783  *
5784  * EC HBRV (0x31) has the following layout
5785  *   Bit 7: unknown function
5786  *   Bit 6: unknown function
5787  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5788  *   Bit 4: must be set to zero to avoid problems
5789  *   Bit 3-0: backlight brightness level
5790  *
5791  * brightness_get_raw returns status data in the HBRV layout
5792  *
5793  * WARNING: The X61 has been verified to use HBRV for something else, so
5794  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
5795  * testing on the very early *60 Lenovo models...
5796  */
5797
5798 enum {
5799         TP_EC_BACKLIGHT = 0x31,
5800
5801         /* TP_EC_BACKLIGHT bitmasks */
5802         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5803         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5804         TP_EC_BACKLIGHT_MAPSW = 0x20,
5805 };
5806
5807 enum tpacpi_brightness_access_mode {
5808         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
5809         TPACPI_BRGHT_MODE_EC,           /* EC control */
5810         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
5811         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
5812         TPACPI_BRGHT_MODE_MAX
5813 };
5814
5815 static struct backlight_device *ibm_backlight_device;
5816
5817 static enum tpacpi_brightness_access_mode brightness_mode =
5818                 TPACPI_BRGHT_MODE_MAX;
5819
5820 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5821
5822 static struct mutex brightness_mutex;
5823
5824 /* NVRAM brightness access,
5825  * call with brightness_mutex held! */
5826 static unsigned int tpacpi_brightness_nvram_get(void)
5827 {
5828         u8 lnvram;
5829
5830         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5831                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5832                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5833         lnvram &= (tp_features.bright_16levels) ? 0x0f : 0x07;
5834
5835         return lnvram;
5836 }
5837
5838 static void tpacpi_brightness_checkpoint_nvram(void)
5839 {
5840         u8 lec = 0;
5841         u8 b_nvram;
5842
5843         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
5844                 return;
5845
5846         vdbg_printk(TPACPI_DBG_BRGHT,
5847                 "trying to checkpoint backlight level to NVRAM...\n");
5848
5849         if (mutex_lock_killable(&brightness_mutex) < 0)
5850                 return;
5851
5852         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5853                 goto unlock;
5854         lec &= TP_EC_BACKLIGHT_LVLMSK;
5855         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
5856
5857         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5858                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
5859                 /* NVRAM needs update */
5860                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
5861                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
5862                 b_nvram |= lec;
5863                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
5864                 dbg_printk(TPACPI_DBG_BRGHT,
5865                            "updated NVRAM backlight level to %u (0x%02x)\n",
5866                            (unsigned int) lec, (unsigned int) b_nvram);
5867         } else
5868                 vdbg_printk(TPACPI_DBG_BRGHT,
5869                            "NVRAM backlight level already is %u (0x%02x)\n",
5870                            (unsigned int) lec, (unsigned int) b_nvram);
5871
5872 unlock:
5873         mutex_unlock(&brightness_mutex);
5874 }
5875
5876
5877 /* call with brightness_mutex held! */
5878 static int tpacpi_brightness_get_raw(int *status)
5879 {
5880         u8 lec = 0;
5881
5882         switch (brightness_mode) {
5883         case TPACPI_BRGHT_MODE_UCMS_STEP:
5884                 *status = tpacpi_brightness_nvram_get();
5885                 return 0;
5886         case TPACPI_BRGHT_MODE_EC:
5887         case TPACPI_BRGHT_MODE_ECNVRAM:
5888                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5889                         return -EIO;
5890                 *status = lec;
5891                 return 0;
5892         default:
5893                 return -ENXIO;
5894         }
5895 }
5896
5897 /* call with brightness_mutex held! */
5898 /* do NOT call with illegal backlight level value */
5899 static int tpacpi_brightness_set_ec(unsigned int value)
5900 {
5901         u8 lec = 0;
5902
5903         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5904                 return -EIO;
5905
5906         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
5907                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
5908                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
5909                 return -EIO;
5910
5911         return 0;
5912 }
5913
5914 /* call with brightness_mutex held! */
5915 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
5916 {
5917         int cmos_cmd, inc;
5918         unsigned int current_value, i;
5919
5920         current_value = tpacpi_brightness_nvram_get();
5921
5922         if (value == current_value)
5923                 return 0;
5924
5925         cmos_cmd = (value > current_value) ?
5926                         TP_CMOS_BRIGHTNESS_UP :
5927                         TP_CMOS_BRIGHTNESS_DOWN;
5928         inc = (value > current_value) ? 1 : -1;
5929
5930         for (i = current_value; i != value; i += inc)
5931                 if (issue_thinkpad_cmos_command(cmos_cmd))
5932                         return -EIO;
5933
5934         return 0;
5935 }
5936
5937 /* May return EINTR which can always be mapped to ERESTARTSYS */
5938 static int brightness_set(unsigned int value)
5939 {
5940         int res;
5941
5942         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
5943             value < 0)
5944                 return -EINVAL;
5945
5946         vdbg_printk(TPACPI_DBG_BRGHT,
5947                         "set backlight level to %d\n", value);
5948
5949         res = mutex_lock_killable(&brightness_mutex);
5950         if (res < 0)
5951                 return res;
5952
5953         switch (brightness_mode) {
5954         case TPACPI_BRGHT_MODE_EC:
5955         case TPACPI_BRGHT_MODE_ECNVRAM:
5956                 res = tpacpi_brightness_set_ec(value);
5957                 break;
5958         case TPACPI_BRGHT_MODE_UCMS_STEP:
5959                 res = tpacpi_brightness_set_ucmsstep(value);
5960                 break;
5961         default:
5962                 res = -ENXIO;
5963         }
5964
5965         mutex_unlock(&brightness_mutex);
5966         return res;
5967 }
5968
5969 /* sysfs backlight class ----------------------------------------------- */
5970
5971 static int brightness_update_status(struct backlight_device *bd)
5972 {
5973         unsigned int level =
5974                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
5975                  bd->props.power == FB_BLANK_UNBLANK) ?
5976                                 bd->props.brightness : 0;
5977
5978         dbg_printk(TPACPI_DBG_BRGHT,
5979                         "backlight: attempt to set level to %d\n",
5980                         level);
5981
5982         /* it is the backlight class's job (caller) to handle
5983          * EINTR and other errors properly */
5984         return brightness_set(level);
5985 }
5986
5987 static int brightness_get(struct backlight_device *bd)
5988 {
5989         int status, res;
5990
5991         res = mutex_lock_killable(&brightness_mutex);
5992         if (res < 0)
5993                 return 0;
5994
5995         res = tpacpi_brightness_get_raw(&status);
5996
5997         mutex_unlock(&brightness_mutex);
5998
5999         if (res < 0)
6000                 return 0;
6001
6002         return status & TP_EC_BACKLIGHT_LVLMSK;
6003 }
6004
6005 static struct backlight_ops ibm_backlight_data = {
6006         .get_brightness = brightness_get,
6007         .update_status  = brightness_update_status,
6008 };
6009
6010 /* --------------------------------------------------------------------- */
6011
6012 /*
6013  * These are only useful for models that have only one possibility
6014  * of GPU.  If the BIOS model handles both ATI and Intel, don't use
6015  * these quirks.
6016  */
6017 #define TPACPI_BRGHT_Q_NOEC     0x0001  /* Must NOT use EC HBRV */
6018 #define TPACPI_BRGHT_Q_EC       0x0002  /* Should or must use EC HBRV */
6019 #define TPACPI_BRGHT_Q_ASK      0x8000  /* Ask for user report */
6020
6021 static const struct tpacpi_quirk brightness_quirk_table[] __initconst = {
6022         /* Models with ATI GPUs known to require ECNVRAM mode */
6023         TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC),      /* T43/p ATI */
6024
6025         /* Models with ATI GPUs that can use ECNVRAM */
6026         TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC),
6027         TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6028         TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6029         TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6030
6031         /* Models with Intel Extreme Graphics 2 */
6032         TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC),
6033         TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_NOEC),
6034         TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_NOEC),
6035
6036         /* Models with Intel GMA900 */
6037         TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC),    /* T43, R52 */
6038         TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC),    /* X41 */
6039         TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC),    /* X41 Tablet */
6040 };
6041
6042 static int __init brightness_init(struct ibm_init_struct *iibm)
6043 {
6044         int b;
6045         unsigned long quirks;
6046
6047         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
6048
6049         mutex_init(&brightness_mutex);
6050
6051         quirks = tpacpi_check_quirks(brightness_quirk_table,
6052                                 ARRAY_SIZE(brightness_quirk_table));
6053
6054         /*
6055          * We always attempt to detect acpi support, so as to switch
6056          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
6057          * going to publish a backlight interface
6058          */
6059         b = tpacpi_check_std_acpi_brightness_support();
6060         if (b > 0) {
6061
6062                 if (acpi_video_backlight_support()) {
6063                         if (brightness_enable > 1) {
6064                                 printk(TPACPI_NOTICE
6065                                        "Standard ACPI backlight interface "
6066                                        "available, not loading native one.\n");
6067                                 return 1;
6068                         } else if (brightness_enable == 1) {
6069                                 printk(TPACPI_NOTICE
6070                                        "Backlight control force enabled, even if standard "
6071                                        "ACPI backlight interface is available\n");
6072                         }
6073                 } else {
6074                         if (brightness_enable > 1) {
6075                                 printk(TPACPI_NOTICE
6076                                        "Standard ACPI backlight interface not "
6077                                        "available, thinkpad_acpi native "
6078                                        "brightness control enabled\n");
6079                         }
6080                 }
6081         }
6082
6083         if (!brightness_enable) {
6084                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6085                            "brightness support disabled by "
6086                            "module parameter\n");
6087                 return 1;
6088         }
6089
6090         if (b > 16) {
6091                 printk(TPACPI_ERR
6092                        "Unsupported brightness interface, "
6093                        "please contact %s\n", TPACPI_MAIL);
6094                 return 1;
6095         }
6096         if (b == 16)
6097                 tp_features.bright_16levels = 1;
6098
6099         /*
6100          * Check for module parameter bogosity, note that we
6101          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6102          * able to detect "unspecified"
6103          */
6104         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6105                 return -EINVAL;
6106
6107         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6108         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6109             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6110                 if (quirks & TPACPI_BRGHT_Q_EC)
6111                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6112                 else
6113                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6114
6115                 dbg_printk(TPACPI_DBG_BRGHT,
6116                            "driver auto-selected brightness_mode=%d\n",
6117                            brightness_mode);
6118         }
6119
6120         /* Safety */
6121         if (thinkpad_id.vendor != PCI_VENDOR_ID_IBM &&
6122             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6123              brightness_mode == TPACPI_BRGHT_MODE_EC))
6124                 return -EINVAL;
6125
6126         if (tpacpi_brightness_get_raw(&b) < 0)
6127                 return 1;
6128
6129         if (tp_features.bright_16levels)
6130                 printk(TPACPI_INFO
6131                        "detected a 16-level brightness capable ThinkPad\n");
6132
6133         ibm_backlight_device = backlight_device_register(
6134                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
6135                                         &ibm_backlight_data);
6136         if (IS_ERR(ibm_backlight_device)) {
6137                 int rc = PTR_ERR(ibm_backlight_device);
6138                 ibm_backlight_device = NULL;
6139                 printk(TPACPI_ERR "Could not register backlight device\n");
6140                 return rc;
6141         }
6142         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6143                         "brightness is supported\n");
6144
6145         if (quirks & TPACPI_BRGHT_Q_ASK) {
6146                 printk(TPACPI_NOTICE
6147                         "brightness: will use unverified default: "
6148                         "brightness_mode=%d\n", brightness_mode);
6149                 printk(TPACPI_NOTICE
6150                         "brightness: please report to %s whether it works well "
6151                         "or not on your ThinkPad\n", TPACPI_MAIL);
6152         }
6153
6154         ibm_backlight_device->props.max_brightness =
6155                                 (tp_features.bright_16levels)? 15 : 7;
6156         ibm_backlight_device->props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6157         backlight_update_status(ibm_backlight_device);
6158
6159         return 0;
6160 }
6161
6162 static void brightness_suspend(pm_message_t state)
6163 {
6164         tpacpi_brightness_checkpoint_nvram();
6165 }
6166
6167 static void brightness_shutdown(void)
6168 {
6169         tpacpi_brightness_checkpoint_nvram();
6170 }
6171
6172 static void brightness_exit(void)
6173 {
6174         if (ibm_backlight_device) {
6175                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6176                             "calling backlight_device_unregister()\n");
6177                 backlight_device_unregister(ibm_backlight_device);
6178         }
6179
6180         tpacpi_brightness_checkpoint_nvram();
6181 }
6182
6183 static int brightness_read(char *p)
6184 {
6185         int len = 0;
6186         int level;
6187
6188         level = brightness_get(NULL);
6189         if (level < 0) {
6190                 len += sprintf(p + len, "level:\t\tunreadable\n");
6191         } else {
6192                 len += sprintf(p + len, "level:\t\t%d\n", level);
6193                 len += sprintf(p + len, "commands:\tup, down\n");
6194                 len += sprintf(p + len, "commands:\tlevel <level>"
6195                                " (<level> is 0-%d)\n",
6196                                (tp_features.bright_16levels) ? 15 : 7);
6197         }
6198
6199         return len;
6200 }
6201
6202 static int brightness_write(char *buf)
6203 {
6204         int level;
6205         int rc;
6206         char *cmd;
6207         int max_level = (tp_features.bright_16levels) ? 15 : 7;
6208
6209         level = brightness_get(NULL);
6210         if (level < 0)
6211                 return level;
6212
6213         while ((cmd = next_cmd(&buf))) {
6214                 if (strlencmp(cmd, "up") == 0) {
6215                         if (level < max_level)
6216                                 level++;
6217                 } else if (strlencmp(cmd, "down") == 0) {
6218                         if (level > 0)
6219                                 level--;
6220                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6221                            level >= 0 && level <= max_level) {
6222                         /* new level set */
6223                 } else
6224                         return -EINVAL;
6225         }
6226
6227         tpacpi_disclose_usertask("procfs brightness",
6228                         "set level to %d\n", level);
6229
6230         /*
6231          * Now we know what the final level should be, so we try to set it.
6232          * Doing it this way makes the syscall restartable in case of EINTR
6233          */
6234         rc = brightness_set(level);
6235         return (rc == -EINTR)? ERESTARTSYS : rc;
6236 }
6237
6238 static struct ibm_struct brightness_driver_data = {
6239         .name = "brightness",
6240         .read = brightness_read,
6241         .write = brightness_write,
6242         .exit = brightness_exit,
6243         .suspend = brightness_suspend,
6244         .shutdown = brightness_shutdown,
6245 };
6246
6247 /*************************************************************************
6248  * Volume subdriver
6249  */
6250
6251 static int volume_offset = 0x30;
6252
6253 static int volume_read(char *p)
6254 {
6255         int len = 0;
6256         u8 level;
6257
6258         if (!acpi_ec_read(volume_offset, &level)) {
6259                 len += sprintf(p + len, "level:\t\tunreadable\n");
6260         } else {
6261                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
6262                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
6263                 len += sprintf(p + len, "commands:\tup, down, mute\n");
6264                 len += sprintf(p + len, "commands:\tlevel <level>"
6265                                " (<level> is 0-15)\n");
6266         }
6267
6268         return len;
6269 }
6270
6271 static int volume_write(char *buf)
6272 {
6273         int cmos_cmd, inc, i;