thinkpad-acpi: add internal hotkey event API
[cascardo/linux.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 static void tpacpi_driver_event(const unsigned int hkey_event);
2018 static void hotkey_driver_event(const unsigned int scancode);
2019
2020 /* HKEY.MHKG() return bits */
2021 #define TP_HOTKEY_TABLET_MASK (1 << 3)
2022
2023 static int hotkey_get_wlsw(void)
2024 {
2025         int status;
2026
2027         if (!tp_features.hotkey_wlsw)
2028                 return -ENODEV;
2029
2030 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2031         if (dbg_wlswemul)
2032                 return (tpacpi_wlsw_emulstate) ?
2033                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2034 #endif
2035
2036         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
2037                 return -EIO;
2038
2039         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
2040 }
2041
2042 static int hotkey_get_tablet_mode(int *status)
2043 {
2044         int s;
2045
2046         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
2047                 return -EIO;
2048
2049         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
2050         return 0;
2051 }
2052
2053 /*
2054  * Reads current event mask from firmware, and updates
2055  * hotkey_acpi_mask accordingly.  Also resets any bits
2056  * from hotkey_user_mask that are unavailable to be
2057  * delivered (shadow requirement of the userspace ABI).
2058  *
2059  * Call with hotkey_mutex held
2060  */
2061 static int hotkey_mask_get(void)
2062 {
2063         if (tp_features.hotkey_mask) {
2064                 u32 m = 0;
2065
2066                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
2067                         return -EIO;
2068
2069                 hotkey_acpi_mask = m;
2070         } else {
2071                 /* no mask support doesn't mean no event support... */
2072                 hotkey_acpi_mask = hotkey_all_mask;
2073         }
2074
2075         /* sync userspace-visible mask */
2076         hotkey_user_mask &= (hotkey_acpi_mask | hotkey_source_mask);
2077
2078         return 0;
2079 }
2080
2081 void static hotkey_mask_warn_incomplete_mask(void)
2082 {
2083         /* log only what the user can fix... */
2084         const u32 wantedmask = hotkey_driver_mask &
2085                 ~(hotkey_acpi_mask | hotkey_source_mask) &
2086                 (hotkey_all_mask | TPACPI_HKEY_NVRAM_KNOWN_MASK);
2087
2088         if (wantedmask)
2089                 printk(TPACPI_NOTICE
2090                         "required events 0x%08x not enabled!\n",
2091                         wantedmask);
2092 }
2093
2094 /*
2095  * Set the firmware mask when supported
2096  *
2097  * Also calls hotkey_mask_get to update hotkey_acpi_mask.
2098  *
2099  * NOTE: does not set bits in hotkey_user_mask, but may reset them.
2100  *
2101  * Call with hotkey_mutex held
2102  */
2103 static int hotkey_mask_set(u32 mask)
2104 {
2105         int i;
2106         int rc = 0;
2107
2108         const u32 fwmask = mask & ~hotkey_source_mask;
2109
2110         if (tp_features.hotkey_mask) {
2111                 for (i = 0; i < 32; i++) {
2112                         if (!acpi_evalf(hkey_handle,
2113                                         NULL, "MHKM", "vdd", i + 1,
2114                                         !!(mask & (1 << i)))) {
2115                                 rc = -EIO;
2116                                 break;
2117                         }
2118                 }
2119         }
2120
2121         /*
2122          * We *must* make an inconditional call to hotkey_mask_get to
2123          * refresh hotkey_acpi_mask and update hotkey_user_mask
2124          *
2125          * Take the opportunity to also log when we cannot _enable_
2126          * a given event.
2127          */
2128         if (!hotkey_mask_get() && !rc && (fwmask & ~hotkey_acpi_mask)) {
2129                 printk(TPACPI_NOTICE
2130                        "asked for hotkey mask 0x%08x, but "
2131                        "firmware forced it to 0x%08x\n",
2132                        fwmask, hotkey_acpi_mask);
2133         }
2134
2135         hotkey_mask_warn_incomplete_mask();
2136
2137         return rc;
2138 }
2139
2140 /*
2141  * Sets hotkey_user_mask and tries to set the firmware mask
2142  *
2143  * Call with hotkey_mutex held
2144  */
2145 static int hotkey_user_mask_set(const u32 mask)
2146 {
2147         int rc;
2148
2149         /* Give people a chance to notice they are doing something that
2150          * is bound to go boom on their users sooner or later */
2151         if (!tp_warned.hotkey_mask_ff &&
2152             (mask == 0xffff || mask == 0xffffff ||
2153              mask == 0xffffffff)) {
2154                 tp_warned.hotkey_mask_ff = 1;
2155                 printk(TPACPI_NOTICE
2156                        "setting the hotkey mask to 0x%08x is likely "
2157                        "not the best way to go about it\n", mask);
2158                 printk(TPACPI_NOTICE
2159                        "please consider using the driver defaults, "
2160                        "and refer to up-to-date thinkpad-acpi "
2161                        "documentation\n");
2162         }
2163
2164         /* Try to enable what the user asked for, plus whatever we need.
2165          * this syncs everything but won't enable bits in hotkey_user_mask */
2166         rc = hotkey_mask_set((mask | hotkey_driver_mask) & ~hotkey_source_mask);
2167
2168         /* Enable the available bits in hotkey_user_mask */
2169         hotkey_user_mask = mask & (hotkey_acpi_mask | hotkey_source_mask);
2170
2171         return rc;
2172 }
2173
2174 /*
2175  * Sets the driver hotkey mask.
2176  *
2177  * Can be called even if the hotkey subdriver is inactive
2178  */
2179 static int tpacpi_hotkey_driver_mask_set(const u32 mask)
2180 {
2181         int rc;
2182
2183         /* Do the right thing if hotkey_init has not been called yet */
2184         if (!tp_features.hotkey) {
2185                 hotkey_driver_mask = mask;
2186                 return 0;
2187         }
2188
2189         mutex_lock(&hotkey_mutex);
2190
2191         HOTKEY_CONFIG_CRITICAL_START
2192         hotkey_driver_mask = mask;
2193         hotkey_source_mask |= (mask & ~hotkey_all_mask);
2194         HOTKEY_CONFIG_CRITICAL_END
2195
2196         rc = hotkey_mask_set((hotkey_acpi_mask | hotkey_driver_mask) &
2197                                                         ~hotkey_source_mask);
2198         mutex_unlock(&hotkey_mutex);
2199
2200         return rc;
2201 }
2202
2203 static int hotkey_status_get(int *status)
2204 {
2205         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
2206                 return -EIO;
2207
2208         return 0;
2209 }
2210
2211 static int hotkey_status_set(bool enable)
2212 {
2213         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
2214                 return -EIO;
2215
2216         return 0;
2217 }
2218
2219 static void tpacpi_input_send_tabletsw(void)
2220 {
2221         int state;
2222
2223         if (tp_features.hotkey_tablet &&
2224             !hotkey_get_tablet_mode(&state)) {
2225                 mutex_lock(&tpacpi_inputdev_send_mutex);
2226
2227                 input_report_switch(tpacpi_inputdev,
2228                                     SW_TABLET_MODE, !!state);
2229                 input_sync(tpacpi_inputdev);
2230
2231                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2232         }
2233 }
2234
2235 /* Do NOT call without validating scancode first */
2236 static void tpacpi_input_send_key(const unsigned int scancode)
2237 {
2238         const unsigned int keycode = hotkey_keycode_map[scancode];
2239
2240         if (keycode != KEY_RESERVED) {
2241                 mutex_lock(&tpacpi_inputdev_send_mutex);
2242
2243                 input_report_key(tpacpi_inputdev, keycode, 1);
2244                 if (keycode == KEY_UNKNOWN)
2245                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2246                                     scancode);
2247                 input_sync(tpacpi_inputdev);
2248
2249                 input_report_key(tpacpi_inputdev, keycode, 0);
2250                 if (keycode == KEY_UNKNOWN)
2251                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
2252                                     scancode);
2253                 input_sync(tpacpi_inputdev);
2254
2255                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2256         }
2257 }
2258
2259 /* Do NOT call without validating scancode first */
2260 static void tpacpi_input_send_key_masked(const unsigned int scancode)
2261 {
2262         hotkey_driver_event(scancode);
2263         if (hotkey_user_mask & (1 << scancode))
2264                 tpacpi_input_send_key(scancode);
2265 }
2266
2267 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2268 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
2269
2270 /* Do NOT call without validating scancode first */
2271 static void tpacpi_hotkey_send_key(unsigned int scancode)
2272 {
2273         tpacpi_input_send_key_masked(scancode);
2274         if (hotkey_report_mode < 2) {
2275                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
2276                                                 0x80, 0x1001 + scancode);
2277         }
2278 }
2279
2280 static void hotkey_read_nvram(struct tp_nvram_state *n, const u32 m)
2281 {
2282         u8 d;
2283
2284         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
2285                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
2286                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
2287                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
2288                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
2289                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
2290         }
2291         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
2292                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
2293                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2294         }
2295         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2296                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2297                 n->displayexp_toggle =
2298                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2299         }
2300         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2301                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2302                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2303                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2304                 n->brightness_toggle =
2305                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2306         }
2307         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2308                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2309                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2310                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2311                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2312                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2313         }
2314 }
2315
2316 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2317                                            struct tp_nvram_state *newn,
2318                                            const u32 event_mask)
2319 {
2320
2321 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2322         do { \
2323                 if ((event_mask & (1 << __scancode)) && \
2324                     oldn->__member != newn->__member) \
2325                         tpacpi_hotkey_send_key(__scancode); \
2326         } while (0)
2327
2328 #define TPACPI_MAY_SEND_KEY(__scancode) \
2329         do { \
2330                 if (event_mask & (1 << __scancode)) \
2331                         tpacpi_hotkey_send_key(__scancode); \
2332         } while (0)
2333
2334         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2335         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2336         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2337         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2338
2339         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2340
2341         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2342
2343         /* handle volume */
2344         if (oldn->volume_toggle != newn->volume_toggle) {
2345                 if (oldn->mute != newn->mute) {
2346                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2347                 }
2348                 if (oldn->volume_level > newn->volume_level) {
2349                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2350                 } else if (oldn->volume_level < newn->volume_level) {
2351                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2352                 } else if (oldn->mute == newn->mute) {
2353                         /* repeated key presses that didn't change state */
2354                         if (newn->mute) {
2355                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2356                         } else if (newn->volume_level != 0) {
2357                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2358                         } else {
2359                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2360                         }
2361                 }
2362         }
2363
2364         /* handle brightness */
2365         if (oldn->brightness_toggle != newn->brightness_toggle) {
2366                 if (oldn->brightness_level < newn->brightness_level) {
2367                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2368                 } else if (oldn->brightness_level > newn->brightness_level) {
2369                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2370                 } else {
2371                         /* repeated key presses that didn't change state */
2372                         if (newn->brightness_level != 0) {
2373                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2374                         } else {
2375                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2376                         }
2377                 }
2378         }
2379
2380 #undef TPACPI_COMPARE_KEY
2381 #undef TPACPI_MAY_SEND_KEY
2382 }
2383
2384 /*
2385  * Polling driver
2386  *
2387  * We track all events in hotkey_source_mask all the time, since
2388  * most of them are edge-based.  We only issue those requested by
2389  * hotkey_user_mask or hotkey_driver_mask, though.
2390  */
2391 static int hotkey_kthread(void *data)
2392 {
2393         struct tp_nvram_state s[2];
2394         u32 poll_mask, event_mask;
2395         unsigned int si, so;
2396         unsigned long t;
2397         unsigned int change_detector, must_reset;
2398         unsigned int poll_freq;
2399
2400         mutex_lock(&hotkey_thread_mutex);
2401
2402         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2403                 goto exit;
2404
2405         set_freezable();
2406
2407         so = 0;
2408         si = 1;
2409         t = 0;
2410
2411         /* Initial state for compares */
2412         mutex_lock(&hotkey_thread_data_mutex);
2413         change_detector = hotkey_config_change;
2414         poll_mask = hotkey_source_mask;
2415         event_mask = hotkey_source_mask &
2416                         (hotkey_driver_mask | hotkey_user_mask);
2417         poll_freq = hotkey_poll_freq;
2418         mutex_unlock(&hotkey_thread_data_mutex);
2419         hotkey_read_nvram(&s[so], poll_mask);
2420
2421         while (!kthread_should_stop()) {
2422                 if (t == 0) {
2423                         if (likely(poll_freq))
2424                                 t = 1000/poll_freq;
2425                         else
2426                                 t = 100;        /* should never happen... */
2427                 }
2428                 t = msleep_interruptible(t);
2429                 if (unlikely(kthread_should_stop()))
2430                         break;
2431                 must_reset = try_to_freeze();
2432                 if (t > 0 && !must_reset)
2433                         continue;
2434
2435                 mutex_lock(&hotkey_thread_data_mutex);
2436                 if (must_reset || hotkey_config_change != change_detector) {
2437                         /* forget old state on thaw or config change */
2438                         si = so;
2439                         t = 0;
2440                         change_detector = hotkey_config_change;
2441                 }
2442                 poll_mask = hotkey_source_mask;
2443                 event_mask = hotkey_source_mask &
2444                                 (hotkey_driver_mask | hotkey_user_mask);
2445                 poll_freq = hotkey_poll_freq;
2446                 mutex_unlock(&hotkey_thread_data_mutex);
2447
2448                 if (likely(poll_mask)) {
2449                         hotkey_read_nvram(&s[si], poll_mask);
2450                         if (likely(si != so)) {
2451                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2452                                                                 event_mask);
2453                         }
2454                 }
2455
2456                 so = si;
2457                 si ^= 1;
2458         }
2459
2460 exit:
2461         mutex_unlock(&hotkey_thread_mutex);
2462         return 0;
2463 }
2464
2465 /* call with hotkey_mutex held */
2466 static void hotkey_poll_stop_sync(void)
2467 {
2468         if (tpacpi_hotkey_task) {
2469                 if (frozen(tpacpi_hotkey_task) ||
2470                     freezing(tpacpi_hotkey_task))
2471                         thaw_process(tpacpi_hotkey_task);
2472
2473                 kthread_stop(tpacpi_hotkey_task);
2474                 tpacpi_hotkey_task = NULL;
2475                 mutex_lock(&hotkey_thread_mutex);
2476                 /* at this point, the thread did exit */
2477                 mutex_unlock(&hotkey_thread_mutex);
2478         }
2479 }
2480
2481 /* call with hotkey_mutex held */
2482 static void hotkey_poll_setup(bool may_warn)
2483 {
2484         const u32 poll_driver_mask = hotkey_driver_mask & hotkey_source_mask;
2485         const u32 poll_user_mask = hotkey_user_mask & hotkey_source_mask;
2486
2487         if (hotkey_poll_freq > 0 &&
2488             (poll_driver_mask ||
2489              (poll_user_mask && tpacpi_inputdev->users > 0))) {
2490                 if (!tpacpi_hotkey_task) {
2491                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2492                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2493                         if (IS_ERR(tpacpi_hotkey_task)) {
2494                                 tpacpi_hotkey_task = NULL;
2495                                 printk(TPACPI_ERR
2496                                        "could not create kernel thread "
2497                                        "for hotkey polling\n");
2498                         }
2499                 }
2500         } else {
2501                 hotkey_poll_stop_sync();
2502                 if (may_warn && (poll_driver_mask || poll_user_mask) &&
2503                     hotkey_poll_freq == 0) {
2504                         printk(TPACPI_NOTICE
2505                                 "hot keys 0x%08x and/or events 0x%08x "
2506                                 "require polling, which is currently "
2507                                 "disabled\n",
2508                                 poll_user_mask, poll_driver_mask);
2509                 }
2510         }
2511 }
2512
2513 static void hotkey_poll_setup_safe(bool may_warn)
2514 {
2515         mutex_lock(&hotkey_mutex);
2516         hotkey_poll_setup(may_warn);
2517         mutex_unlock(&hotkey_mutex);
2518 }
2519
2520 /* call with hotkey_mutex held */
2521 static void hotkey_poll_set_freq(unsigned int freq)
2522 {
2523         if (!freq)
2524                 hotkey_poll_stop_sync();
2525
2526         hotkey_poll_freq = freq;
2527 }
2528
2529 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2530
2531 static void hotkey_poll_setup_safe(bool __unused)
2532 {
2533 }
2534
2535 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2536
2537 static int hotkey_inputdev_open(struct input_dev *dev)
2538 {
2539         switch (tpacpi_lifecycle) {
2540         case TPACPI_LIFE_INIT:
2541                 /*
2542                  * hotkey_init will call hotkey_poll_setup_safe
2543                  * at the appropriate moment
2544                  */
2545                 return 0;
2546         case TPACPI_LIFE_EXITING:
2547                 return -EBUSY;
2548         case TPACPI_LIFE_RUNNING:
2549                 hotkey_poll_setup_safe(false);
2550                 return 0;
2551         }
2552
2553         /* Should only happen if tpacpi_lifecycle is corrupt */
2554         BUG();
2555         return -EBUSY;
2556 }
2557
2558 static void hotkey_inputdev_close(struct input_dev *dev)
2559 {
2560         /* disable hotkey polling when possible */
2561         if (tpacpi_lifecycle == TPACPI_LIFE_RUNNING &&
2562             !(hotkey_source_mask & hotkey_driver_mask))
2563                 hotkey_poll_setup_safe(false);
2564 }
2565
2566 /* sysfs hotkey enable ------------------------------------------------- */
2567 static ssize_t hotkey_enable_show(struct device *dev,
2568                            struct device_attribute *attr,
2569                            char *buf)
2570 {
2571         int res, status;
2572
2573         printk_deprecated_attribute("hotkey_enable",
2574                         "Hotkey reporting is always enabled");
2575
2576         res = hotkey_status_get(&status);
2577         if (res)
2578                 return res;
2579
2580         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2581 }
2582
2583 static ssize_t hotkey_enable_store(struct device *dev,
2584                             struct device_attribute *attr,
2585                             const char *buf, size_t count)
2586 {
2587         unsigned long t;
2588
2589         printk_deprecated_attribute("hotkey_enable",
2590                         "Hotkeys can be disabled through hotkey_mask");
2591
2592         if (parse_strtoul(buf, 1, &t))
2593                 return -EINVAL;
2594
2595         if (t == 0)
2596                 return -EPERM;
2597
2598         return count;
2599 }
2600
2601 static struct device_attribute dev_attr_hotkey_enable =
2602         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2603                 hotkey_enable_show, hotkey_enable_store);
2604
2605 /* sysfs hotkey mask --------------------------------------------------- */
2606 static ssize_t hotkey_mask_show(struct device *dev,
2607                            struct device_attribute *attr,
2608                            char *buf)
2609 {
2610         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_user_mask);
2611 }
2612
2613 static ssize_t hotkey_mask_store(struct device *dev,
2614                             struct device_attribute *attr,
2615                             const char *buf, size_t count)
2616 {
2617         unsigned long t;
2618         int res;
2619
2620         if (parse_strtoul(buf, 0xffffffffUL, &t))
2621                 return -EINVAL;
2622
2623         if (mutex_lock_killable(&hotkey_mutex))
2624                 return -ERESTARTSYS;
2625
2626         res = hotkey_user_mask_set(t);
2627
2628 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2629         hotkey_poll_setup(true);
2630 #endif
2631
2632         mutex_unlock(&hotkey_mutex);
2633
2634         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2635
2636         return (res) ? res : count;
2637 }
2638
2639 static struct device_attribute dev_attr_hotkey_mask =
2640         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2641                 hotkey_mask_show, hotkey_mask_store);
2642
2643 /* sysfs hotkey bios_enabled ------------------------------------------- */
2644 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2645                            struct device_attribute *attr,
2646                            char *buf)
2647 {
2648         return sprintf(buf, "0\n");
2649 }
2650
2651 static struct device_attribute dev_attr_hotkey_bios_enabled =
2652         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2653
2654 /* sysfs hotkey bios_mask ---------------------------------------------- */
2655 static ssize_t hotkey_bios_mask_show(struct device *dev,
2656                            struct device_attribute *attr,
2657                            char *buf)
2658 {
2659         printk_deprecated_attribute("hotkey_bios_mask",
2660                         "This attribute is useless.");
2661         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2662 }
2663
2664 static struct device_attribute dev_attr_hotkey_bios_mask =
2665         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2666
2667 /* sysfs hotkey all_mask ----------------------------------------------- */
2668 static ssize_t hotkey_all_mask_show(struct device *dev,
2669                            struct device_attribute *attr,
2670                            char *buf)
2671 {
2672         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2673                                 hotkey_all_mask | hotkey_source_mask);
2674 }
2675
2676 static struct device_attribute dev_attr_hotkey_all_mask =
2677         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2678
2679 /* sysfs hotkey recommended_mask --------------------------------------- */
2680 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2681                                             struct device_attribute *attr,
2682                                             char *buf)
2683 {
2684         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2685                         (hotkey_all_mask | hotkey_source_mask)
2686                         & ~hotkey_reserved_mask);
2687 }
2688
2689 static struct device_attribute dev_attr_hotkey_recommended_mask =
2690         __ATTR(hotkey_recommended_mask, S_IRUGO,
2691                 hotkey_recommended_mask_show, NULL);
2692
2693 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2694
2695 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2696 static ssize_t hotkey_source_mask_show(struct device *dev,
2697                            struct device_attribute *attr,
2698                            char *buf)
2699 {
2700         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2701 }
2702
2703 static ssize_t hotkey_source_mask_store(struct device *dev,
2704                             struct device_attribute *attr,
2705                             const char *buf, size_t count)
2706 {
2707         unsigned long t;
2708         u32 r_ev;
2709         int rc;
2710
2711         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2712                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2713                 return -EINVAL;
2714
2715         if (mutex_lock_killable(&hotkey_mutex))
2716                 return -ERESTARTSYS;
2717
2718         HOTKEY_CONFIG_CRITICAL_START
2719         hotkey_source_mask = t;
2720         HOTKEY_CONFIG_CRITICAL_END
2721
2722         rc = hotkey_mask_set((hotkey_user_mask | hotkey_driver_mask) &
2723                         ~hotkey_source_mask);
2724         hotkey_poll_setup(true);
2725
2726         /* check if events needed by the driver got disabled */
2727         r_ev = hotkey_driver_mask & ~(hotkey_acpi_mask & hotkey_all_mask)
2728                 & ~hotkey_source_mask & TPACPI_HKEY_NVRAM_KNOWN_MASK;
2729
2730         mutex_unlock(&hotkey_mutex);
2731
2732         if (rc < 0)
2733                 printk(TPACPI_ERR "hotkey_source_mask: failed to update the"
2734                         "firmware event mask!\n");
2735
2736         if (r_ev)
2737                 printk(TPACPI_NOTICE "hotkey_source_mask: "
2738                         "some important events were disabled: "
2739                         "0x%04x\n", r_ev);
2740
2741         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2742
2743         return (rc < 0) ? rc : count;
2744 }
2745
2746 static struct device_attribute dev_attr_hotkey_source_mask =
2747         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2748                 hotkey_source_mask_show, hotkey_source_mask_store);
2749
2750 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2751 static ssize_t hotkey_poll_freq_show(struct device *dev,
2752                            struct device_attribute *attr,
2753                            char *buf)
2754 {
2755         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2756 }
2757
2758 static ssize_t hotkey_poll_freq_store(struct device *dev,
2759                             struct device_attribute *attr,
2760                             const char *buf, size_t count)
2761 {
2762         unsigned long t;
2763
2764         if (parse_strtoul(buf, 25, &t))
2765                 return -EINVAL;
2766
2767         if (mutex_lock_killable(&hotkey_mutex))
2768                 return -ERESTARTSYS;
2769
2770         hotkey_poll_set_freq(t);
2771         hotkey_poll_setup(true);
2772
2773         mutex_unlock(&hotkey_mutex);
2774
2775         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2776
2777         return count;
2778 }
2779
2780 static struct device_attribute dev_attr_hotkey_poll_freq =
2781         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2782                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2783
2784 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2785
2786 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2787 static ssize_t hotkey_radio_sw_show(struct device *dev,
2788                            struct device_attribute *attr,
2789                            char *buf)
2790 {
2791         int res;
2792         res = hotkey_get_wlsw();
2793         if (res < 0)
2794                 return res;
2795
2796         /* Opportunistic update */
2797         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2798
2799         return snprintf(buf, PAGE_SIZE, "%d\n",
2800                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2801 }
2802
2803 static struct device_attribute dev_attr_hotkey_radio_sw =
2804         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
2805
2806 static void hotkey_radio_sw_notify_change(void)
2807 {
2808         if (tp_features.hotkey_wlsw)
2809                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2810                              "hotkey_radio_sw");
2811 }
2812
2813 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2814 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2815                            struct device_attribute *attr,
2816                            char *buf)
2817 {
2818         int res, s;
2819         res = hotkey_get_tablet_mode(&s);
2820         if (res < 0)
2821                 return res;
2822
2823         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2824 }
2825
2826 static struct device_attribute dev_attr_hotkey_tablet_mode =
2827         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2828
2829 static void hotkey_tablet_mode_notify_change(void)
2830 {
2831         if (tp_features.hotkey_tablet)
2832                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2833                              "hotkey_tablet_mode");
2834 }
2835
2836 /* sysfs hotkey report_mode -------------------------------------------- */
2837 static ssize_t hotkey_report_mode_show(struct device *dev,
2838                            struct device_attribute *attr,
2839                            char *buf)
2840 {
2841         return snprintf(buf, PAGE_SIZE, "%d\n",
2842                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2843 }
2844
2845 static struct device_attribute dev_attr_hotkey_report_mode =
2846         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2847
2848 /* sysfs wakeup reason (pollable) -------------------------------------- */
2849 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2850                            struct device_attribute *attr,
2851                            char *buf)
2852 {
2853         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2854 }
2855
2856 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2857         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2858
2859 static void hotkey_wakeup_reason_notify_change(void)
2860 {
2861         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2862                      "wakeup_reason");
2863 }
2864
2865 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2866 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2867                            struct device_attribute *attr,
2868                            char *buf)
2869 {
2870         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2871 }
2872
2873 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2874         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2875                hotkey_wakeup_hotunplug_complete_show, NULL);
2876
2877 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2878 {
2879         sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2880                      "wakeup_hotunplug_complete");
2881 }
2882
2883 /* --------------------------------------------------------------------- */
2884
2885 static struct attribute *hotkey_attributes[] __initdata = {
2886         &dev_attr_hotkey_enable.attr,
2887         &dev_attr_hotkey_bios_enabled.attr,
2888         &dev_attr_hotkey_bios_mask.attr,
2889         &dev_attr_hotkey_report_mode.attr,
2890         &dev_attr_hotkey_wakeup_reason.attr,
2891         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2892         &dev_attr_hotkey_mask.attr,
2893         &dev_attr_hotkey_all_mask.attr,
2894         &dev_attr_hotkey_recommended_mask.attr,
2895 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2896         &dev_attr_hotkey_source_mask.attr,
2897         &dev_attr_hotkey_poll_freq.attr,
2898 #endif
2899 };
2900
2901 /*
2902  * Sync both the hw and sw blocking state of all switches
2903  */
2904 static void tpacpi_send_radiosw_update(void)
2905 {
2906         int wlsw;
2907
2908         /*
2909          * We must sync all rfkill controllers *before* issuing any
2910          * rfkill input events, or we will race the rfkill core input
2911          * handler.
2912          *
2913          * tpacpi_inputdev_send_mutex works as a syncronization point
2914          * for the above.
2915          *
2916          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2917          */
2918
2919         wlsw = hotkey_get_wlsw();
2920
2921         /* Sync hw blocking state first if it is hw-blocked */
2922         if (wlsw == TPACPI_RFK_RADIO_OFF)
2923                 tpacpi_rfk_update_hwblock_state(true);
2924
2925         /* Sync sw blocking state */
2926         tpacpi_rfk_update_swstate_all();
2927
2928         /* Sync hw blocking state last if it is hw-unblocked */
2929         if (wlsw == TPACPI_RFK_RADIO_ON)
2930                 tpacpi_rfk_update_hwblock_state(false);
2931
2932         /* Issue rfkill input event for WLSW switch */
2933         if (!(wlsw < 0)) {
2934                 mutex_lock(&tpacpi_inputdev_send_mutex);
2935
2936                 input_report_switch(tpacpi_inputdev,
2937                                     SW_RFKILL_ALL, (wlsw > 0));
2938                 input_sync(tpacpi_inputdev);
2939
2940                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2941         }
2942
2943         /*
2944          * this can be unconditional, as we will poll state again
2945          * if userspace uses the notify to read data
2946          */
2947         hotkey_radio_sw_notify_change();
2948 }
2949
2950 static void hotkey_exit(void)
2951 {
2952 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2953         mutex_lock(&hotkey_mutex);
2954         hotkey_poll_stop_sync();
2955         mutex_unlock(&hotkey_mutex);
2956 #endif
2957
2958         if (hotkey_dev_attributes)
2959                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
2960
2961         kfree(hotkey_keycode_map);
2962
2963         dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
2964                    "restoring original HKEY status and mask\n");
2965         /* yes, there is a bitwise or below, we want the
2966          * functions to be called even if one of them fail */
2967         if (((tp_features.hotkey_mask &&
2968               hotkey_mask_set(hotkey_orig_mask)) |
2969              hotkey_status_set(false)) != 0)
2970                 printk(TPACPI_ERR
2971                        "failed to restore hot key mask "
2972                        "to BIOS defaults\n");
2973 }
2974
2975 static void __init hotkey_unmap(const unsigned int scancode)
2976 {
2977         if (hotkey_keycode_map[scancode] != KEY_RESERVED) {
2978                 clear_bit(hotkey_keycode_map[scancode],
2979                           tpacpi_inputdev->keybit);
2980                 hotkey_keycode_map[scancode] = KEY_RESERVED;
2981         }
2982 }
2983
2984 /*
2985  * HKEY quirks:
2986  *   TPACPI_HK_Q_INIMASK:       Supports FN+F3,FN+F4,FN+F12
2987  */
2988
2989 #define TPACPI_HK_Q_INIMASK     0x0001
2990
2991 static const struct tpacpi_quirk tpacpi_hotkey_qtable[] __initconst = {
2992         TPACPI_Q_IBM('I', 'H', TPACPI_HK_Q_INIMASK), /* 600E */
2993         TPACPI_Q_IBM('I', 'N', TPACPI_HK_Q_INIMASK), /* 600E */
2994         TPACPI_Q_IBM('I', 'D', TPACPI_HK_Q_INIMASK), /* 770, 770E, 770ED */
2995         TPACPI_Q_IBM('I', 'W', TPACPI_HK_Q_INIMASK), /* A20m */
2996         TPACPI_Q_IBM('I', 'V', TPACPI_HK_Q_INIMASK), /* A20p */
2997         TPACPI_Q_IBM('1', '0', TPACPI_HK_Q_INIMASK), /* A21e, A22e */
2998         TPACPI_Q_IBM('K', 'U', TPACPI_HK_Q_INIMASK), /* A21e */
2999         TPACPI_Q_IBM('K', 'X', TPACPI_HK_Q_INIMASK), /* A21m, A22m */
3000         TPACPI_Q_IBM('K', 'Y', TPACPI_HK_Q_INIMASK), /* A21p, A22p */
3001         TPACPI_Q_IBM('1', 'B', TPACPI_HK_Q_INIMASK), /* A22e */
3002         TPACPI_Q_IBM('1', '3', TPACPI_HK_Q_INIMASK), /* A22m */
3003         TPACPI_Q_IBM('1', 'E', TPACPI_HK_Q_INIMASK), /* A30/p (0) */
3004         TPACPI_Q_IBM('1', 'C', TPACPI_HK_Q_INIMASK), /* R30 */
3005         TPACPI_Q_IBM('1', 'F', TPACPI_HK_Q_INIMASK), /* R31 */
3006         TPACPI_Q_IBM('I', 'Y', TPACPI_HK_Q_INIMASK), /* T20 */
3007         TPACPI_Q_IBM('K', 'Z', TPACPI_HK_Q_INIMASK), /* T21 */
3008         TPACPI_Q_IBM('1', '6', TPACPI_HK_Q_INIMASK), /* T22 */
3009         TPACPI_Q_IBM('I', 'Z', TPACPI_HK_Q_INIMASK), /* X20, X21 */
3010         TPACPI_Q_IBM('1', 'D', TPACPI_HK_Q_INIMASK), /* X22, X23, X24 */
3011 };
3012
3013 static int __init hotkey_init(struct ibm_init_struct *iibm)
3014 {
3015         /* Requirements for changing the default keymaps:
3016          *
3017          * 1. Many of the keys are mapped to KEY_RESERVED for very
3018          *    good reasons.  Do not change them unless you have deep
3019          *    knowledge on the IBM and Lenovo ThinkPad firmware for
3020          *    the various ThinkPad models.  The driver behaves
3021          *    differently for KEY_RESERVED: such keys have their
3022          *    hot key mask *unset* in mask_recommended, and also
3023          *    in the initial hot key mask programmed into the
3024          *    firmware at driver load time, which means the firm-
3025          *    ware may react very differently if you change them to
3026          *    something else;
3027          *
3028          * 2. You must be subscribed to the linux-thinkpad and
3029          *    ibm-acpi-devel mailing lists, and you should read the
3030          *    list archives since 2007 if you want to change the
3031          *    keymaps.  This requirement exists so that you will
3032          *    know the past history of problems with the thinkpad-
3033          *    acpi driver keymaps, and also that you will be
3034          *    listening to any bug reports;
3035          *
3036          * 3. Do not send thinkpad-acpi specific patches directly to
3037          *    for merging, *ever*.  Send them to the linux-acpi
3038          *    mailinglist for comments.  Merging is to be done only
3039          *    through acpi-test and the ACPI maintainer.
3040          *
3041          * If the above is too much to ask, don't change the keymap.
3042          * Ask the thinkpad-acpi maintainer to do it, instead.
3043          */
3044         static u16 ibm_keycode_map[] __initdata = {
3045                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3046                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
3047                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3048                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3049
3050                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3051                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3052                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3053                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3054
3055                 /* brightness: firmware always reacts to them */
3056                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
3057                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
3058
3059                 /* Thinklight: firmware always react to it */
3060                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3061
3062                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3063                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3064
3065                 /* Volume: firmware always react to it and reprograms
3066                  * the built-in *extra* mixer.  Never map it to control
3067                  * another mixer by default. */
3068                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3069                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3070                 KEY_RESERVED,   /* 0x16: MUTE */
3071
3072                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3073
3074                 /* (assignments unknown, please report if found) */
3075                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3076                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3077         };
3078         static u16 lenovo_keycode_map[] __initdata = {
3079                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
3080                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
3081                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
3082                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
3083
3084                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
3085                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
3086                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
3087                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
3088
3089                 /* These should be enabled --only-- when ACPI video
3090                  * is disabled (i.e. in "vendor" mode), and are handled
3091                  * in a special way by the init code */
3092                 KEY_BRIGHTNESSUP,       /* 0x0F: FN+HOME (brightness up) */
3093                 KEY_BRIGHTNESSDOWN,     /* 0x10: FN+END (brightness down) */
3094
3095                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
3096
3097                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
3098                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
3099
3100                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
3101                  * react to it and reprograms the built-in *extra* mixer.
3102                  * Never map it to control another mixer by default.
3103                  *
3104                  * T60?, T61, R60?, R61: firmware and EC tries to send
3105                  * these over the regular keyboard, so these are no-ops,
3106                  * but there are still weird bugs re. MUTE, so do not
3107                  * change unless you get test reports from all Lenovo
3108                  * models.  May cause the BIOS to interfere with the
3109                  * HDA mixer.
3110                  */
3111                 KEY_RESERVED,   /* 0x14: VOLUME UP */
3112                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
3113                 KEY_RESERVED,   /* 0x16: MUTE */
3114
3115                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
3116
3117                 /* (assignments unknown, please report if found) */
3118                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3119                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
3120         };
3121
3122 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
3123 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
3124 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
3125
3126         int res, i;
3127         int status;
3128         int hkeyv;
3129
3130         unsigned long quirks;
3131
3132         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3133                         "initializing hotkey subdriver\n");
3134
3135         BUG_ON(!tpacpi_inputdev);
3136         BUG_ON(tpacpi_inputdev->open != NULL ||
3137                tpacpi_inputdev->close != NULL);
3138
3139         TPACPI_ACPIHANDLE_INIT(hkey);
3140         mutex_init(&hotkey_mutex);
3141
3142 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3143         mutex_init(&hotkey_thread_mutex);
3144         mutex_init(&hotkey_thread_data_mutex);
3145 #endif
3146
3147         /* hotkey not supported on 570 */
3148         tp_features.hotkey = hkey_handle != NULL;
3149
3150         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3151                 "hotkeys are %s\n",
3152                 str_supported(tp_features.hotkey));
3153
3154         if (!tp_features.hotkey)
3155                 return 1;
3156
3157         quirks = tpacpi_check_quirks(tpacpi_hotkey_qtable,
3158                                      ARRAY_SIZE(tpacpi_hotkey_qtable));
3159
3160         tpacpi_disable_brightness_delay();
3161
3162         /* MUST have enough space for all attributes to be added to
3163          * hotkey_dev_attributes */
3164         hotkey_dev_attributes = create_attr_set(
3165                                         ARRAY_SIZE(hotkey_attributes) + 2,
3166                                         NULL);
3167         if (!hotkey_dev_attributes)
3168                 return -ENOMEM;
3169         res = add_many_to_attr_set(hotkey_dev_attributes,
3170                         hotkey_attributes,
3171                         ARRAY_SIZE(hotkey_attributes));
3172         if (res)
3173                 goto err_exit;
3174
3175         /* mask not supported on 600e/x, 770e, 770x, A21e, A2xm/p,
3176            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
3177            for HKEY interface version 0x100 */
3178         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
3179                 if ((hkeyv >> 8) != 1) {
3180                         printk(TPACPI_ERR "unknown version of the "
3181                                "HKEY interface: 0x%x\n", hkeyv);
3182                         printk(TPACPI_ERR "please report this to %s\n",
3183                                TPACPI_MAIL);
3184                 } else {
3185                         /*
3186                          * MHKV 0x100 in A31, R40, R40e,
3187                          * T4x, X31, and later
3188                          */
3189                         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3190                                 "firmware HKEY interface version: 0x%x\n",
3191                                 hkeyv);
3192
3193                         /* Paranoia check AND init hotkey_all_mask */
3194                         if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
3195                                         "MHKA", "qd")) {
3196                                 printk(TPACPI_ERR
3197                                        "missing MHKA handler, "
3198                                        "please report this to %s\n",
3199                                        TPACPI_MAIL);
3200                                 /* Fallback: pre-init for FN+F3,F4,F12 */
3201                                 hotkey_all_mask = 0x080cU;
3202                         } else {
3203                                 tp_features.hotkey_mask = 1;
3204                         }
3205                 }
3206         }
3207
3208         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3209                 "hotkey masks are %s\n",
3210                 str_supported(tp_features.hotkey_mask));
3211
3212         /* Init hotkey_all_mask if not initialized yet */
3213         if (!tp_features.hotkey_mask && !hotkey_all_mask &&
3214             (quirks & TPACPI_HK_Q_INIMASK))
3215                 hotkey_all_mask = 0x080cU;  /* FN+F12, FN+F4, FN+F3 */
3216
3217         /* Init hotkey_acpi_mask and hotkey_orig_mask */
3218         if (tp_features.hotkey_mask) {
3219                 /* hotkey_source_mask *must* be zero for
3220                  * the first hotkey_mask_get to return hotkey_orig_mask */
3221                 res = hotkey_mask_get();
3222                 if (res)
3223                         goto err_exit;
3224
3225                 hotkey_orig_mask = hotkey_acpi_mask;
3226         } else {
3227                 hotkey_orig_mask = hotkey_all_mask;
3228                 hotkey_acpi_mask = hotkey_all_mask;
3229         }
3230
3231 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3232         if (dbg_wlswemul) {
3233                 tp_features.hotkey_wlsw = 1;
3234                 printk(TPACPI_INFO
3235                         "radio switch emulation enabled\n");
3236         } else
3237 #endif
3238         /* Not all thinkpads have a hardware radio switch */
3239         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
3240                 tp_features.hotkey_wlsw = 1;
3241                 printk(TPACPI_INFO
3242                         "radio switch found; radios are %s\n",
3243                         enabled(status, 0));
3244         }
3245         if (tp_features.hotkey_wlsw)
3246                 res = add_to_attr_set(hotkey_dev_attributes,
3247                                 &dev_attr_hotkey_radio_sw.attr);
3248
3249         /* For X41t, X60t, X61t Tablets... */
3250         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
3251                 tp_features.hotkey_tablet = 1;
3252                 printk(TPACPI_INFO
3253                         "possible tablet mode switch found; "
3254                         "ThinkPad in %s mode\n",
3255                         (status & TP_HOTKEY_TABLET_MASK)?
3256                                 "tablet" : "laptop");
3257                 res = add_to_attr_set(hotkey_dev_attributes,
3258                                 &dev_attr_hotkey_tablet_mode.attr);
3259         }
3260
3261         if (!res)
3262                 res = register_attr_set_with_sysfs(
3263                                 hotkey_dev_attributes,
3264                                 &tpacpi_pdev->dev.kobj);
3265         if (res)
3266                 goto err_exit;
3267
3268         /* Set up key map */
3269
3270         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
3271                                         GFP_KERNEL);
3272         if (!hotkey_keycode_map) {
3273                 printk(TPACPI_ERR
3274                         "failed to allocate memory for key map\n");
3275                 res = -ENOMEM;
3276                 goto err_exit;
3277         }
3278
3279         if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
3280                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3281                            "using Lenovo default hot key map\n");
3282                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
3283                         TPACPI_HOTKEY_MAP_SIZE);
3284         } else {
3285                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3286                            "using IBM default hot key map\n");
3287                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
3288                         TPACPI_HOTKEY_MAP_SIZE);
3289         }
3290
3291         set_bit(EV_KEY, tpacpi_inputdev->evbit);
3292         set_bit(EV_MSC, tpacpi_inputdev->evbit);
3293         set_bit(MSC_SCAN, tpacpi_inputdev->mscbit);
3294         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
3295         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
3296         tpacpi_inputdev->keycode = hotkey_keycode_map;
3297         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
3298                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
3299                         set_bit(hotkey_keycode_map[i],
3300                                 tpacpi_inputdev->keybit);
3301                 } else {
3302                         if (i < sizeof(hotkey_reserved_mask)*8)
3303                                 hotkey_reserved_mask |= 1 << i;
3304                 }
3305         }
3306
3307         if (tp_features.hotkey_wlsw) {
3308                 set_bit(EV_SW, tpacpi_inputdev->evbit);
3309                 set_bit(SW_RFKILL_ALL, tpacpi_inputdev->swbit);
3310         }
3311         if (tp_features.hotkey_tablet) {
3312                 set_bit(EV_SW, tpacpi_inputdev->evbit);
3313                 set_bit(SW_TABLET_MODE, tpacpi_inputdev->swbit);
3314         }
3315
3316         /* Do not issue duplicate brightness change events to
3317          * userspace */
3318         if (!tp_features.bright_acpimode)
3319                 /* update bright_acpimode... */
3320                 tpacpi_check_std_acpi_brightness_support();
3321
3322         if (tp_features.bright_acpimode && acpi_video_backlight_support()) {
3323                 printk(TPACPI_INFO
3324                        "This ThinkPad has standard ACPI backlight "
3325                        "brightness control, supported by the ACPI "
3326                        "video driver\n");
3327                 printk(TPACPI_NOTICE
3328                        "Disabling thinkpad-acpi brightness events "
3329                        "by default...\n");
3330
3331                 /* Disable brightness up/down on Lenovo thinkpads when
3332                  * ACPI is handling them, otherwise it is plain impossible
3333                  * for userspace to do something even remotely sane */
3334                 hotkey_reserved_mask |=
3335                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
3336                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
3337                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNHOME);
3338                 hotkey_unmap(TP_ACPI_HOTKEYSCAN_FNEND);
3339         }
3340
3341 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
3342         hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
3343                                 & ~hotkey_all_mask
3344                                 & ~hotkey_reserved_mask;
3345
3346         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3347                     "hotkey source mask 0x%08x, polling freq %u\n",
3348                     hotkey_source_mask, hotkey_poll_freq);
3349 #endif
3350
3351         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3352                         "enabling firmware HKEY event interface...\n");
3353         res = hotkey_status_set(true);
3354         if (res) {
3355                 hotkey_exit();
3356                 return res;
3357         }
3358         res = hotkey_mask_set(((hotkey_all_mask & ~hotkey_reserved_mask)
3359                                | hotkey_driver_mask)
3360                               & ~hotkey_source_mask);
3361         if (res < 0 && res != -ENXIO) {
3362                 hotkey_exit();
3363                 return res;
3364         }
3365         hotkey_user_mask = (hotkey_acpi_mask | hotkey_source_mask)
3366                                 & ~hotkey_reserved_mask;
3367         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3368                 "initial masks: user=0x%08x, fw=0x%08x, poll=0x%08x\n",
3369                 hotkey_user_mask, hotkey_acpi_mask, hotkey_source_mask);
3370
3371         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
3372                         "legacy ibm/hotkey event reporting over procfs %s\n",
3373                         (hotkey_report_mode < 2) ?
3374                                 "enabled" : "disabled");
3375
3376         tpacpi_inputdev->open = &hotkey_inputdev_open;
3377         tpacpi_inputdev->close = &hotkey_inputdev_close;
3378
3379         hotkey_poll_setup_safe(true);
3380         tpacpi_send_radiosw_update();
3381         tpacpi_input_send_tabletsw();
3382
3383         return 0;
3384
3385 err_exit:
3386         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3387         hotkey_dev_attributes = NULL;
3388
3389         return (res < 0)? res : 1;
3390 }
3391
3392 static bool hotkey_notify_hotkey(const u32 hkey,
3393                                  bool *send_acpi_ev,
3394                                  bool *ignore_acpi_ev)
3395 {
3396         /* 0x1000-0x1FFF: key presses */
3397         unsigned int scancode = hkey & 0xfff;
3398         *send_acpi_ev = true;
3399         *ignore_acpi_ev = false;
3400
3401         if (scancode > 0 && scancode < 0x21) {
3402                 scancode--;
3403                 if (!(hotkey_source_mask & (1 << scancode))) {
3404                         tpacpi_input_send_key_masked(scancode);
3405                         *send_acpi_ev = false;
3406                 } else {
3407                         *ignore_acpi_ev = true;
3408                 }
3409                 return true;
3410         }
3411         return false;
3412 }
3413
3414 static bool hotkey_notify_wakeup(const u32 hkey,
3415                                  bool *send_acpi_ev,
3416                                  bool *ignore_acpi_ev)
3417 {
3418         /* 0x2000-0x2FFF: Wakeup reason */
3419         *send_acpi_ev = true;
3420         *ignore_acpi_ev = false;
3421
3422         switch (hkey) {
3423         case 0x2304: /* suspend, undock */
3424         case 0x2404: /* hibernation, undock */
3425                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3426                 *ignore_acpi_ev = true;
3427                 break;
3428
3429         case 0x2305: /* suspend, bay eject */
3430         case 0x2405: /* hibernation, bay eject */
3431                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3432                 *ignore_acpi_ev = true;
3433                 break;
3434
3435         case 0x2313: /* Battery on critical low level (S3) */
3436         case 0x2413: /* Battery on critical low level (S4) */
3437                 printk(TPACPI_ALERT
3438                         "EMERGENCY WAKEUP: battery almost empty\n");
3439                 /* how to auto-heal: */
3440                 /* 2313: woke up from S3, go to S4/S5 */
3441                 /* 2413: woke up from S4, go to S5 */
3442                 break;
3443
3444         default:
3445                 return false;
3446         }
3447
3448         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3449                 printk(TPACPI_INFO
3450                        "woke up due to a hot-unplug "
3451                        "request...\n");
3452                 hotkey_wakeup_reason_notify_change();
3453         }
3454         return true;
3455 }
3456
3457 static bool hotkey_notify_usrevent(const u32 hkey,
3458                                  bool *send_acpi_ev,
3459                                  bool *ignore_acpi_ev)
3460 {
3461         /* 0x5000-0x5FFF: human interface helpers */
3462         *send_acpi_ev = true;
3463         *ignore_acpi_ev = false;
3464
3465         switch (hkey) {
3466         case 0x500b: /* X61t: tablet pen inserted into bay */
3467         case 0x500c: /* X61t: tablet pen removed from bay */
3468                 return true;
3469
3470         case 0x5009: /* X41t-X61t: swivel up (tablet mode) */
3471         case 0x500a: /* X41t-X61t: swivel down (normal mode) */
3472                 tpacpi_input_send_tabletsw();
3473                 hotkey_tablet_mode_notify_change();
3474                 *send_acpi_ev = false;
3475                 return true;
3476
3477         case 0x5001: /* Lid close */
3478         case 0x5002: /* Lid open */
3479         case 0x5010: /* brightness control */
3480                 /* do not propagate these events */
3481                 *ignore_acpi_ev = true;
3482                 return true;
3483
3484         default:
3485                 return false;
3486         }
3487 }
3488
3489 static bool hotkey_notify_thermal(const u32 hkey,
3490                                  bool *send_acpi_ev,
3491                                  bool *ignore_acpi_ev)
3492 {
3493         /* 0x6000-0x6FFF: thermal alarms */
3494         *send_acpi_ev = true;
3495         *ignore_acpi_ev = false;
3496
3497         switch (hkey) {
3498         case 0x6011:
3499                 printk(TPACPI_CRIT
3500                         "THERMAL ALARM: battery is too hot!\n");
3501                 /* recommended action: warn user through gui */
3502                 return true;
3503         case 0x6012:
3504                 printk(TPACPI_ALERT
3505                         "THERMAL EMERGENCY: battery is extremely hot!\n");
3506                 /* recommended action: immediate sleep/hibernate */
3507                 return true;
3508         case 0x6021:
3509                 printk(TPACPI_CRIT
3510                         "THERMAL ALARM: "
3511                         "a sensor reports something is too hot!\n");
3512                 /* recommended action: warn user through gui, that */
3513                 /* some internal component is too hot */
3514                 return true;
3515         case 0x6022:
3516                 printk(TPACPI_ALERT
3517                         "THERMAL EMERGENCY: "
3518                         "a sensor reports something is extremely hot!\n");
3519                 /* recommended action: immediate sleep/hibernate */
3520                 return true;
3521         case 0x6030:
3522                 printk(TPACPI_INFO
3523                         "EC reports that Thermal Table has changed\n");
3524                 /* recommended action: do nothing, we don't have
3525                  * Lenovo ATM information */
3526                 return true;
3527         default:
3528                 printk(TPACPI_ALERT
3529                          "THERMAL ALERT: unknown thermal alarm received\n");
3530                 return false;
3531         }
3532 }
3533
3534 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3535 {
3536         u32 hkey;
3537         bool send_acpi_ev;
3538         bool ignore_acpi_ev;
3539         bool known_ev;
3540
3541         if (event != 0x80) {
3542                 printk(TPACPI_ERR
3543                        "unknown HKEY notification event %d\n", event);
3544                 /* forward it to userspace, maybe it knows how to handle it */
3545                 acpi_bus_generate_netlink_event(
3546                                         ibm->acpi->device->pnp.device_class,
3547                                         dev_name(&ibm->acpi->device->dev),
3548                                         event, 0);
3549                 return;
3550         }
3551
3552         while (1) {
3553                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
3554                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
3555                         return;
3556                 }
3557
3558                 if (hkey == 0) {
3559                         /* queue empty */
3560                         return;
3561                 }
3562
3563                 send_acpi_ev = true;
3564                 ignore_acpi_ev = false;
3565
3566                 switch (hkey >> 12) {
3567                 case 1:
3568                         /* 0x1000-0x1FFF: key presses */
3569                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
3570                                                  &ignore_acpi_ev);
3571                         break;
3572                 case 2:
3573                         /* 0x2000-0x2FFF: Wakeup reason */
3574                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
3575                                                  &ignore_acpi_ev);
3576                         break;
3577                 case 3:
3578                         /* 0x3000-0x3FFF: bay-related wakeups */
3579                         if (hkey == 0x3003) {
3580                                 hotkey_autosleep_ack = 1;
3581                                 printk(TPACPI_INFO
3582                                        "bay ejected\n");
3583                                 hotkey_wakeup_hotunplug_complete_notify_change();
3584                                 known_ev = true;
3585                         } else {
3586                                 known_ev = false;
3587                         }
3588                         break;
3589                 case 4:
3590                         /* 0x4000-0x4FFF: dock-related wakeups */
3591                         if (hkey == 0x4003) {
3592                                 hotkey_autosleep_ack = 1;
3593                                 printk(TPACPI_INFO
3594                                        "undocked\n");
3595                                 hotkey_wakeup_hotunplug_complete_notify_change();
3596                                 known_ev = true;
3597                         } else {
3598                                 known_ev = false;
3599                         }
3600                         break;
3601                 case 5:
3602                         /* 0x5000-0x5FFF: human interface helpers */
3603                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
3604                                                  &ignore_acpi_ev);
3605                         break;
3606                 case 6:
3607                         /* 0x6000-0x6FFF: thermal alarms */
3608                         known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev,
3609                                                  &ignore_acpi_ev);
3610                         break;
3611                 case 7:
3612                         /* 0x7000-0x7FFF: misc */
3613                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
3614                                 tpacpi_send_radiosw_update();
3615                                 send_acpi_ev = 0;
3616                                 known_ev = true;
3617                                 break;
3618                         }
3619                         /* fallthrough to default */
3620                 default:
3621                         known_ev = false;
3622                 }
3623                 if (!known_ev) {
3624                         printk(TPACPI_NOTICE
3625                                "unhandled HKEY event 0x%04x\n", hkey);
3626                         printk(TPACPI_NOTICE
3627                                "please report the conditions when this "
3628                                "event happened to %s\n", TPACPI_MAIL);
3629                 }
3630
3631                 /* Legacy events */
3632                 if (!ignore_acpi_ev &&
3633                     (send_acpi_ev || hotkey_report_mode < 2)) {
3634                         acpi_bus_generate_proc_event(ibm->acpi->device,
3635                                                      event, hkey);
3636                 }
3637
3638                 /* netlink events */
3639                 if (!ignore_acpi_ev && send_acpi_ev) {
3640                         acpi_bus_generate_netlink_event(
3641                                         ibm->acpi->device->pnp.device_class,
3642                                         dev_name(&ibm->acpi->device->dev),
3643                                         event, hkey);
3644                 }
3645         }
3646 }
3647
3648 static void hotkey_suspend(pm_message_t state)
3649 {
3650         /* Do these on suspend, we get the events on early resume! */
3651         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
3652         hotkey_autosleep_ack = 0;
3653 }
3654
3655 static void hotkey_resume(void)
3656 {
3657         tpacpi_disable_brightness_delay();
3658
3659         if (hotkey_status_set(true) < 0 ||
3660             hotkey_mask_set(hotkey_acpi_mask) < 0)
3661                 printk(TPACPI_ERR
3662                        "error while attempting to reset the event "
3663                        "firmware interface\n");
3664
3665         tpacpi_send_radiosw_update();
3666         hotkey_tablet_mode_notify_change();
3667         hotkey_wakeup_reason_notify_change();
3668         hotkey_wakeup_hotunplug_complete_notify_change();
3669         hotkey_poll_setup_safe(false);
3670 }
3671
3672 /* procfs -------------------------------------------------------------- */
3673 static int hotkey_read(char *p)
3674 {
3675         int res, status;
3676         int len = 0;
3677
3678         if (!tp_features.hotkey) {
3679                 len += sprintf(p + len, "status:\t\tnot supported\n");
3680                 return len;
3681         }
3682
3683         if (mutex_lock_killable(&hotkey_mutex))
3684                 return -ERESTARTSYS;
3685         res = hotkey_status_get(&status);
3686         if (!res)
3687                 res = hotkey_mask_get();
3688         mutex_unlock(&hotkey_mutex);
3689         if (res)
3690                 return res;
3691
3692         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
3693         if (hotkey_all_mask) {
3694                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_user_mask);
3695                 len += sprintf(p + len,
3696                                "commands:\tenable, disable, reset, <mask>\n");
3697         } else {
3698                 len += sprintf(p + len, "mask:\t\tnot supported\n");
3699                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
3700         }
3701
3702         return len;
3703 }
3704
3705 static void hotkey_enabledisable_warn(bool enable)
3706 {
3707         tpacpi_log_usertask("procfs hotkey enable/disable");
3708         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
3709                         TPACPI_WARN
3710                         "hotkey enable/disable functionality has been "
3711                         "removed from the driver.  Hotkeys are always "
3712                         "enabled\n"))
3713                 printk(TPACPI_ERR
3714                         "Please remove the hotkey=enable module "
3715                         "parameter, it is deprecated.  Hotkeys are always "
3716                         "enabled\n");
3717 }
3718
3719 static int hotkey_write(char *buf)
3720 {
3721         int res;
3722         u32 mask;
3723         char *cmd;
3724
3725         if (!tp_features.hotkey)
3726                 return -ENODEV;
3727
3728         if (mutex_lock_killable(&hotkey_mutex))
3729                 return -ERESTARTSYS;
3730
3731         mask = hotkey_user_mask;
3732
3733         res = 0;
3734         while ((cmd = next_cmd(&buf))) {
3735                 if (strlencmp(cmd, "enable") == 0) {
3736                         hotkey_enabledisable_warn(1);
3737                 } else if (strlencmp(cmd, "disable") == 0) {
3738                         hotkey_enabledisable_warn(0);
3739                         res = -EPERM;
3740                 } else if (strlencmp(cmd, "reset") == 0) {
3741                         mask = (hotkey_all_mask | hotkey_source_mask)
3742                                 & ~hotkey_reserved_mask;
3743                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
3744                         /* mask set */
3745                 } else if (sscanf(cmd, "%x", &mask) == 1) {
3746                         /* mask set */
3747                 } else {
3748                         res = -EINVAL;
3749                         goto errexit;
3750                 }
3751         }
3752
3753         if (!res) {
3754                 tpacpi_disclose_usertask("procfs hotkey",
3755                         "set mask to 0x%08x\n", mask);
3756                 res = hotkey_user_mask_set(mask);
3757         }
3758
3759 errexit:
3760         mutex_unlock(&hotkey_mutex);
3761         return res;
3762 }
3763
3764 static const struct acpi_device_id ibm_htk_device_ids[] = {
3765         {TPACPI_ACPI_HKEY_HID, 0},
3766         {"", 0},
3767 };
3768
3769 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
3770         .hid = ibm_htk_device_ids,
3771         .notify = hotkey_notify,
3772         .handle = &hkey_handle,
3773         .type = ACPI_DEVICE_NOTIFY,
3774 };
3775
3776 static struct ibm_struct hotkey_driver_data = {
3777         .name = "hotkey",
3778         .read = hotkey_read,
3779         .write = hotkey_write,
3780         .exit = hotkey_exit,
3781         .resume = hotkey_resume,
3782         .suspend = hotkey_suspend,
3783         .acpi = &ibm_hotkey_acpidriver,
3784 };
3785
3786 /*************************************************************************
3787  * Bluetooth subdriver
3788  */
3789
3790 enum {
3791         /* ACPI GBDC/SBDC bits */
3792         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
3793         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
3794         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
3795                                                    off / last state */
3796 };
3797
3798 enum {
3799         /* ACPI \BLTH commands */
3800         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
3801         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
3802         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
3803         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
3804         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
3805 };
3806
3807 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
3808
3809 static void bluetooth_suspend(pm_message_t state)
3810 {
3811         /* Try to make sure radio will resume powered off */
3812         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3813                    TP_ACPI_BLTH_PWR_OFF_ON_RESUME))
3814                 vdbg_printk(TPACPI_DBG_RFKILL,
3815                         "bluetooth power down on resume request failed\n");
3816 }
3817
3818 static int bluetooth_get_status(void)
3819 {
3820         int status;
3821
3822 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3823         if (dbg_bluetoothemul)
3824                 return (tpacpi_bluetooth_emulstate) ?
3825                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3826 #endif
3827
3828         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
3829                 return -EIO;
3830
3831         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
3832                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3833 }
3834
3835 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
3836 {
3837         int status;
3838
3839         vdbg_printk(TPACPI_DBG_RFKILL,
3840                 "will attempt to %s bluetooth\n",
3841                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3842
3843 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3844         if (dbg_bluetoothemul) {
3845                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
3846                 return 0;
3847         }
3848 #endif
3849
3850         /* We make sure to keep TP_ACPI_BLUETOOTH_RESUMECTRL off */
3851         if (state == TPACPI_RFK_RADIO_ON)
3852                 status = TP_ACPI_BLUETOOTH_RADIOSSW;
3853         else
3854                 status = 0;
3855
3856         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
3857                 return -EIO;
3858
3859         return 0;
3860 }
3861
3862 /* sysfs bluetooth enable ---------------------------------------------- */
3863 static ssize_t bluetooth_enable_show(struct device *dev,
3864                            struct device_attribute *attr,
3865                            char *buf)
3866 {
3867         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
3868                         attr, buf);
3869 }
3870
3871 static ssize_t bluetooth_enable_store(struct device *dev,
3872                             struct device_attribute *attr,
3873                             const char *buf, size_t count)
3874 {
3875         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
3876                                 attr, buf, count);
3877 }
3878
3879 static struct device_attribute dev_attr_bluetooth_enable =
3880         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
3881                 bluetooth_enable_show, bluetooth_enable_store);
3882
3883 /* --------------------------------------------------------------------- */
3884
3885 static struct attribute *bluetooth_attributes[] = {
3886         &dev_attr_bluetooth_enable.attr,
3887         NULL
3888 };
3889
3890 static const struct attribute_group bluetooth_attr_group = {
3891         .attrs = bluetooth_attributes,
3892 };
3893
3894 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
3895         .get_status = bluetooth_get_status,
3896         .set_status = bluetooth_set_status,
3897 };
3898
3899 static void bluetooth_shutdown(void)
3900 {
3901         /* Order firmware to save current state to NVRAM */
3902         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3903                         TP_ACPI_BLTH_SAVE_STATE))
3904                 printk(TPACPI_NOTICE
3905                         "failed to save bluetooth state to NVRAM\n");
3906         else
3907                 vdbg_printk(TPACPI_DBG_RFKILL,
3908                         "bluestooth state saved to NVRAM\n");
3909 }
3910
3911 static void bluetooth_exit(void)
3912 {
3913         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3914                         &bluetooth_attr_group);
3915
3916         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3917
3918         bluetooth_shutdown();
3919 }
3920
3921 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3922 {
3923         int res;
3924         int status = 0;
3925
3926         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3927                         "initializing bluetooth subdriver\n");
3928
3929         TPACPI_ACPIHANDLE_INIT(hkey);
3930
3931         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3932            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
3933         tp_features.bluetooth = hkey_handle &&
3934             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
3935
3936         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3937                 "bluetooth is %s, status 0x%02x\n",
3938                 str_supported(tp_features.bluetooth),
3939                 status);
3940
3941 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3942         if (dbg_bluetoothemul) {
3943                 tp_features.bluetooth = 1;
3944                 printk(TPACPI_INFO
3945                         "bluetooth switch emulation enabled\n");
3946         } else
3947 #endif
3948         if (tp_features.bluetooth &&
3949             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
3950                 /* no bluetooth hardware present in system */
3951                 tp_features.bluetooth = 0;
3952                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3953                            "bluetooth hardware not installed\n");
3954         }
3955
3956         if (!tp_features.bluetooth)
3957                 return 1;
3958
3959         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
3960                                 &bluetooth_tprfk_ops,
3961                                 RFKILL_TYPE_BLUETOOTH,
3962                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
3963                                 true);
3964         if (res)
3965                 return res;
3966
3967         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3968                                 &bluetooth_attr_group);
3969         if (res) {
3970                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3971                 return res;
3972         }
3973
3974         return 0;
3975 }
3976
3977 /* procfs -------------------------------------------------------------- */
3978 static int bluetooth_read(char *p)
3979 {
3980         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, p);
3981 }
3982
3983 static int bluetooth_write(char *buf)
3984 {
3985         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
3986 }
3987
3988 static struct ibm_struct bluetooth_driver_data = {
3989         .name = "bluetooth",
3990         .read = bluetooth_read,
3991         .write = bluetooth_write,
3992         .exit = bluetooth_exit,
3993         .suspend = bluetooth_suspend,
3994         .shutdown = bluetooth_shutdown,
3995 };
3996
3997 /*************************************************************************
3998  * Wan subdriver
3999  */
4000
4001 enum {
4002         /* ACPI GWAN/SWAN bits */
4003         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
4004         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
4005         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
4006                                                    off / last state */
4007 };
4008
4009 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
4010
4011 static void wan_suspend(pm_message_t state)
4012 {
4013         /* Try to make sure radio will resume powered off */
4014         if (!acpi_evalf(NULL, NULL, "\\WGSV", "qvd",
4015                    TP_ACPI_WGSV_PWR_OFF_ON_RESUME))
4016                 vdbg_printk(TPACPI_DBG_RFKILL,
4017                         "WWAN power down on resume request failed\n");
4018 }
4019
4020 static int wan_get_status(void)
4021 {
4022         int status;
4023
4024 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4025         if (dbg_wwanemul)
4026                 return (tpacpi_wwan_emulstate) ?
4027                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4028 #endif
4029
4030         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
4031                 return -EIO;
4032
4033         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
4034                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4035 }
4036
4037 static int wan_set_status(enum tpacpi_rfkill_state state)
4038 {
4039         int status;
4040
4041         vdbg_printk(TPACPI_DBG_RFKILL,
4042                 "will attempt to %s wwan\n",
4043                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4044
4045 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4046         if (dbg_wwanemul) {
4047                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
4048                 return 0;
4049         }
4050 #endif
4051
4052         /* We make sure to keep TP_ACPI_WANCARD_RESUMECTRL off */
4053         if (state == TPACPI_RFK_RADIO_ON)
4054                 status = TP_ACPI_WANCARD_RADIOSSW;
4055         else
4056                 status = 0;
4057
4058         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
4059                 return -EIO;
4060
4061         return 0;
4062 }
4063
4064 /* sysfs wan enable ---------------------------------------------------- */
4065 static ssize_t wan_enable_show(struct device *dev,
4066                            struct device_attribute *attr,
4067                            char *buf)
4068 {
4069         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
4070                         attr, buf);
4071 }
4072
4073 static ssize_t wan_enable_store(struct device *dev,
4074                             struct device_attribute *attr,
4075                             const char *buf, size_t count)
4076 {
4077         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
4078                         attr, buf, count);
4079 }
4080
4081 static struct device_attribute dev_attr_wan_enable =
4082         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
4083                 wan_enable_show, wan_enable_store);
4084
4085 /* --------------------------------------------------------------------- */
4086
4087 static struct attribute *wan_attributes[] = {
4088         &dev_attr_wan_enable.attr,
4089         NULL
4090 };
4091
4092 static const struct attribute_group wan_attr_group = {
4093         .attrs = wan_attributes,
4094 };
4095
4096 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
4097         .get_status = wan_get_status,
4098         .set_status = wan_set_status,
4099 };
4100
4101 static void wan_shutdown(void)
4102 {
4103         /* Order firmware to save current state to NVRAM */
4104         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
4105                         TP_ACPI_WGSV_SAVE_STATE))
4106                 printk(TPACPI_NOTICE
4107                         "failed to save WWAN state to NVRAM\n");
4108         else
4109                 vdbg_printk(TPACPI_DBG_RFKILL,
4110                         "WWAN state saved to NVRAM\n");
4111 }
4112
4113 static void wan_exit(void)
4114 {
4115         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
4116                 &wan_attr_group);
4117
4118         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4119
4120         wan_shutdown();
4121 }
4122
4123 static int __init wan_init(struct ibm_init_struct *iibm)
4124 {
4125         int res;
4126         int status = 0;
4127
4128         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4129                         "initializing wan subdriver\n");
4130
4131         TPACPI_ACPIHANDLE_INIT(hkey);
4132
4133         tp_features.wan = hkey_handle &&
4134             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
4135
4136         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4137                 "wan is %s, status 0x%02x\n",
4138                 str_supported(tp_features.wan),
4139                 status);
4140
4141 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4142         if (dbg_wwanemul) {
4143                 tp_features.wan = 1;
4144                 printk(TPACPI_INFO
4145                         "wwan switch emulation enabled\n");
4146         } else
4147 #endif
4148         if (tp_features.wan &&
4149             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
4150                 /* no wan hardware present in system */
4151                 tp_features.wan = 0;
4152                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4153                            "wan hardware not installed\n");
4154         }
4155
4156         if (!tp_features.wan)
4157                 return 1;
4158
4159         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
4160                                 &wan_tprfk_ops,
4161                                 RFKILL_TYPE_WWAN,
4162                                 TPACPI_RFK_WWAN_SW_NAME,
4163                                 true);
4164         if (res)
4165                 return res;
4166
4167         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
4168                                 &wan_attr_group);
4169
4170         if (res) {
4171                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
4172                 return res;
4173         }
4174
4175         return 0;
4176 }
4177
4178 /* procfs -------------------------------------------------------------- */
4179 static int wan_read(char *p)
4180 {
4181         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, p);
4182 }
4183
4184 static int wan_write(char *buf)
4185 {
4186         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
4187 }
4188
4189 static struct ibm_struct wan_driver_data = {
4190         .name = "wan",
4191         .read = wan_read,
4192         .write = wan_write,
4193         .exit = wan_exit,
4194         .suspend = wan_suspend,
4195         .shutdown = wan_shutdown,
4196 };
4197
4198 /*************************************************************************
4199  * UWB subdriver
4200  */
4201
4202 enum {
4203         /* ACPI GUWB/SUWB bits */
4204         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
4205         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
4206 };
4207
4208 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
4209
4210 static int uwb_get_status(void)
4211 {
4212         int status;
4213
4214 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4215         if (dbg_uwbemul)
4216                 return (tpacpi_uwb_emulstate) ?
4217                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4218 #endif
4219
4220         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
4221                 return -EIO;
4222
4223         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
4224                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
4225 }
4226
4227 static int uwb_set_status(enum tpacpi_rfkill_state state)
4228 {
4229         int status;
4230
4231         vdbg_printk(TPACPI_DBG_RFKILL,
4232                 "will attempt to %s UWB\n",
4233                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
4234
4235 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4236         if (dbg_uwbemul) {
4237                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
4238                 return 0;
4239         }
4240 #endif
4241
4242         if (state == TPACPI_RFK_RADIO_ON)
4243                 status = TP_ACPI_UWB_RADIOSSW;
4244         else
4245                 status = 0;
4246
4247         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
4248                 return -EIO;
4249
4250         return 0;
4251 }
4252
4253 /* --------------------------------------------------------------------- */
4254
4255 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
4256         .get_status = uwb_get_status,
4257         .set_status = uwb_set_status,
4258 };
4259
4260 static void uwb_exit(void)
4261 {
4262         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
4263 }
4264
4265 static int __init uwb_init(struct ibm_init_struct *iibm)
4266 {
4267         int res;
4268         int status = 0;
4269
4270         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4271                         "initializing uwb subdriver\n");
4272
4273         TPACPI_ACPIHANDLE_INIT(hkey);
4274
4275         tp_features.uwb = hkey_handle &&
4276             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
4277
4278         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
4279                 "uwb is %s, status 0x%02x\n",
4280                 str_supported(tp_features.uwb),
4281                 status);
4282
4283 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
4284         if (dbg_uwbemul) {
4285                 tp_features.uwb = 1;
4286                 printk(TPACPI_INFO
4287                         "uwb switch emulation enabled\n");
4288         } else
4289 #endif
4290         if (tp_features.uwb &&
4291             !(status & TP_ACPI_UWB_HWPRESENT)) {
4292                 /* no uwb hardware present in system */
4293                 tp_features.uwb = 0;
4294                 dbg_printk(TPACPI_DBG_INIT,
4295                            "uwb hardware not installed\n");
4296         }
4297
4298         if (!tp_features.uwb)
4299                 return 1;
4300
4301         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
4302                                 &uwb_tprfk_ops,
4303                                 RFKILL_TYPE_UWB,
4304                                 TPACPI_RFK_UWB_SW_NAME,
4305                                 false);
4306         return res;
4307 }
4308
4309 static struct ibm_struct uwb_driver_data = {
4310         .name = "uwb",
4311         .exit = uwb_exit,
4312         .flags.experimental = 1,
4313 };
4314
4315 /*************************************************************************
4316  * Video subdriver
4317  */
4318
4319 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
4320
4321 enum video_access_mode {
4322         TPACPI_VIDEO_NONE = 0,
4323         TPACPI_VIDEO_570,       /* 570 */
4324         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
4325         TPACPI_VIDEO_NEW,       /* all others */
4326 };
4327
4328 enum {  /* video status flags, based on VIDEO_570 */
4329         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
4330         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
4331         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
4332 };
4333
4334 enum {  /* TPACPI_VIDEO_570 constants */
4335         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
4336         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
4337                                                  * video_status_flags */
4338         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
4339         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
4340 };
4341
4342 static enum video_access_mode video_supported;
4343 static int video_orig_autosw;
4344
4345 static int video_autosw_get(void);
4346 static int video_autosw_set(int enable);
4347
4348 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
4349
4350 static int __init video_init(struct ibm_init_struct *iibm)
4351 {
4352         int ivga;
4353
4354         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
4355
4356         TPACPI_ACPIHANDLE_INIT(vid);
4357         TPACPI_ACPIHANDLE_INIT(vid2);
4358
4359         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
4360                 /* G41, assume IVGA doesn't change */
4361                 vid_handle = vid2_handle;
4362
4363         if (!vid_handle)
4364                 /* video switching not supported on R30, R31 */
4365                 video_supported = TPACPI_VIDEO_NONE;
4366         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
4367                 /* 570 */
4368                 video_supported = TPACPI_VIDEO_570;
4369         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
4370                 /* 600e/x, 770e, 770x */
4371                 video_supported = TPACPI_VIDEO_770;
4372         else
4373                 /* all others */
4374                 video_supported = TPACPI_VIDEO_NEW;
4375
4376         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
4377                 str_supported(video_supported != TPACPI_VIDEO_NONE),
4378                 video_supported);
4379
4380         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
4381 }
4382
4383 static void video_exit(void)
4384 {
4385         dbg_printk(TPACPI_DBG_EXIT,
4386                    "restoring original video autoswitch mode\n");
4387         if (video_autosw_set(video_orig_autosw))
4388                 printk(TPACPI_ERR "error while trying to restore original "
4389                         "video autoswitch mode\n");
4390 }
4391
4392 static int video_outputsw_get(void)
4393 {
4394         int status = 0;
4395         int i;
4396
4397         switch (video_supported) {
4398         case TPACPI_VIDEO_570:
4399                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4400                                  TP_ACPI_VIDEO_570_PHSCMD))
4401                         return -EIO;
4402                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4403                 break;
4404         case TPACPI_VIDEO_770:
4405                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4406                         return -EIO;
4407                 if (i)
4408                         status |= TP_ACPI_VIDEO_S_LCD;
4409                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4410                         return -EIO;
4411                 if (i)
4412                         status |= TP_ACPI_VIDEO_S_CRT;
4413                 break;
4414         case TPACPI_VIDEO_NEW:
4415                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4416                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4417                         return -EIO;
4418                 if (i)
4419                         status |= TP_ACPI_VIDEO_S_CRT;
4420
4421                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4422                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4423                         return -EIO;
4424                 if (i)
4425                         status |= TP_ACPI_VIDEO_S_LCD;
4426                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4427                         return -EIO;
4428                 if (i)
4429                         status |= TP_ACPI_VIDEO_S_DVI;
4430                 break;
4431         default:
4432                 return -ENOSYS;
4433         }
4434
4435         return status;
4436 }
4437
4438 static int video_outputsw_set(int status)
4439 {
4440         int autosw;
4441         int res = 0;
4442
4443         switch (video_supported) {
4444         case TPACPI_VIDEO_570:
4445                 res = acpi_evalf(NULL, NULL,
4446                                  "\\_SB.PHS2", "vdd",
4447                                  TP_ACPI_VIDEO_570_PHS2CMD,
4448                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4449                 break;
4450         case TPACPI_VIDEO_770:
4451                 autosw = video_autosw_get();
4452                 if (autosw < 0)
4453                         return autosw;
4454
4455                 res = video_autosw_set(1);
4456                 if (res)
4457                         return res;
4458                 res = acpi_evalf(vid_handle, NULL,
4459                                  "ASWT", "vdd", status * 0x100, 0);
4460                 if (!autosw && video_autosw_set(autosw)) {
4461                         printk(TPACPI_ERR
4462                                "video auto-switch left enabled due to error\n");
4463                         return -EIO;
4464                 }
4465                 break;
4466         case TPACPI_VIDEO_NEW:
4467                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4468                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4469                 break;
4470         default:
4471                 return -ENOSYS;
4472         }
4473
4474         return (res)? 0 : -EIO;
4475 }
4476
4477 static int video_autosw_get(void)
4478 {
4479         int autosw = 0;
4480
4481         switch (video_supported) {
4482         case TPACPI_VIDEO_570:
4483                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4484                         return -EIO;
4485                 break;
4486         case TPACPI_VIDEO_770:
4487         case TPACPI_VIDEO_NEW:
4488                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4489                         return -EIO;
4490                 break;
4491         default:
4492                 return -ENOSYS;
4493         }
4494
4495         return autosw & 1;
4496 }
4497
4498 static int video_autosw_set(int enable)
4499 {
4500         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
4501                 return -EIO;
4502         return 0;
4503 }
4504
4505 static int video_outputsw_cycle(void)
4506 {
4507         int autosw = video_autosw_get();
4508         int res;
4509
4510         if (autosw < 0)
4511                 return autosw;
4512
4513         switch (video_supported) {
4514         case TPACPI_VIDEO_570:
4515                 res = video_autosw_set(1);
4516                 if (res)
4517                         return res;
4518                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4519                 break;
4520         case TPACPI_VIDEO_770:
4521         case TPACPI_VIDEO_NEW:
4522                 res = video_autosw_set(1);
4523                 if (res)
4524                         return res;
4525                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4526                 break;
4527         default:
4528                 return -ENOSYS;
4529         }
4530         if (!autosw && video_autosw_set(autosw)) {
4531                 printk(TPACPI_ERR
4532                        "video auto-switch left enabled due to error\n");
4533                 return -EIO;
4534         }
4535
4536         return (res)? 0 : -EIO;
4537 }
4538
4539 static int video_expand_toggle(void)
4540 {
4541         switch (video_supported) {
4542         case TPACPI_VIDEO_570:
4543                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
4544                         0 : -EIO;
4545         case TPACPI_VIDEO_770:
4546                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
4547                         0 : -EIO;
4548         case TPACPI_VIDEO_NEW:
4549                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
4550                         0 : -EIO;
4551         default:
4552                 return -ENOSYS;
4553         }
4554         /* not reached */
4555 }
4556
4557 static int video_read(char *p)
4558 {
4559         int status, autosw;
4560         int len = 0;
4561
4562         if (video_supported == TPACPI_VIDEO_NONE) {
4563                 len += sprintf(p + len, "status:\t\tnot supported\n");
4564                 return len;
4565         }
4566
4567         status = video_outputsw_get();
4568         if (status < 0)
4569                 return status;
4570
4571         autosw = video_autosw_get();
4572         if (autosw < 0)
4573                 return autosw;
4574
4575         len += sprintf(p + len, "status:\t\tsupported\n");
4576         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
4577         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
4578         if (video_supported == TPACPI_VIDEO_NEW)
4579                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
4580         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
4581         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
4582         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
4583         if (video_supported == TPACPI_VIDEO_NEW)
4584                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
4585         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
4586         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
4587
4588         return len;
4589 }
4590
4591 static int video_write(char *buf)
4592 {
4593         char *cmd;
4594         int enable, disable, status;
4595         int res;
4596
4597         if (video_supported == TPACPI_VIDEO_NONE)
4598                 return -ENODEV;
4599
4600         enable = 0;
4601         disable = 0;
4602
4603         while ((cmd = next_cmd(&buf))) {
4604                 if (strlencmp(cmd, "lcd_enable") == 0) {
4605                         enable |= TP_ACPI_VIDEO_S_LCD;
4606                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
4607                         disable |= TP_ACPI_VIDEO_S_LCD;
4608                 } else if (strlencmp(cmd, "crt_enable") == 0) {
4609                         enable |= TP_ACPI_VIDEO_S_CRT;
4610                 } else if (strlencmp(cmd, "crt_disable") == 0) {
4611                         disable |= TP_ACPI_VIDEO_S_CRT;
4612                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4613                            strlencmp(cmd, "dvi_enable") == 0) {
4614                         enable |= TP_ACPI_VIDEO_S_DVI;
4615                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4616                            strlencmp(cmd, "dvi_disable") == 0) {
4617                         disable |= TP_ACPI_VIDEO_S_DVI;
4618                 } else if (strlencmp(cmd, "auto_enable") == 0) {
4619                         res = video_autosw_set(1);
4620                         if (res)
4621                                 return res;
4622                 } else if (strlencmp(cmd, "auto_disable") == 0) {
4623                         res = video_autosw_set(0);
4624                         if (res)
4625                                 return res;
4626                 } else if (strlencmp(cmd, "video_switch") == 0) {
4627                         res = video_outputsw_cycle();
4628                         if (res)
4629                                 return res;
4630                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
4631                         res = video_expand_toggle();
4632                         if (res)
4633                                 return res;
4634                 } else
4635                         return -EINVAL;
4636         }
4637
4638         if (enable || disable) {
4639                 status = video_outputsw_get();
4640                 if (status < 0)
4641                         return status;
4642                 res = video_outputsw_set((status & ~disable) | enable);
4643                 if (res)
4644                         return res;
4645         }
4646
4647         return 0;
4648 }
4649
4650 static struct ibm_struct video_driver_data = {
4651         .name = "video",
4652         .read = video_read,
4653         .write = video_write,
4654         .exit = video_exit,
4655 };
4656
4657 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
4658
4659 /*************************************************************************
4660  * Light (thinklight) subdriver
4661  */
4662
4663 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
4664 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
4665
4666 static int light_get_status(void)
4667 {
4668         int status = 0;
4669
4670         if (tp_features.light_status) {
4671                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
4672                         return -EIO;
4673                 return (!!status);
4674         }
4675
4676         return -ENXIO;
4677 }
4678
4679 static int light_set_status(int status)
4680 {
4681         int rc;
4682
4683         if (tp_features.light) {
4684                 if (cmos_handle) {
4685                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
4686                                         (status)?
4687                                                 TP_CMOS_THINKLIGHT_ON :
4688                                                 TP_CMOS_THINKLIGHT_OFF);
4689                 } else {
4690                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
4691                                         (status)? 1 : 0);
4692                 }
4693                 return (rc)? 0 : -EIO;
4694         }
4695
4696         return -ENXIO;
4697 }
4698
4699 static void light_set_status_worker(struct work_struct *work)
4700 {
4701         struct tpacpi_led_classdev *data =
4702                         container_of(work, struct tpacpi_led_classdev, work);
4703
4704         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4705                 light_set_status((data->new_state != TPACPI_LED_OFF));
4706 }
4707
4708 static void light_sysfs_set(struct led_classdev *led_cdev,
4709                         enum led_brightness brightness)
4710 {
4711         struct tpacpi_led_classdev *data =
4712                 container_of(led_cdev,
4713                              struct tpacpi_led_classdev,
4714                              led_classdev);
4715         data->new_state = (brightness != LED_OFF) ?
4716                                 TPACPI_LED_ON : TPACPI_LED_OFF;
4717         queue_work(tpacpi_wq, &data->work);
4718 }
4719
4720 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
4721 {
4722         return (light_get_status() == 1)? LED_FULL : LED_OFF;
4723 }
4724
4725 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
4726         .led_classdev = {
4727                 .name           = "tpacpi::thinklight",
4728                 .brightness_set = &light_sysfs_set,
4729                 .brightness_get = &light_sysfs_get,
4730         }
4731 };
4732
4733 static int __init light_init(struct ibm_init_struct *iibm)
4734 {
4735         int rc;
4736
4737         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
4738
4739         TPACPI_ACPIHANDLE_INIT(ledb);
4740         TPACPI_ACPIHANDLE_INIT(lght);
4741         TPACPI_ACPIHANDLE_INIT(cmos);
4742         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
4743
4744         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
4745         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
4746
4747         if (tp_features.light)
4748                 /* light status not supported on
4749                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
4750                 tp_features.light_status =
4751                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
4752
4753         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4754                 str_supported(tp_features.light),
4755                 str_supported(tp_features.light_status));
4756
4757         if (!tp_features.light)
4758                 return 1;
4759
4760         rc = led_classdev_register(&tpacpi_pdev->dev,
4761                                    &tpacpi_led_thinklight.led_classdev);
4762
4763         if (rc < 0) {
4764                 tp_features.light = 0;
4765                 tp_features.light_status = 0;
4766         } else  {
4767                 rc = 0;
4768         }
4769
4770         return rc;
4771 }
4772
4773 static void light_exit(void)
4774 {
4775         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4776         if (work_pending(&tpacpi_led_thinklight.work))
4777                 flush_workqueue(tpacpi_wq);
4778 }
4779
4780 static int light_read(char *p)
4781 {
4782         int len = 0;
4783         int status;
4784
4785         if (!tp_features.light) {
4786                 len += sprintf(p + len, "status:\t\tnot supported\n");
4787         } else if (!tp_features.light_status) {
4788                 len += sprintf(p + len, "status:\t\tunknown\n");
4789                 len += sprintf(p + len, "commands:\ton, off\n");
4790         } else {
4791                 status = light_get_status();
4792                 if (status < 0)
4793                         return status;
4794                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
4795                 len += sprintf(p + len, "commands:\ton, off\n");
4796         }
4797
4798         return len;
4799 }
4800
4801 static int light_write(char *buf)
4802 {
4803         char *cmd;
4804         int newstatus = 0;
4805
4806         if (!tp_features.light)
4807                 return -ENODEV;
4808
4809         while ((cmd = next_cmd(&buf))) {
4810                 if (strlencmp(cmd, "on") == 0) {
4811                         newstatus = 1;
4812                 } else if (strlencmp(cmd, "off") == 0) {
4813                         newstatus = 0;
4814                 } else
4815                         return -EINVAL;
4816         }
4817
4818         return light_set_status(newstatus);
4819 }
4820
4821 static struct ibm_struct light_driver_data = {
4822         .name = "light",
4823         .read = light_read,
4824         .write = light_write,
4825         .exit = light_exit,
4826 };
4827
4828 /*************************************************************************
4829  * CMOS subdriver
4830  */
4831
4832 /* sysfs cmos_command -------------------------------------------------- */
4833 static ssize_t cmos_command_store(struct device *dev,
4834                             struct device_attribute *attr,
4835                             const char *buf, size_t count)
4836 {
4837         unsigned long cmos_cmd;
4838         int res;
4839
4840         if (parse_strtoul(buf, 21, &cmos_cmd))
4841                 return -EINVAL;
4842
4843         res = issue_thinkpad_cmos_command(cmos_cmd);
4844         return (res)? res : count;
4845 }
4846
4847 static struct device_attribute dev_attr_cmos_command =
4848         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4849
4850 /* --------------------------------------------------------------------- */
4851
4852 static int __init cmos_init(struct ibm_init_struct *iibm)
4853 {
4854         int res;
4855
4856         vdbg_printk(TPACPI_DBG_INIT,
4857                 "initializing cmos commands subdriver\n");
4858
4859         TPACPI_ACPIHANDLE_INIT(cmos);
4860
4861         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4862                 str_supported(cmos_handle != NULL));
4863
4864         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4865         if (res)
4866                 return res;
4867
4868         return (cmos_handle)? 0 : 1;
4869 }
4870
4871 static void cmos_exit(void)
4872 {
4873         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4874 }
4875
4876 static int cmos_read(char *p)
4877 {
4878         int len = 0;
4879
4880         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4881            R30, R31, T20-22, X20-21 */
4882         if (!cmos_handle)
4883                 len += sprintf(p + len, "status:\t\tnot supported\n");
4884         else {
4885                 len += sprintf(p + len, "status:\t\tsupported\n");
4886                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
4887         }
4888
4889         return len;
4890 }
4891
4892 static int cmos_write(char *buf)
4893 {
4894         char *cmd;
4895         int cmos_cmd, res;
4896
4897         while ((cmd = next_cmd(&buf))) {
4898                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4899                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4900                         /* cmos_cmd set */
4901                 } else
4902                         return -EINVAL;
4903
4904                 res = issue_thinkpad_cmos_command(cmos_cmd);
4905                 if (res)
4906                         return res;
4907         }
4908
4909         return 0;
4910 }
4911
4912 static struct ibm_struct cmos_driver_data = {
4913         .name = "cmos",
4914         .read = cmos_read,
4915         .write = cmos_write,
4916         .exit = cmos_exit,
4917 };
4918
4919 /*************************************************************************
4920  * LED subdriver
4921  */
4922
4923 enum led_access_mode {
4924         TPACPI_LED_NONE = 0,
4925         TPACPI_LED_570, /* 570 */
4926         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4927         TPACPI_LED_NEW, /* all others */
4928 };
4929
4930 enum {  /* For TPACPI_LED_OLD */
4931         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4932         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4933         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4934 };
4935
4936 static enum led_access_mode led_supported;
4937
4938 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4939            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4940                                 /* T20-22, X20-21 */
4941            "LED",               /* all others */
4942            );                   /* R30, R31 */
4943
4944 #define TPACPI_LED_NUMLEDS 16
4945 static struct tpacpi_led_classdev *tpacpi_leds;
4946 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4947 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4948         /* there's a limit of 19 chars + NULL before 2.6.26 */
4949         "tpacpi::power",
4950         "tpacpi:orange:batt",
4951         "tpacpi:green:batt",
4952         "tpacpi::dock_active",
4953         "tpacpi::bay_active",
4954         "tpacpi::dock_batt",
4955         "tpacpi::unknown_led",
4956         "tpacpi::standby",
4957         "tpacpi::dock_status1",
4958         "tpacpi::dock_status2",
4959         "tpacpi::unknown_led2",
4960         "tpacpi::unknown_led3",
4961         "tpacpi::thinkvantage",
4962 };
4963 #define TPACPI_SAFE_LEDS        0x1081U
4964
4965 static inline bool tpacpi_is_led_restricted(const unsigned int led)
4966 {
4967 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
4968         return false;
4969 #else
4970         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
4971 #endif
4972 }
4973
4974 static int led_get_status(const unsigned int led)
4975 {
4976         int status;
4977         enum led_status_t led_s;
4978
4979         switch (led_supported) {
4980         case TPACPI_LED_570:
4981                 if (!acpi_evalf(ec_handle,
4982                                 &status, "GLED", "dd", 1 << led))
4983                         return -EIO;
4984                 led_s = (status == 0)?
4985                                 TPACPI_LED_OFF :
4986                                 ((status == 1)?
4987                                         TPACPI_LED_ON :
4988                                         TPACPI_LED_BLINK);
4989                 tpacpi_led_state_cache[led] = led_s;
4990                 return led_s;
4991         default:
4992                 return -ENXIO;
4993         }
4994
4995         /* not reached */
4996 }
4997
4998 static int led_set_status(const unsigned int led,
4999                           const enum led_status_t ledstatus)
5000 {
5001         /* off, on, blink. Index is led_status_t */
5002         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
5003         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
5004
5005         int rc = 0;
5006
5007         switch (led_supported) {
5008         case TPACPI_LED_570:
5009                 /* 570 */
5010                 if (unlikely(led > 7))
5011                         return -EINVAL;
5012                 if (unlikely(tpacpi_is_led_restricted(led)))
5013                         return -EPERM;
5014                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5015                                 (1 << led), led_sled_arg1[ledstatus]))
5016                         rc = -EIO;
5017                 break;
5018         case TPACPI_LED_OLD:
5019                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
5020                 if (unlikely(led > 7))
5021                         return -EINVAL;
5022                 if (unlikely(tpacpi_is_led_restricted(led)))
5023                         return -EPERM;
5024                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
5025                 if (rc >= 0)
5026                         rc = ec_write(TPACPI_LED_EC_HLBL,
5027                                       (ledstatus == TPACPI_LED_BLINK) << led);
5028                 if (rc >= 0)
5029                         rc = ec_write(TPACPI_LED_EC_HLCL,
5030                                       (ledstatus != TPACPI_LED_OFF) << led);
5031                 break;
5032         case TPACPI_LED_NEW:
5033                 /* all others */
5034                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
5035                         return -EINVAL;
5036                 if (unlikely(tpacpi_is_led_restricted(led)))
5037                         return -EPERM;
5038                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
5039                                 led, led_led_arg1[ledstatus]))
5040                         rc = -EIO;
5041                 break;
5042         default:
5043                 rc = -ENXIO;
5044         }
5045
5046         if (!rc)
5047                 tpacpi_led_state_cache[led] = ledstatus;
5048
5049         return rc;
5050 }
5051
5052 static void led_set_status_worker(struct work_struct *work)
5053 {
5054         struct tpacpi_led_classdev *data =
5055                 container_of(work, struct tpacpi_led_classdev, work);
5056
5057         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
5058                 led_set_status(data->led, data->new_state);
5059 }
5060
5061 static void led_sysfs_set(struct led_classdev *led_cdev,
5062                         enum led_brightness brightness)
5063 {
5064         struct tpacpi_led_classdev *data = container_of(led_cdev,
5065                              struct tpacpi_led_classdev, led_classdev);
5066
5067         if (brightness == LED_OFF)
5068                 data->new_state = TPACPI_LED_OFF;
5069         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
5070                 data->new_state = TPACPI_LED_ON;
5071         else
5072                 data->new_state = TPACPI_LED_BLINK;
5073
5074         queue_work(tpacpi_wq, &data->work);
5075 }
5076
5077 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
5078                         unsigned long *delay_on, unsigned long *delay_off)
5079 {
5080         struct tpacpi_led_classdev *data = container_of(led_cdev,
5081                              struct tpacpi_led_classdev, led_classdev);
5082
5083         /* Can we choose the flash rate? */
5084         if (*delay_on == 0 && *delay_off == 0) {
5085                 /* yes. set them to the hardware blink rate (1 Hz) */
5086                 *delay_on = 500; /* ms */
5087                 *delay_off = 500; /* ms */
5088         } else if ((*delay_on != 500) || (*delay_off != 500))
5089                 return -EINVAL;
5090
5091         data->new_state = TPACPI_LED_BLINK;
5092         queue_work(tpacpi_wq, &data->work);
5093
5094         return 0;
5095 }
5096
5097 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5098 {
5099         int rc;
5100
5101         struct tpacpi_led_classdev *data = container_of(led_cdev,
5102                              struct tpacpi_led_classdev, led_classdev);
5103
5104         rc = led_get_status(data->led);
5105
5106         if (rc == TPACPI_LED_OFF || rc < 0)
5107                 rc = LED_OFF;   /* no error handling in led class :( */
5108         else
5109                 rc = LED_FULL;
5110
5111         return rc;
5112 }
5113
5114 static void led_exit(void)
5115 {
5116         unsigned int i;
5117
5118         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5119                 if (tpacpi_leds[i].led_classdev.name)
5120                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5121         }
5122
5123         kfree(tpacpi_leds);
5124 }
5125
5126 static int __init tpacpi_init_led(unsigned int led)
5127 {
5128         int rc;
5129
5130         tpacpi_leds[led].led = led;
5131
5132         /* LEDs with no name don't get registered */
5133         if (!tpacpi_led_names[led])
5134                 return 0;
5135
5136         tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set;
5137         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5138         if (led_supported == TPACPI_LED_570)
5139                 tpacpi_leds[led].led_classdev.brightness_get =
5140                                                 &led_sysfs_get;
5141
5142         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5143
5144         INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker);
5145
5146         rc = led_classdev_register(&tpacpi_pdev->dev,
5147                                 &tpacpi_leds[led].led_classdev);
5148         if (rc < 0)
5149                 tpacpi_leds[led].led_classdev.name = NULL;
5150
5151         return rc;
5152 }
5153
5154 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5155         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5156         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5157         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5158
5159         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5160         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5161         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5162         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5163         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5164         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5165         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5166         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5167
5168         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5169         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5170         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5171         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5172         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5173
5174         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5175         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5176         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5177         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5178
5179         /* (1) - may have excess leds enabled on MSB */
5180
5181         /* Defaults (order matters, keep last, don't reorder!) */
5182         { /* Lenovo */
5183           .vendor = PCI_VENDOR_ID_LENOVO,
5184           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5185           .quirks = 0x1fffU,
5186         },
5187         { /* IBM ThinkPads with no EC version string */
5188           .vendor = PCI_VENDOR_ID_IBM,
5189           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5190           .quirks = 0x00ffU,
5191         },
5192         { /* IBM ThinkPads with EC version string */
5193           .vendor = PCI_VENDOR_ID_IBM,
5194           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5195           .quirks = 0x00bfU,
5196         },
5197 };
5198
5199 #undef TPACPI_LEDQ_IBM
5200 #undef TPACPI_LEDQ_LNV
5201
5202 static int __init led_init(struct ibm_init_struct *iibm)
5203 {
5204         unsigned int i;
5205         int rc;
5206         unsigned long useful_leds;
5207
5208         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5209
5210         TPACPI_ACPIHANDLE_INIT(led);
5211
5212         if (!led_handle)
5213                 /* led not supported on R30, R31 */
5214                 led_supported = TPACPI_LED_NONE;
5215         else if (strlencmp(led_path, "SLED") == 0)
5216                 /* 570 */
5217                 led_supported = TPACPI_LED_570;
5218         else if (strlencmp(led_path, "SYSL") == 0)
5219                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5220                 led_supported = TPACPI_LED_OLD;
5221         else
5222                 /* all others */
5223                 led_supported = TPACPI_LED_NEW;
5224
5225         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5226                 str_supported(led_supported), led_supported);
5227
5228         if (led_supported == TPACPI_LED_NONE)
5229                 return 1;
5230
5231         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5232                               GFP_KERNEL);
5233         if (!tpacpi_leds) {
5234                 printk(TPACPI_ERR "Out of memory for LED data\n");
5235                 return -ENOMEM;
5236         }
5237
5238         useful_leds = tpacpi_check_quirks(led_useful_qtable,
5239                                           ARRAY_SIZE(led_useful_qtable));
5240
5241         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5242                 if (!tpacpi_is_led_restricted(i) &&
5243                     test_bit(i, &useful_leds)) {
5244                         rc = tpacpi_init_led(i);
5245                         if (rc < 0) {
5246                                 led_exit();
5247                                 return rc;
5248                         }
5249                 }
5250         }
5251
5252 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5253         printk(TPACPI_NOTICE
5254                 "warning: userspace override of important "
5255                 "firmware LEDs is enabled\n");
5256 #endif
5257         return 0;
5258 }
5259
5260 #define str_led_status(s) \
5261         ((s) == TPACPI_LED_OFF ? "off" : \
5262                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5263
5264 static int led_read(char *p)
5265 {
5266         int len = 0;
5267
5268         if (!led_supported) {
5269                 len += sprintf(p + len, "status:\t\tnot supported\n");
5270                 return len;
5271         }
5272         len += sprintf(p + len, "status:\t\tsupported\n");
5273
5274         if (led_supported == TPACPI_LED_570) {
5275                 /* 570 */
5276                 int i, status;
5277                 for (i = 0; i < 8; i++) {
5278                         status = led_get_status(i);
5279                         if (status < 0)
5280                                 return -EIO;
5281                         len += sprintf(p + len, "%d:\t\t%s\n",
5282                                        i, str_led_status(status));
5283                 }
5284         }
5285
5286         len += sprintf(p + len, "commands:\t"
5287                        "<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5288
5289         return len;
5290 }
5291
5292 static int led_write(char *buf)
5293 {
5294         char *cmd;
5295         int led, rc;
5296         enum led_status_t s;
5297
5298         if (!led_supported)
5299                 return -ENODEV;
5300
5301         while ((cmd = next_cmd(&buf))) {
5302                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15)
5303                         return -EINVAL;
5304
5305                 if (strstr(cmd, "off")) {
5306                         s = TPACPI_LED_OFF;
5307                 } else if (strstr(cmd, "on")) {
5308                         s = TPACPI_LED_ON;
5309                 } else if (strstr(cmd, "blink")) {
5310                         s = TPACPI_LED_BLINK;
5311                 } else {
5312                         return -EINVAL;
5313                 }
5314
5315                 rc = led_set_status(led, s);
5316                 if (rc < 0)
5317                         return rc;
5318         }
5319
5320         return 0;
5321 }
5322
5323 static struct ibm_struct led_driver_data = {
5324         .name = "led",
5325         .read = led_read,
5326         .write = led_write,
5327         .exit = led_exit,
5328 };
5329
5330 /*************************************************************************
5331  * Beep subdriver
5332  */
5333
5334 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
5335
5336 #define TPACPI_BEEP_Q1 0x0001
5337
5338 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
5339         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
5340         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
5341 };
5342
5343 static int __init beep_init(struct ibm_init_struct *iibm)
5344 {
5345         unsigned long quirks;
5346
5347         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
5348
5349         TPACPI_ACPIHANDLE_INIT(beep);
5350
5351         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
5352                 str_supported(beep_handle != NULL));
5353
5354         quirks = tpacpi_check_quirks(beep_quirk_table,
5355                                      ARRAY_SIZE(beep_quirk_table));
5356
5357         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
5358
5359         return (beep_handle)? 0 : 1;
5360 }
5361
5362 static int beep_read(char *p)
5363 {
5364         int len = 0;
5365
5366         if (!beep_handle)
5367                 len += sprintf(p + len, "status:\t\tnot supported\n");
5368         else {
5369                 len += sprintf(p + len, "status:\t\tsupported\n");
5370                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
5371         }
5372
5373         return len;
5374 }
5375
5376 static int beep_write(char *buf)
5377 {
5378         char *cmd;
5379         int beep_cmd;
5380
5381         if (!beep_handle)
5382                 return -ENODEV;
5383
5384         while ((cmd = next_cmd(&buf))) {
5385                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
5386                     beep_cmd >= 0 && beep_cmd <= 17) {
5387                         /* beep_cmd set */
5388                 } else
5389                         return -EINVAL;
5390                 if (tp_features.beep_needs_two_args) {
5391                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
5392                                         beep_cmd, 0))
5393                                 return -EIO;
5394                 } else {
5395                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
5396                                         beep_cmd))
5397                                 return -EIO;
5398                 }
5399         }
5400
5401         return 0;
5402 }
5403
5404 static struct ibm_struct beep_driver_data = {
5405         .name = "beep",
5406         .read = beep_read,
5407         .write = beep_write,
5408 };
5409
5410 /*************************************************************************
5411  * Thermal subdriver
5412  */
5413
5414 enum thermal_access_mode {
5415         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
5416         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
5417         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
5418         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
5419         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
5420 };
5421
5422 enum { /* TPACPI_THERMAL_TPEC_* */
5423         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
5424         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
5425         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
5426 };
5427
5428 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
5429 struct ibm_thermal_sensors_struct {
5430         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
5431 };
5432
5433 static enum thermal_access_mode thermal_read_mode;
5434
5435 /* idx is zero-based */
5436 static int thermal_get_sensor(int idx, s32 *value)
5437 {
5438         int t;
5439         s8 tmp;
5440         char tmpi[5];
5441
5442         t = TP_EC_THERMAL_TMP0;
5443
5444         switch (thermal_read_mode) {
5445 #if TPACPI_MAX_THERMAL_SENSORS >= 16
5446         case TPACPI_THERMAL_TPEC_16:
5447                 if (idx >= 8 && idx <= 15) {
5448                         t = TP_EC_THERMAL_TMP8;
5449                         idx -= 8;
5450                 }
5451                 /* fallthrough */
5452 #endif
5453         case TPACPI_THERMAL_TPEC_8:
5454                 if (idx <= 7) {
5455                         if (!acpi_ec_read(t + idx, &tmp))
5456                                 return -EIO;
5457                         *value = tmp * 1000;
5458                         return 0;
5459                 }
5460                 break;
5461
5462         case TPACPI_THERMAL_ACPI_UPDT:
5463                 if (idx <= 7) {
5464                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5465                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
5466                                 return -EIO;
5467                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5468                                 return -EIO;
5469                         *value = (t - 2732) * 100;
5470                         return 0;
5471                 }
5472                 break;
5473
5474         case TPACPI_THERMAL_ACPI_TMP07:
5475                 if (idx <= 7) {
5476                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5477                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5478                                 return -EIO;
5479                         if (t > 127 || t < -127)
5480                                 t = TP_EC_THERMAL_TMP_NA;
5481                         *value = t * 1000;
5482                         return 0;
5483                 }
5484                 break;
5485
5486         case TPACPI_THERMAL_NONE:
5487         default:
5488                 return -ENOSYS;
5489         }
5490
5491         return -EINVAL;
5492 }
5493
5494 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
5495 {
5496         int res, i;
5497         int n;
5498
5499         n = 8;
5500         i = 0;
5501
5502         if (!s)
5503                 return -EINVAL;
5504
5505         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
5506                 n = 16;
5507
5508         for (i = 0 ; i < n; i++) {
5509                 res = thermal_get_sensor(i, &s->temp[i]);
5510                 if (res)
5511                         return res;
5512         }
5513
5514         return n;
5515 }
5516
5517 /* sysfs temp##_input -------------------------------------------------- */
5518
5519 static ssize_t thermal_temp_input_show(struct device *dev,
5520                            struct device_attribute *attr,
5521                            char *buf)
5522 {
5523         struct sensor_device_attribute *sensor_attr =
5524                                         to_sensor_dev_attr(attr);
5525         int idx = sensor_attr->index;
5526         s32 value;
5527         int res;
5528
5529         res = thermal_get_sensor(idx, &value);
5530         if (res)
5531                 return res;
5532         if (value == TP_EC_THERMAL_TMP_NA * 1000)
5533                 return -ENXIO;
5534
5535         return snprintf(buf, PAGE_SIZE, "%d\n", value);
5536 }
5537
5538 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
5539          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
5540                      thermal_temp_input_show, NULL, _idxB)
5541
5542 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
5543         THERMAL_SENSOR_ATTR_TEMP(1, 0),
5544         THERMAL_SENSOR_ATTR_TEMP(2, 1),
5545         THERMAL_SENSOR_ATTR_TEMP(3, 2),
5546         THERMAL_SENSOR_ATTR_TEMP(4, 3),
5547         THERMAL_SENSOR_ATTR_TEMP(5, 4),
5548         THERMAL_SENSOR_ATTR_TEMP(6, 5),
5549         THERMAL_SENSOR_ATTR_TEMP(7, 6),
5550         THERMAL_SENSOR_ATTR_TEMP(8, 7),
5551         THERMAL_SENSOR_ATTR_TEMP(9, 8),
5552         THERMAL_SENSOR_ATTR_TEMP(10, 9),
5553         THERMAL_SENSOR_ATTR_TEMP(11, 10),
5554         THERMAL_SENSOR_ATTR_TEMP(12, 11),
5555         THERMAL_SENSOR_ATTR_TEMP(13, 12),
5556         THERMAL_SENSOR_ATTR_TEMP(14, 13),
5557         THERMAL_SENSOR_ATTR_TEMP(15, 14),
5558         THERMAL_SENSOR_ATTR_TEMP(16, 15),
5559 };
5560
5561 #define THERMAL_ATTRS(X) \
5562         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
5563
5564 static struct attribute *thermal_temp_input_attr[] = {
5565         THERMAL_ATTRS(8),
5566         THERMAL_ATTRS(9),
5567         THERMAL_ATTRS(10),
5568         THERMAL_ATTRS(11),
5569         THERMAL_ATTRS(12),
5570         THERMAL_ATTRS(13),
5571         THERMAL_ATTRS(14),
5572         THERMAL_ATTRS(15),
5573         THERMAL_ATTRS(0),
5574         THERMAL_ATTRS(1),
5575         THERMAL_ATTRS(2),
5576         THERMAL_ATTRS(3),
5577         THERMAL_ATTRS(4),
5578         THERMAL_ATTRS(5),
5579         THERMAL_ATTRS(6),
5580         THERMAL_ATTRS(7),
5581         NULL
5582 };
5583
5584 static const struct attribute_group thermal_temp_input16_group = {
5585         .attrs = thermal_temp_input_attr
5586 };
5587
5588 static const struct attribute_group thermal_temp_input8_group = {
5589         .attrs = &thermal_temp_input_attr[8]
5590 };
5591
5592 #undef THERMAL_SENSOR_ATTR_TEMP
5593 #undef THERMAL_ATTRS
5594
5595 /* --------------------------------------------------------------------- */
5596
5597 static int __init thermal_init(struct ibm_init_struct *iibm)
5598 {
5599         u8 t, ta1, ta2;
5600         int i;
5601         int acpi_tmp7;
5602         int res;
5603
5604         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5605
5606         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5607
5608         if (thinkpad_id.ec_model) {
5609                 /*
5610                  * Direct EC access mode: sensors at registers
5611                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5612                  * non-implemented, thermal sensors return 0x80 when
5613                  * not available
5614                  */
5615
5616                 ta1 = ta2 = 0;
5617                 for (i = 0; i < 8; i++) {
5618                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5619                                 ta1 |= t;
5620                         } else {
5621                                 ta1 = 0;
5622                                 break;
5623                         }
5624                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5625                                 ta2 |= t;
5626                         } else {
5627                                 ta1 = 0;
5628                                 break;
5629                         }
5630                 }
5631                 if (ta1 == 0) {
5632                         /* This is sheer paranoia, but we handle it anyway */
5633                         if (acpi_tmp7) {
5634                                 printk(TPACPI_ERR
5635                                        "ThinkPad ACPI EC access misbehaving, "
5636                                        "falling back to ACPI TMPx access "
5637                                        "mode\n");
5638                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5639                         } else {
5640                                 printk(TPACPI_ERR
5641                                        "ThinkPad ACPI EC access misbehaving, "
5642                                        "disabling thermal sensors access\n");
5643                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5644                         }
5645                 } else {
5646                         thermal_read_mode =
5647                             (ta2 != 0) ?
5648                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5649                 }
5650         } else if (acpi_tmp7) {
5651                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5652                         /* 600e/x, 770e, 770x */
5653                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5654                 } else {
5655                         /* Standard ACPI TMPx access, max 8 sensors */
5656                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5657                 }
5658         } else {
5659                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5660                 thermal_read_mode = TPACPI_THERMAL_NONE;
5661         }
5662
5663         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5664                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5665                 thermal_read_mode);
5666
5667         switch (thermal_read_mode) {
5668         case TPACPI_THERMAL_TPEC_16:
5669                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5670                                 &thermal_temp_input16_group);
5671                 if (res)
5672                         return res;
5673                 break;
5674         case TPACPI_THERMAL_TPEC_8:
5675         case TPACPI_THERMAL_ACPI_TMP07:
5676         case TPACPI_THERMAL_ACPI_UPDT:
5677                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5678                                 &thermal_temp_input8_group);
5679                 if (res)
5680                         return res;
5681                 break;
5682         case TPACPI_THERMAL_NONE:
5683         default:
5684                 return 1;
5685         }
5686
5687         return 0;
5688 }
5689
5690 static void thermal_exit(void)
5691 {
5692         switch (thermal_read_mode) {
5693         case TPACPI_THERMAL_TPEC_16:
5694                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5695                                    &thermal_temp_input16_group);
5696                 break;
5697         case TPACPI_THERMAL_TPEC_8:
5698         case TPACPI_THERMAL_ACPI_TMP07:
5699         case TPACPI_THERMAL_ACPI_UPDT:
5700                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5701                                    &thermal_temp_input16_group);
5702                 break;
5703         case TPACPI_THERMAL_NONE:
5704         default:
5705                 break;
5706         }
5707 }
5708
5709 static int thermal_read(char *p)
5710 {
5711         int len = 0;
5712         int n, i;
5713         struct ibm_thermal_sensors_struct t;
5714
5715         n = thermal_get_sensors(&t);
5716         if (unlikely(n < 0))
5717                 return n;
5718
5719         len += sprintf(p + len, "temperatures:\t");
5720
5721         if (n > 0) {
5722                 for (i = 0; i < (n - 1); i++)
5723                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
5724                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
5725         } else
5726                 len += sprintf(p + len, "not supported\n");
5727
5728         return len;
5729 }
5730
5731 static struct ibm_struct thermal_driver_data = {
5732         .name = "thermal",
5733         .read = thermal_read,
5734         .exit = thermal_exit,
5735 };
5736
5737 /*************************************************************************
5738  * EC Dump subdriver
5739  */
5740
5741 static u8 ecdump_regs[256];
5742
5743 static int ecdump_read(char *p)
5744 {
5745         int len = 0;
5746         int i, j;
5747         u8 v;
5748
5749         len += sprintf(p + len, "EC      "
5750                        " +00 +01 +02 +03 +04 +05 +06 +07"
5751                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5752         for (i = 0; i < 256; i += 16) {
5753                 len += sprintf(p + len, "EC 0x%02x:", i);
5754                 for (j = 0; j < 16; j++) {
5755                         if (!acpi_ec_read(i + j, &v))
5756                                 break;
5757                         if (v != ecdump_regs[i + j])
5758                                 len += sprintf(p + len, " *%02x", v);
5759                         else
5760                                 len += sprintf(p + len, "  %02x", v);
5761                         ecdump_regs[i + j] = v;
5762                 }
5763                 len += sprintf(p + len, "\n");
5764                 if (j != 16)
5765                         break;
5766         }
5767
5768         /* These are way too dangerous to advertise openly... */
5769 #if 0
5770         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
5771                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5772         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
5773                        " (<offset> is 00-ff, <value> is 0-255)\n");
5774 #endif
5775         return len;
5776 }
5777
5778 static int ecdump_write(char *buf)
5779 {
5780         char *cmd;
5781         int i, v;
5782
5783         while ((cmd = next_cmd(&buf))) {
5784                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5785                         /* i and v set */
5786                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5787                         /* i and v set */
5788                 } else
5789                         return -EINVAL;
5790                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5791                         if (!acpi_ec_write(i, v))
5792                                 return -EIO;
5793                 } else
5794                         return -EINVAL;
5795         }
5796
5797         return 0;
5798 }
5799
5800 static struct ibm_struct ecdump_driver_data = {
5801         .name = "ecdump",
5802         .read = ecdump_read,
5803         .write = ecdump_write,
5804         .flags.experimental = 1,
5805 };
5806
5807 /*************************************************************************
5808  * Backlight/brightness subdriver
5809  */
5810
5811 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5812
5813 /*
5814  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
5815  * CMOS NVRAM byte 0x5E, bits 0-3.
5816  *
5817  * EC HBRV (0x31) has the following layout
5818  *   Bit 7: unknown function
5819  *   Bit 6: unknown function
5820  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5821  *   Bit 4: must be set to zero to avoid problems
5822  *   Bit 3-0: backlight brightness level
5823  *
5824  * brightness_get_raw returns status data in the HBRV layout
5825  *
5826  * WARNING: The X61 has been verified to use HBRV for something else, so
5827  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
5828  * testing on the very early *60 Lenovo models...
5829  */
5830
5831 enum {
5832         TP_EC_BACKLIGHT = 0x31,
5833
5834         /* TP_EC_BACKLIGHT bitmasks */
5835         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5836         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5837         TP_EC_BACKLIGHT_MAPSW = 0x20,
5838 };
5839
5840 enum tpacpi_brightness_access_mode {
5841         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
5842         TPACPI_BRGHT_MODE_EC,           /* EC control */
5843         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
5844         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
5845         TPACPI_BRGHT_MODE_MAX
5846 };
5847
5848 static struct backlight_device *ibm_backlight_device;
5849
5850 static enum tpacpi_brightness_access_mode brightness_mode =
5851                 TPACPI_BRGHT_MODE_MAX;
5852
5853 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5854
5855 static struct mutex brightness_mutex;
5856
5857 /* NVRAM brightness access,
5858  * call with brightness_mutex held! */
5859 static unsigned int tpacpi_brightness_nvram_get(void)
5860 {
5861         u8 lnvram;
5862
5863         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5864                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5865                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5866         lnvram &= (tp_features.bright_16levels) ? 0x0f : 0x07;
5867
5868         return lnvram;
5869 }
5870
5871 static void tpacpi_brightness_checkpoint_nvram(void)
5872 {
5873         u8 lec = 0;
5874         u8 b_nvram;
5875
5876         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
5877                 return;
5878
5879         vdbg_printk(TPACPI_DBG_BRGHT,
5880                 "trying to checkpoint backlight level to NVRAM...\n");
5881
5882         if (mutex_lock_killable(&brightness_mutex) < 0)
5883                 return;
5884
5885         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5886                 goto unlock;
5887         lec &= TP_EC_BACKLIGHT_LVLMSK;
5888         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
5889
5890         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5891                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
5892                 /* NVRAM needs update */
5893                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
5894                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
5895                 b_nvram |= lec;
5896                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
5897                 dbg_printk(TPACPI_DBG_BRGHT,
5898                            "updated NVRAM backlight level to %u (0x%02x)\n",
5899                            (unsigned int) lec, (unsigned int) b_nvram);
5900         } else
5901                 vdbg_printk(TPACPI_DBG_BRGHT,
5902                            "NVRAM backlight level already is %u (0x%02x)\n",
5903                            (unsigned int) lec, (unsigned int) b_nvram);
5904
5905 unlock:
5906         mutex_unlock(&brightness_mutex);
5907 }
5908
5909
5910 /* call with brightness_mutex held! */
5911 static int tpacpi_brightness_get_raw(int *status)
5912 {
5913         u8 lec = 0;
5914
5915         switch (brightness_mode) {
5916         case TPACPI_BRGHT_MODE_UCMS_STEP:
5917                 *status = tpacpi_brightness_nvram_get();
5918                 return 0;
5919         case TPACPI_BRGHT_MODE_EC:
5920         case TPACPI_BRGHT_MODE_ECNVRAM:
5921                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5922                         return -EIO;
5923                 *status = lec;
5924                 return 0;
5925         default:
5926                 return -ENXIO;
5927         }
5928 }
5929
5930 /* call with brightness_mutex held! */
5931 /* do NOT call with illegal backlight level value */
5932 static int tpacpi_brightness_set_ec(unsigned int value)
5933 {
5934         u8 lec = 0;
5935
5936         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5937                 return -EIO;
5938
5939         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
5940                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
5941                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
5942                 return -EIO;
5943
5944         return 0;
5945 }
5946
5947 /* call with brightness_mutex held! */
5948 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
5949 {
5950         int cmos_cmd, inc;
5951         unsigned int current_value, i;
5952
5953         current_value = tpacpi_brightness_nvram_get();
5954
5955         if (value == current_value)
5956                 return 0;
5957
5958         cmos_cmd = (value > current_value) ?
5959                         TP_CMOS_BRIGHTNESS_UP :
5960                         TP_CMOS_BRIGHTNESS_DOWN;
5961         inc = (value > current_value) ? 1 : -1;
5962
5963         for (i = current_value; i != value; i += inc)
5964                 if (issue_thinkpad_cmos_command(cmos_cmd))
5965                         return -EIO;
5966
5967         return 0;
5968 }
5969
5970 /* May return EINTR which can always be mapped to ERESTARTSYS */
5971 static int brightness_set(unsigned int value)
5972 {
5973         int res;
5974
5975         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
5976             value < 0)
5977                 return -EINVAL;
5978
5979         vdbg_printk(TPACPI_DBG_BRGHT,
5980                         "set backlight level to %d\n", value);
5981
5982         res = mutex_lock_killable(&brightness_mutex);
5983         if (res < 0)
5984                 return res;
5985
5986         switch (brightness_mode) {
5987         case TPACPI_BRGHT_MODE_EC:
5988         case TPACPI_BRGHT_MODE_ECNVRAM:
5989                 res = tpacpi_brightness_set_ec(value);
5990                 break;
5991         case TPACPI_BRGHT_MODE_UCMS_STEP:
5992                 res = tpacpi_brightness_set_ucmsstep(value);
5993                 break;
5994         default:
5995                 res = -ENXIO;
5996         }
5997
5998         mutex_unlock(&brightness_mutex);
5999         return res;
6000 }
6001
6002 /* sysfs backlight class ----------------------------------------------- */
6003
6004 static int brightness_update_status(struct backlight_device *bd)
6005 {
6006         unsigned int level =
6007                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
6008                  bd->props.power == FB_BLANK_UNBLANK) ?
6009                                 bd->props.brightness : 0;
6010
6011         dbg_printk(TPACPI_DBG_BRGHT,
6012                         "backlight: attempt to set level to %d\n",
6013                         level);
6014
6015         /* it is the backlight class's job (caller) to handle
6016          * EINTR and other errors properly */
6017         return brightness_set(level);
6018 }
6019
6020 static int brightness_get(struct backlight_device *bd)
6021 {
6022         int status, res;
6023
6024         res = mutex_lock_killable(&brightness_mutex);
6025         if (res < 0)
6026                 return 0;
6027
6028         res = tpacpi_brightness_get_raw(&status);
6029
6030         mutex_unlock(&brightness_mutex);
6031
6032         if (res < 0)
6033                 return 0;
6034
6035         return status & TP_EC_BACKLIGHT_LVLMSK;
6036 }
6037
6038 static struct backlight_ops ibm_backlight_data = {
6039         .get_brightness = brightness_get,
6040         .update_status  = brightness_update_status,
6041 };
6042
6043 /* --------------------------------------------------------------------- */
6044
6045 /*
6046  * These are only useful for models that have only one possibility
6047  * of GPU.  If the BIOS model handles both ATI and Intel, don't use
6048  * these quirks.
6049  */
6050 #define TPACPI_BRGHT_Q_NOEC     0x0001  /* Must NOT use EC HBRV */
6051 #define TPACPI_BRGHT_Q_EC       0x0002  /* Should or must use EC HBRV */
6052 #define TPACPI_BRGHT_Q_ASK      0x8000  /* Ask for user report */
6053
6054 static const struct tpacpi_quirk brightness_quirk_table[] __initconst = {
6055         /* Models with ATI GPUs known to require ECNVRAM mode */
6056         TPACPI_Q_IBM('1', 'Y', TPACPI_BRGHT_Q_EC),      /* T43/p ATI */
6057
6058         /* Models with ATI GPUs that can use ECNVRAM */
6059         TPACPI_Q_IBM('1', 'R', TPACPI_BRGHT_Q_EC),
6060         TPACPI_Q_IBM('1', 'Q', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6061         TPACPI_Q_IBM('7', '6', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6062         TPACPI_Q_IBM('7', '8', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_EC),
6063
6064         /* Models with Intel Extreme Graphics 2 */
6065         TPACPI_Q_IBM('1', 'U', TPACPI_BRGHT_Q_NOEC),
6066         TPACPI_Q_IBM('1', 'V', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_NOEC),
6067         TPACPI_Q_IBM('1', 'W', TPACPI_BRGHT_Q_ASK|TPACPI_BRGHT_Q_NOEC),
6068
6069         /* Models with Intel GMA900 */
6070         TPACPI_Q_IBM('7', '0', TPACPI_BRGHT_Q_NOEC),    /* T43, R52 */
6071         TPACPI_Q_IBM('7', '4', TPACPI_BRGHT_Q_NOEC),    /* X41 */
6072         TPACPI_Q_IBM('7', '5', TPACPI_BRGHT_Q_NOEC),    /* X41 Tablet */
6073 };
6074
6075 static int __init brightness_init(struct ibm_init_struct *iibm)
6076 {
6077         int b;
6078         unsigned long quirks;
6079
6080         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
6081
6082         mutex_init(&brightness_mutex);
6083
6084         quirks = tpacpi_check_quirks(brightness_quirk_table,
6085                                 ARRAY_SIZE(brightness_quirk_table));
6086
6087         /*
6088          * We always attempt to detect acpi support, so as to switch
6089          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
6090          * going to publish a backlight interface
6091          */
6092         b = tpacpi_check_std_acpi_brightness_support();
6093         if (b > 0) {
6094
6095                 if (acpi_video_backlight_support()) {
6096                         if (brightness_enable > 1) {
6097                                 printk(TPACPI_NOTICE
6098                                        "Standard ACPI backlight interface "
6099                                        "available, not loading native one.\n");
6100                                 return 1;
6101                         } else if (brightness_enable == 1) {
6102                                 printk(TPACPI_NOTICE
6103                                        "Backlight control force enabled, even if standard "
6104                                        "ACPI backlight interface is available\n");
6105                         }
6106                 } else {
6107                         if (brightness_enable > 1) {
6108                                 printk(TPACPI_NOTICE
6109                                        "Standard ACPI backlight interface not "
6110                                        "available, thinkpad_acpi native "
6111                                        "brightness control enabled\n");
6112                         }
6113                 }
6114         }
6115
6116         if (!brightness_enable) {
6117                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6118                            "brightness support disabled by "
6119                            "module parameter\n");
6120                 return 1;
6121         }
6122
6123         if (b > 16) {
6124                 printk(TPACPI_ERR
6125                        "Unsupported brightness interface, "
6126                        "please contact %s\n", TPACPI_MAIL);
6127                 return 1;
6128         }
6129         if (b == 16)
6130                 tp_features.bright_16levels = 1;
6131
6132         /*
6133          * Check for module parameter bogosity, note that we
6134          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6135          * able to detect "unspecified"
6136          */
6137         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6138                 return -EINVAL;
6139
6140         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6141         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6142             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6143                 if (quirks & TPACPI_BRGHT_Q_EC)
6144                         brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6145                 else
6146                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6147
6148                 dbg_printk(TPACPI_DBG_BRGHT,
6149                            "driver auto-selected brightness_mode=%d\n",
6150                            brightness_mode);
6151         }
6152
6153         /* Safety */
6154         if (thinkpad_id.vendor != PCI_VENDOR_ID_IBM &&
6155             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6156              brightness_mode == TPACPI_BRGHT_MODE_EC))
6157                 return -EINVAL;
6158
6159         if (tpacpi_brightness_get_raw(&b) < 0)
6160                 return 1;
6161
6162         if (tp_features.bright_16levels)
6163                 printk(TPACPI_INFO
6164                        "detected a 16-level brightness capable ThinkPad\n");
6165
6166         ibm_backlight_device = backlight_device_register(
6167                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
6168                                         &ibm_backlight_data);
6169         if (IS_ERR(ibm_backlight_device)) {
6170                 int rc = PTR_ERR(ibm_backlight_device);
6171                 ibm_backlight_device = NULL;
6172                 printk(TPACPI_ERR "Could not register backlight device\n");
6173                 return rc;
6174         }
6175         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6176                         "brightness is supported\n");
6177
6178         if (quirks & TPACPI_BRGHT_Q_ASK) {
6179                 printk(TPACPI_NOTICE
6180                         "brightness: will use unverified default: "
6181                         "brightness_mode=%d\n", brightness_mode);
6182                 printk(TPACPI_NOTICE
6183                         "brightness: please report to %s whether it works well "
6184                         "or not on your ThinkPad\n", TPACPI_MAIL);
6185         }
6186
6187         ibm_backlight_device->props.max_brightness =
6188                                 (tp_features.bright_16levels)? 15 : 7;
6189         ibm_backlight_device->props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6190         backlight_update_status(ibm_backlight_device);
6191
6192         return 0;
6193 }
6194
6195 static void brightness_suspend(pm_message_t state)
6196 {
6197         tpacpi_brightness_checkpoint_nvram();
6198 }
6199
6200 static void brightness_shutdown(void)
6201 {
6202         tpacpi_brightness_checkpoint_nvram();
6203 }
6204
6205 static void brightness_exit(void)
6206 {
6207         if (ibm_backlight_device) {
6208                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6209                             "calling backlight_device_unregister()\n");
6210                 backlight_device_unregister(ibm_backlight_device);
6211         }
6212
6213         tpacpi_brightness_checkpoint_nvram();
6214 }
6215
6216 static int brightness_read(char *p)
6217 {
6218         int len = 0;
6219         int level;
6220
6221         level = brightness_get(NULL);
6222         if (level < 0) {
6223                 len += sprintf(p + len, "level:\t\tunreadable\n");
6224         } else {
6225                 len += sprintf(p + len, "level:\t\t%d\n", level);
6226                 len += sprintf(p + len, "commands:\tup, down\n");
6227                 len += sprintf(p + len, "commands:\tlevel <level>"
6228                                " (<level> is 0-%d)\n",
6229                                (tp_features.bright_16levels) ? 15 : 7);
6230         }
6231
6232         return len;
6233 }
6234
6235 static int brightness_write(char *buf)
6236 {
6237         int level;
6238         int rc;
6239         char *cmd;
6240         int max_level = (tp_features.bright_16levels) ? 15 : 7;
6241
6242         level = brightness_get(NULL);
6243         if (level < 0)
6244                 return level;
6245
6246         while ((cmd = next_cmd(&buf))) {
6247                 if (strlencmp(cmd, "up") == 0) {
6248                         if (level < max_level)
6249                                 level++;
6250                 } else if (strlencmp(cmd, "down") == 0) {
6251                         if (level > 0)
6252                                 level--;
6253                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6254                            level >= 0 && level <= max_level) {
6255                         /* new level set */
6256                 } else
6257                         return -EINVAL;
6258         }
6259
6260         tpacpi_disclose_usertask("procfs brightness",
6261                         "set level to %d\n", level);
6262
6263         /*
6264          * Now we know what the final level should be, so we try to set it.
6265          * Doing it this way makes the syscall restartable in case of EINTR
6266          */
6267         rc = brightness_set(level);
6268         return (rc == -EINTR)? ERESTARTSYS : rc;
6269 }
6270
6271 static struct ibm_struct brightness_driver_data = {
6272         .name = "brightness",
6273         .read = brightness_read,
6274         .write = brightness_write,
6275         .exit = brightness_exit,
6276         .suspend = brightness_suspend,
6277         .shutdown = brightness_shutdown,
6278 };
6279
6280 /*************************************************************************
6281  * Volume subdriver
6282  */
6283
6284 static int volume_offset = 0x30;
6285
6286 static int volume_read(char *p)
6287 {
6288         int len = 0;
6289         u8 level;
6290
6291         if (!acpi_ec_read(volume_offset, &level)) {
6292                 len += sprintf(p + len, "level:\t\tunreadable\n");
6293         } else {
6294                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
6295                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
6296                 len += sprintf(p + len, "commands:\tup, down, mute\n");
6297                 len += sprintf(p + len, "commands:\tlevel <level>"
6298                                " (<level> is 0-15)\n");
6299         }
6300
6301         return len;
6302 }
6303
6304 static int volume_write(char *buf)
6305 {
6306         int cmos_cmd, inc, i;
6307         u8 level, mute;
6308         int new_level, new_mute;
6309         char *cmd;
6310
6311         while ((cmd = next_cmd(&buf))) {
6312                 if (!acpi_ec_read(volume_offset, &level))
6313                         return -EIO;
6314                 new_mute = mute = level & 0x40;
6315                 new_level = level = level & 0xf;
6316
6317                 if (strlencmp(cmd, "up") == 0) {
6318                         if (mute)
6319                                 new_mute = 0;
6320                         else
6321                                 new_level = level == 15 ? 15 : level + 1;
6322                 } else if (strlencmp(cmd, "down") == 0) {
6323                         if (mute)
6324                                 new_mute = 0;
6325                         else
6326                                 new_level = level == 0 ? 0 : level - 1;
6327                 } else if (sscanf(cmd, "level %d", &new_level) == 1 &&
6328                            new_level >= 0 && new_level <= 15) {
6329                         /* new_level set */
6330                 } else if (strlencmp(cmd, "mute") == 0) {
6331                         new_mute = 0x40;
6332                 } else
6333                         return -EINVAL;
6334
6335                 if (new_level != level) {
6336                         /* mute doesn't change */
6337
6338                         cmos_cmd = (new_level > level) ?
6339                                         TP_CMOS_VOLUME_UP : TP_CMOS_VOLUME_DOWN;
6340                         inc = new_level > level ? 1 : -1;
6341
6342                         if (mute && (issue_thinkpad_cmos_command(cmos_cmd) ||
6343                                      !acpi_ec_write(volume_offset, level)))
6344                                 return -EIO;
6345
6346                         for (i = level; i != new_level; i += inc)
6347                                 if (issue_thinkpad_cmos_command(cmos_cmd) ||
6348                                     !acpi_ec_write(volume_offset, i + inc))
6349                                         return -EIO;
6350
6351                         if (mute &&
6352                             (issue_thinkpad_cmos_command(TP_CMOS_VOLUME_MUTE) ||
6353                              !acpi_ec_write(volume_offset, new_level + mute))) {
6354                                 return -EIO;
6355                         }
6356                 }
6357
6358                 if (new_mute != mute) {
6359                         /* level doesn't change */
6360
6361                         cmos_cmd = (new_mute) ?
6362                                    TP_CMOS_VOLUME_MUTE : TP_CMOS_VOLUME_UP;
6363
6364                         if (issue_thinkpad_cmos_command(cmos_cmd) ||
6365                             !acpi_ec_write(volume_offset, level + new_mute))
6366                                 return -EIO;
6367                 }
6368         }
6369
6370         return 0;
6371 }
6372
6373 static struct ibm_struct volume_driver_data = {
6374         .name = "volume",
6375         .read = volume_read,
6376         .write = volume_write,
6377 };
6378
6379 /*************************************************************************
6380  * Fan subdriver
6381  */
6382
6383 /*
6384  * FAN ACCESS MODES
6385  *
6386  * TPACPI_FAN_RD_ACPI_GFAN:
6387  *      ACPI GFAN method: returns fan level
6388  *
6389  *      see TPACPI_FAN_WR_ACPI_SFAN
6390  *      EC 0x2f (HFSP) not available if GFAN exists
6391  *
6392  * TPACPI_FAN_WR_ACPI_SFAN:
6393  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
6394  *
6395  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
6396  *      it for writing.
6397  *
6398  * TPACPI_FAN_WR_TPEC:
6399  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
6400  *      Supported on almost all ThinkPads
6401  *
6402  *      Fan speed changes of any sort (including those caused by the
6403  *      disengaged mode) are usually done slowly by the firmware as the
6404  *      maximum ammount of fan duty cycle change per second seems to be
6405  *      limited.
6406  *
6407  *      Reading is not available if GFAN exists.
6408  *      Writing is not available if SFAN exists.
6409  *
6410  *      Bits
6411  *       7      automatic mode engaged;
6412  *              (default operation mode of the ThinkPad)
6413  *              fan level is ignored in this mode.
6414  *       6      full speed mode (takes precedence over bit 7);
6415  *              not available on all thinkpads.  May disable
6416  *              the tachometer while the fan controller ramps up
6417  *              the speed (which can take up to a few *minutes*).
6418  *              Speeds up fan to 100% duty-cycle, which is far above
6419  *              the standard RPM levels.  It is not impossible that
6420  *              it could cause hardware damage.
6421  *      5-3     unused in some models.  Extra bits for fan level
6422  *              in others, but still useless as all values above
6423  *              7 map to the same speed as level 7 in these models.
6424  *      2-0     fan level (0..7 usually)
6425  *                      0x00 = stop
6426  *                      0x07 = max (set when temperatures critical)
6427  *              Some ThinkPads may have other levels, see
6428  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
6429  *
6430  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
6431  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
6432  *      does so, its initial value is meaningless (0x07).
6433  *
6434  *      For firmware bugs, refer to:
6435  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
6436  *
6437  *      ----
6438  *
6439  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
6440  *      Main fan tachometer reading (in RPM)
6441  *
6442  *      This register is present on all ThinkPads with a new-style EC, and
6443  *      it is known not to be present on the A21m/e, and T22, as there is
6444  *      something else in offset 0x84 according to the ACPI DSDT.  Other
6445  *      ThinkPads from this same time period (and earlier) probably lack the
6446  *      tachometer as well.
6447  *
6448  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
6449  *      was never fixed by IBM to report the EC firmware version string
6450  *      probably support the tachometer (like the early X models), so
6451  *      detecting it is quite hard.  We need more data to know for sure.
6452  *
6453  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
6454  *      might result.
6455  *
6456  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
6457  *      mode.
6458  *
6459  *      For firmware bugs, refer to:
6460  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
6461  *
6462  *      ----
6463  *
6464  *      ThinkPad EC register 0x31 bit 0 (only on select models)
6465  *
6466  *      When bit 0 of EC register 0x31 is zero, the tachometer registers
6467  *      show the speed of the main fan.  When bit 0 of EC register 0x31
6468  *      is one, the tachometer registers show the speed of the auxiliary
6469  *      fan.
6470  *
6471  *      Fan control seems to affect both fans, regardless of the state
6472  *      of this bit.
6473  *
6474  *      So far, only the firmware for the X60/X61 non-tablet versions
6475  *      seem to support this (firmware TP-7M).
6476  *
6477  * TPACPI_FAN_WR_ACPI_FANS:
6478  *      ThinkPad X31, X40, X41.  Not available in the X60.
6479  *
6480  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
6481  *      high speed.  ACPI DSDT seems to map these three speeds to levels
6482  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
6483  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
6484  *
6485  *      The speeds are stored on handles
6486  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
6487  *
6488  *      There are three default speed sets, acessible as handles:
6489  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
6490  *
6491  *      ACPI DSDT switches which set is in use depending on various
6492  *      factors.
6493  *
6494  *      TPACPI_FAN_WR_TPEC is also available and should be used to
6495  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
6496  *      but the ACPI tables just mention level 7.
6497  */
6498
6499 enum {                                  /* Fan control constants */
6500         fan_status_offset = 0x2f,       /* EC register 0x2f */
6501         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
6502                                          * 0x84 must be read before 0x85 */
6503         fan_select_offset = 0x31,       /* EC register 0x31 (Firmware 7M)
6504                                            bit 0 selects which fan is active */
6505
6506         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
6507         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
6508
6509         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
6510 };
6511
6512 enum fan_status_access_mode {
6513         TPACPI_FAN_NONE = 0,            /* No fan status or control */
6514         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
6515         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
6516 };
6517
6518 enum fan_control_access_mode {
6519         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
6520         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
6521         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
6522         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
6523 };
6524
6525 enum fan_control_commands {
6526         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
6527         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
6528         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
6529                                                  * and also watchdog cmd */
6530 };
6531
6532 static int fan_control_allowed;
6533
6534 static enum fan_status_access_mode fan_status_access_mode;
6535 static enum fan_control_access_mode fan_control_access_mode;
6536 static enum fan_control_commands fan_control_commands;
6537
6538 static u8 fan_control_initial_status;
6539 static u8 fan_control_desired_level;
6540 static u8 fan_control_resume_level;
6541 static int fan_watchdog_maxinterval;
6542
6543 static struct mutex fan_mutex;
6544
6545 static void fan_watchdog_fire(struct work_struct *ignored);
6546 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
6547
6548 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
6549 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
6550            "\\FSPD",            /* 600e/x, 770e, 770x */
6551            );                   /* all others */
6552 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
6553            "JFNS",              /* 770x-JL */
6554            );                   /* all others */
6555
6556 /*
6557  * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the
6558  * HFSP register at boot, so it contains 0x07 but the Thinkpad could
6559  * be in auto mode (0x80).
6560  *
6561  * This is corrected by any write to HFSP either by the driver, or
6562  * by the firmware.
6563  *
6564  * We assume 0x07 really means auto mode while this quirk is active,
6565  * as this is far more likely than the ThinkPad being in level 7,
6566  * which is only used by the firmware during thermal emergencies.
6567  *
6568  * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52),
6569  * TP-70 (T43, R52), which are known to be buggy.
6570  */
6571
6572 static void fan_quirk1_setup(void)
6573 {
6574         if (fan_control_initial_status == 0x07) {
6575                 printk(TPACPI_NOTICE
6576                        "fan_init: initial fan status is unknown, "
6577                        "assuming it is in auto mode\n");
6578                 tp_features.fan_ctrl_status_undef = 1;
6579         }
6580 }
6581
6582 static void fan_quirk1_handle(u8 *fan_status)
6583 {
6584         if (unlikely(tp_features.fan_ctrl_status_undef)) {
6585                 if (*fan_status != fan_control_initial_status) {
6586                         /* something changed the HFSP regisnter since
6587                          * driver init time, so it is not undefined
6588                          * anymore */
6589                         tp_features.fan_ctrl_status_undef = 0;
6590                 } else {
6591                         /* Return most likely status. In fact, it
6592                          * might be the only possible status */
6593                         *fan_status = TP_EC_FAN_AUTO;
6594                 }
6595         }
6596 }
6597
6598 /* Select main fan on X60/X61, NOOP on others */
6599 static bool fan_select_fan1(void)
6600 {
6601         if (tp_features.second_fan) {
6602                 u8 val;
6603
6604                 if (ec_read(fan_select_offset, &val) < 0)
6605                         return false;
6606                 val &= 0xFEU;
6607                 if (ec_write(fan_select_offset, val) < 0)
6608                         return false;
6609         }
6610         return true;
6611 }
6612
6613 /* Select secondary fan on X60/X61 */
6614 static bool fan_select_fan2(void)
6615 {
6616         u8 val;
6617
6618         if (!tp_features.second_fan)
6619                 return false;
6620
6621         if (ec_read(fan_select_offset, &val) < 0)
6622                 return false;
6623         val |= 0x01U;
6624         if (ec_write(fan_select_offset, val) < 0)
6625                 return false;
6626
6627         return true;
6628 }
6629
6630 /*
6631  * Call with fan_mutex held
6632  */
6633 static void fan_update_desired_level(u8 status)
6634 {
6635         if ((status &
6636              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
6637                 if (status > 7)
6638                         fan_control_desired_level = 7;
6639                 else
6640                         fan_control_desired_level = status;
6641         }
6642 }
6643
6644 static int fan_get_status(u8 *status)
6645 {
6646         u8 s;
6647
6648         /* TODO:
6649          * Add TPACPI_FAN_RD_ACPI_FANS ? */
6650
6651         switch (fan_status_access_mode) {
6652         case TPACPI_FAN_RD_ACPI_GFAN:
6653                 /* 570, 600e/x, 770e, 770x */
6654
6655                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
6656                         return -EIO;
6657
6658                 if (likely(status))
6659                         *status = s & 0x07;
6660
6661                 break;
6662
6663         case TPACPI_FAN_RD_TPEC:
6664                 /* all except 570, 600e/x, 770e, 770x */
6665                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
6666                         return -EIO;
6667
6668                 if (likely(status)) {
6669                         *status = s;
6670                         fan_quirk1_handle(status);
6671                 }
6672
6673                 break;
6674
6675         default:
6676                 return -ENXIO;
6677         }
6678
6679         return 0;
6680 }
6681
6682 static int fan_get_status_safe(u8 *status)
6683 {
6684         int rc;
6685         u8 s;
6686
6687         if (mutex_lock_killable(&fan_mutex))
6688                 return -ERESTARTSYS;
6689         rc = fan_get_status(&s);
6690         if (!rc)
6691                 fan_update_desired_level(s);
6692         mutex_unlock(&fan_mutex);
6693
6694         if (status)
6695                 *status = s;
6696
6697         return rc;
6698 }
6699
6700 static int fan_get_speed(unsigned int *speed)
6701 {
6702         u8 hi, lo;
6703
6704         switch (fan_status_access_mode) {
6705         case TPACPI_FAN_RD_TPEC:
6706                 /* all except 570, 600e/x, 770e, 770x */
6707                 if (unlikely(!fan_select_fan1()))
6708                         return -EIO;
6709                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
6710                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
6711                         return -EIO;
6712
6713                 if (likely(speed))
6714                         *speed = (hi << 8) | lo;
6715
6716                 break;
6717
6718         default:
6719                 return -ENXIO;
6720         }
6721
6722         return 0;
6723 }
6724
6725 static int fan2_get_speed(unsigned int *speed)
6726 {
6727         u8 hi, lo;
6728         bool rc;
6729
6730         switch (fan_status_access_mode) {
6731         case TPACPI_FAN_RD_TPEC:
6732                 /* all except 570, 600e/x, 770e, 770x */
6733                 if (unlikely(!fan_select_fan2()))
6734                         return -EIO;
6735                 rc = !acpi_ec_read(fan_rpm_offset, &lo) ||
6736                              !acpi_ec_read(fan_rpm_offset + 1, &hi);
6737                 fan_select_fan1(); /* play it safe */
6738                 if (rc)
6739                         return -EIO;
6740
6741                 if (likely(speed))
6742                         *speed = (hi << 8) | lo;
6743
6744                 break;
6745
6746         default:
6747                 return -ENXIO;
6748         }
6749
6750         return 0;
6751 }
6752
6753 static int fan_set_level(int level)
6754 {
6755         if (!fan_control_allowed)
6756                 return -EPERM;
6757
6758         switch (fan_control_access_mode) {
6759         case TPACPI_FAN_WR_ACPI_SFAN:
6760                 if (level >= 0 && level <= 7) {
6761                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
6762                                 return -EIO;
6763                 } else
6764                         return -EINVAL;
6765                 break;
6766
6767         case TPACPI_FAN_WR_ACPI_FANS:
6768         case TPACPI_FAN_WR_TPEC:
6769                 if (!(level & TP_EC_FAN_AUTO) &&
6770                     !(level & TP_EC_FAN_FULLSPEED) &&
6771                     ((level < 0) || (level > 7)))
6772                         return -EINVAL;
6773
6774                 /* safety net should the EC not support AUTO
6775                  * or FULLSPEED mode bits and just ignore them */
6776                 if (level & TP_EC_FAN_FULLSPEED)
6777                         level |= 7;     /* safety min speed 7 */
6778                 else if (level & TP_EC_FAN_AUTO)
6779                         level |= 4;     /* safety min speed 4 */
6780
6781                 if (!acpi_ec_write(fan_status_offset, level))
6782                         return -EIO;
6783                 else
6784                         tp_features.fan_ctrl_status_undef = 0;
6785                 break;
6786
6787         default:
6788                 return -ENXIO;
6789         }
6790
6791         vdbg_printk(TPACPI_DBG_FAN,
6792                 "fan control: set fan control register to 0x%02x\n", level);
6793         return 0;
6794 }
6795
6796 static int fan_set_level_safe(int level)
6797 {
6798         int rc;
6799
6800         if (!fan_control_allowed)
6801                 return -EPERM;
6802
6803         if (mutex_lock_killable(&fan_mutex))
6804                 return -ERESTARTSYS;
6805
6806         if (level == TPACPI_FAN_LAST_LEVEL)
6807                 level = fan_control_desired_level;
6808
6809         rc = fan_set_level(level);
6810         if (!rc)
6811                 fan_update_desired_level(level);
6812
6813         mutex_unlock(&fan_mutex);
6814         return rc;
6815 }
6816
6817 static int fan_set_enable(void)
6818 {
6819         u8 s;
6820         int rc;
6821
6822         if (!fan_control_allowed)
6823                 return -EPERM;
6824
6825         if (mutex_lock_killable(&fan_mutex))
6826                 return -ERESTARTSYS;
6827
6828         switch (fan_control_access_mode) {
6829         case TPACPI_FAN_WR_ACPI_FANS:
6830         case TPACPI_FAN_WR_TPEC:
6831                 rc = fan_get_status(&s);
6832                 if (rc < 0)
6833                         break;
6834
6835                 /* Don't go out of emergency fan mode */
6836                 if (s != 7) {
6837                         s &= 0x07;
6838                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
6839                 }
6840
6841                 if (!acpi_ec_write(fan_status_offset, s))
6842                         rc = -EIO;
6843                 else {
6844                         tp_features.fan_ctrl_status_undef = 0;
6845                         rc = 0;
6846                 }
6847                 break;
6848
6849         case TPACPI_FAN_WR_ACPI_SFAN:
6850                 rc = fan_get_status(&s);
6851                 if (rc < 0)
6852                         break;
6853
6854                 s &= 0x07;
6855
6856                 /* Set fan to at least level 4 */
6857                 s |= 4;
6858
6859                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
6860                         rc = -EIO;
6861                 else
6862                         rc = 0;
6863                 break;
6864
6865         default:
6866                 rc = -ENXIO;
6867         }
6868
6869         mutex_unlock(&fan_mutex);
6870
6871         if (!rc)
6872                 vdbg_printk(TPACPI_DBG_FAN,
6873                         "fan control: set fan control register to 0x%02x\n",
6874                         s);
6875         return rc;
6876 }
6877
6878 static int fan_set_disable(void)
6879 {
6880         int rc;
6881
6882         if (!fan_control_allowed)
6883                 return -EPERM;
6884
6885         if (mutex_lock_killable(&fan_mutex))
6886                 return -ERESTARTSYS;
6887
6888         rc = 0;
6889         switch (fan_control_access_mode) {
6890         case TPACPI_FAN_WR_ACPI_FANS:
6891         case TPACPI_FAN_WR_TPEC:
6892                 if (!acpi_ec_write(fan_status_offset, 0x00))
6893                         rc = -EIO;
6894                 else {
6895                         fan_control_desired_level = 0;
6896                         tp_features.fan_ctrl_status_undef = 0;
6897                 }
6898                 break;
6899
6900         case TPACPI_FAN_WR_ACPI_SFAN:
6901                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
6902                         rc = -EIO;
6903                 else
6904                         fan_control_desired_level = 0;
6905                 break;
6906
6907         default:
6908                 rc = -ENXIO;
6909         }
6910
6911         if (!rc)
6912                 vdbg_printk(TPACPI_DBG_FAN,
6913                         "fan control: set fan control register to 0\n");
6914
6915         mutex_unlock(&fan_mutex);
6916         return rc;
6917 }
6918
6919 static int fan_set_speed(int speed)
6920 {
6921         int rc;
6922
6923         if (!fan_control_allowed)
6924                 return -EPERM;
6925
6926         if (mutex_lock_killable(&fan_mutex))
6927                 return -ERESTARTSYS;
6928
6929         rc = 0;
6930         switch (fan_control_access_mode) {
6931         case TPACPI_FAN_WR_ACPI_FANS:
6932                 if (speed >= 0 && speed <= 65535) {
6933                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
6934                                         speed, speed, speed))
6935                                 rc = -EIO;
6936                 } else
6937                         rc = -EINVAL;
6938                 break;
6939
6940         default:
6941                 rc = -ENXIO;
6942         }
6943
6944         mutex_unlock(&fan_mutex);
6945         return rc;
6946 }
6947
6948 static void fan_watchdog_reset(void)
6949 {
6950         static int fan_watchdog_active;
6951
6952         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
6953                 return;
6954
6955         if (fan_watchdog_active)
6956                 cancel_delayed_work(&fan_watchdog_task);
6957
6958         if (fan_watchdog_maxinterval > 0 &&
6959             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
6960                 fan_watchdog_active = 1;
6961                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
6962                                 msecs_to_jiffies(fan_watchdog_maxinterval
6963                                                  * 1000))) {
6964                         printk(TPACPI_ERR
6965                                "failed to queue the fan watchdog, "
6966                                "watchdog will not trigger\n");
6967                 }
6968         } else
6969                 fan_watchdog_active = 0;
6970 }
6971
6972 static void fan_watchdog_fire(struct work_struct *ignored)
6973 {
6974         int rc;
6975
6976         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
6977                 return;
6978
6979         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
6980         rc = fan_set_enable();
6981         if (rc < 0) {
6982                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
6983                         "will try again later...\n", -rc);
6984                 /* reschedule for later */
6985                 fan_watchdog_reset();
6986         }
6987 }
6988
6989 /*
6990  * SYSFS fan layout: hwmon compatible (device)
6991  *
6992  * pwm*_enable:
6993  *      0: "disengaged" mode
6994  *      1: manual mode
6995  *      2: native EC "auto" mode (recommended, hardware default)
6996  *
6997  * pwm*: set speed in manual mode, ignored otherwise.
6998  *      0 is level 0; 255 is level 7. Intermediate points done with linear
6999  *      interpolation.
7000  *
7001  * fan*_input: tachometer reading, RPM
7002  *
7003  *
7004  * SYSFS fan layout: extensions
7005  *
7006  * fan_watchdog (driver):
7007  *      fan watchdog interval in seconds, 0 disables (default), max 120
7008  */
7009
7010 /* sysfs fan pwm1_enable ----------------------------------------------- */
7011 static ssize_t fan_pwm1_enable_show(struct device *dev,
7012                                     struct device_attribute *attr,
7013                                     char *buf)
7014 {
7015         int res, mode;
7016         u8 status;
7017
7018         res = fan_get_status_safe(&status);
7019         if (res)
7020                 return res;
7021
7022         if (status & TP_EC_FAN_FULLSPEED) {
7023                 mode = 0;
7024         } else if (status & TP_EC_FAN_AUTO) {
7025                 mode = 2;
7026         } else
7027                 mode = 1;
7028
7029         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
7030 }
7031
7032 static ssize_t fan_pwm1_enable_store(struct device *dev,
7033                                      struct device_attribute *attr,
7034                                      const char *buf, size_t count)
7035 {
7036         unsigned long t;
7037         int res, level;
7038
7039         if (parse_strtoul(buf, 2, &t))
7040                 return -EINVAL;
7041
7042         tpacpi_disclose_usertask("hwmon pwm1_enable",
7043                         "set fan mode to %lu\n", t);
7044
7045         switch (t) {
7046         case 0:
7047                 level = TP_EC_FAN_FULLSPEED;
7048                 break;
7049         case 1:
7050                 level = TPACPI_FAN_LAST_LEVEL;
7051                 break;
7052         case 2:
7053                 level = TP_EC_FAN_AUTO;
7054                 break;
7055         case 3:
7056                 /* reserved for software-controlled auto mode */
7057                 return -ENOSYS;
7058         default:
7059                 return -EINVAL;
7060         }
7061
7062         res = fan_set_level_safe(level);
7063         if (res == -ENXIO)
7064                 return -EINVAL;
7065         else if (res < 0)
7066                 return res;
7067
7068         fan_watchdog_reset();
7069
7070         return count;
7071 }
7072
7073 static struct device_attribute dev_attr_fan_pwm1_enable =
7074         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
7075                 fan_pwm1_enable_show, fan_pwm1_enable_store);
7076
7077 /* sysfs fan pwm1 ------------------------------------------------------ */
7078 static ssize_t fan_pwm1_show(struct device *dev,
7079                              struct device_attribute *attr,
7080                              char *buf)
7081 {
7082         int res;
7083         u8 status;
7084
7085         res = fan_get_status_safe(&status);
7086         if (res)
7087                 return res;
7088
7089         if ((status &
7090              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
7091                 status = fan_control_desired_level;
7092
7093         if (status > 7)
7094                 status = 7;
7095
7096         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
7097 }
7098
7099 static ssize_t fan_pwm1_store(struct device *dev,
7100                               struct device_attribute *attr,
7101                               const char *buf, size_t count)
7102 {
7103         unsigned long s;
7104         int rc;
7105         u8 status, newlevel;
7106
7107         if (parse_strtoul(buf, 255, &s))
7108                 return -EINVAL;
7109
7110         tpacpi_disclose_usertask("hwmon pwm1",
7111                         "set fan speed to %lu\n", s);
7112
7113         /* scale down from 0-255 to 0-7 */
7114         newlevel = (s >> 5) & 0x07;
7115
7116         if (mutex_lock_killable(&fan_mutex))
7117                 return -ERESTARTSYS;
7118
7119         rc = fan_get_status(&status);
7120         if (!rc && (status &
7121                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
7122                 rc = fan_set_level(newlevel);
7123                 if (rc == -ENXIO)
7124                         rc = -EINVAL;
7125                 else if (!rc) {
7126                         fan_update_desired_level(newlevel);
7127                         fan_watchdog_reset();
7128                 }
7129         }
7130
7131         mutex_unlock(&fan_mutex);
7132         return (rc)? rc : count;
7133 }
7134
7135 static struct device_attribute dev_attr_fan_pwm1 =
7136         __ATTR(pwm1, S_IWUSR | S_IRUGO,
7137                 fan_pwm1_show, fan_pwm1_store);
7138
7139 /* sysfs fan fan1_input ------------------------------------------------ */
7140 static ssize_t fan_fan1_input_show(struct device *dev,
7141                            struct device_attribute *attr,
7142                            char *buf)
7143 {
7144         int res;
7145         unsigned int speed;
7146
7147         res = fan_get_speed(&speed);
7148         if (res < 0)
7149                 return res;
7150
7151         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7152 }
7153
7154 static struct device_attribute dev_attr_fan_fan1_input =
7155         __ATTR(fan1_input, S_IRUGO,
7156                 fan_fan1_input_show, NULL);
7157
7158 /* sysfs fan fan2_input ------------------------------------------------ */
7159 static ssize_t fan_fan2_input_show(struct device *dev,
7160                            struct device_attribute *attr,
7161                            char *buf)
7162 {
7163         int res;
7164         unsigned int speed;
7165
7166         res = fan2_get_speed(&speed);
7167         if (res < 0)
7168                 return res;
7169
7170         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7171 }
7172
7173 static struct device_attribute dev_attr_fan_fan2_input =
7174         __ATTR(fan2_input, S_IRUGO,
7175                 fan_fan2_input_show, NULL);
7176
7177 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
7178 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
7179                                      char *buf)
7180 {
7181         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
7182 }
7183
7184 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
7185                                       const char *buf, size_t count)
7186 {
7187         unsigned long t;
7188
7189         if (parse_strtoul(buf, 120, &t))
7190                 return -EINVAL;
7191
7192         if (!fan_control_allowed)
7193                 return -EPERM;
7194
7195         fan_watchdog_maxinterval = t;
7196         fan_watchdog_reset();
7197
7198         tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t);
7199
7200         return count;
7201 }
7202
7203 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
7204                 fan_fan_watchdog_show, fan_fan_watchdog_store);
7205
7206 /* --------------------------------------------------------------------- */
7207 static struct attribute *fan_attributes[] = {
7208         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
7209         &dev_attr_fan_fan1_input.attr,
7210         NULL, /* for fan2_input */
7211         NULL
7212 };
7213
7214 static const struct attribute_group fan_attr_group = {
7215         .attrs = fan_attributes,
7216 };
7217
7218 #define TPACPI_FAN_Q1   0x0001          /* Unitialized HFSP */
7219 #define TPACPI_FAN_2FAN 0x0002          /* EC 0x31 bit 0 selects fan2 */
7220
7221 #define TPACPI_FAN_QI(__id1, __id2, __quirks)   \
7222         { .vendor = PCI_VENDOR_ID_IBM,          \
7223           .bios = TPACPI_MATCH_ANY,             \
7224           .ec = TPID(__id1, __id2),             \
7225           .quirks = __quirks }
7226
7227 #define TPACPI_FAN_QL(__id1, __id2, __quirks)   \
7228         { .vendor = PCI_VENDOR_ID_LENOVO,       \
7229           .bios = TPACPI_MATCH_ANY,             \
7230           .ec = TPID(__id1, __id2),             \
7231           .quirks = __quirks }
7232
7233 static const struct tpacpi_quirk fan_quirk_table[] __initconst = {
7234         TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1),
7235         TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1),
7236         TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1),
7237         TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1),
7238         TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN),
7239 };
7240
7241 #undef TPACPI_FAN_QL
7242 #undef TPACPI_FAN_QI
7243
7244 static int __init fan_init(struct ibm_init_struct *iibm)
7245 {
7246         int rc;
7247         unsigned long quirks;
7248
7249         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7250                         "initializing fan subdriver\n");
7251
7252         mutex_init(&fan_mutex);
7253         fan_status_access_mode = TPACPI_FAN_NONE;
7254         fan_control_access_mode = TPACPI_FAN_WR_NONE;
7255         fan_control_commands = 0;
7256         fan_watchdog_maxinterval = 0;
7257         tp_features.fan_ctrl_status_undef = 0;
7258         tp_features.second_fan = 0;
7259         fan_control_desired_level = 7;
7260
7261         TPACPI_ACPIHANDLE_INIT(fans);
7262         TPACPI_ACPIHANDLE_INIT(gfan);
7263         TPACPI_ACPIHANDLE_INIT(sfan);
7264
7265         quirks = tpacpi_check_quirks(fan_quirk_table,
7266                                      ARRAY_SIZE(fan_quirk_table));
7267
7268         if (gfan_handle) {
7269                 /* 570, 600e/x, 770e, 770x */
7270                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
7271         } else {
7272                 /* all other ThinkPads: note that even old-style
7273                  * ThinkPad ECs supports the fan control register */
7274                 if (likely(acpi_ec_read(fan_status_offset,
7275                                         &fan_control_initial_status))) {
7276                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
7277                         if (quirks & TPACPI_FAN_Q1)
7278                                 fan_quirk1_setup();
7279                         if (quirks & TPACPI_FAN_2FAN) {
7280                                 tp_features.second_fan = 1;
7281                                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7282                                         "secondary fan support enabled\n");
7283                         }
7284                 } else {
7285                         printk(TPACPI_ERR
7286                                "ThinkPad ACPI EC access misbehaving, "
7287                                "fan status and control unavailable\n");
7288                         return 1;
7289                 }
7290         }
7291
7292         if (sfan_handle) {
7293                 /* 570, 770x-JL */
7294                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
7295                 fan_control_commands |=
7296                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
7297         } else {
7298                 if (!gfan_handle) {
7299                         /* gfan without sfan means no fan control */
7300                         /* all other models implement TP EC 0x2f control */
7301
7302                         if (fans_handle) {
7303                                 /* X31, X40, X41 */
7304                                 fan_control_access_mode =
7305                                     TPACPI_FAN_WR_ACPI_FANS;
7306                                 fan_control_commands |=
7307                                     TPACPI_FAN_CMD_SPEED |
7308                                     TPACPI_FAN_CMD_LEVEL |
7309                                     TPACPI_FAN_CMD_ENABLE;
7310                         } else {
7311                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
7312                                 fan_control_commands |=
7313                                     TPACPI_FAN_CMD_LEVEL |
7314                                     TPACPI_FAN_CMD_ENABLE;
7315                         }
7316                 }
7317         }
7318
7319         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7320                 "fan is %s, modes %d, %d\n",
7321                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
7322                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
7323                 fan_status_access_mode, fan_control_access_mode);
7324
7325         /* fan control master switch */
7326         if (!fan_control_allowed) {
7327                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
7328                 fan_control_commands = 0;
7329                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7330                            "fan control features disabled by parameter\n");
7331         }
7332
7333         /* update fan_control_desired_level */
7334         if (fan_status_access_mode != TPACPI_FAN_NONE)
7335                 fan_get_status_safe(NULL);
7336
7337         if (fan_status_access_mode != TPACPI_FAN_NONE ||
7338             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
7339                 if (tp_features.second_fan) {
7340                         /* attach second fan tachometer */
7341                         fan_attributes[ARRAY_SIZE(fan_attributes)-2] =
7342                                         &dev_attr_fan_fan2_input.attr;
7343                 }
7344                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
7345                                          &fan_attr_group);
7346                 if (rc < 0)
7347                         return rc;
7348
7349                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
7350                                         &driver_attr_fan_watchdog);
7351                 if (rc < 0) {
7352                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
7353                                         &fan_attr_group);
7354                         return rc;
7355                 }
7356                 return 0;
7357         } else
7358                 return 1;
7359 }
7360
7361 static void fan_exit(void)
7362 {
7363         vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN,
7364                     "cancelling any pending fan watchdog tasks\n");
7365
7366         /* FIXME: can we really do this unconditionally? */
7367         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
7368         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
7369                            &driver_attr_fan_watchdog);
7370
7371         cancel_delayed_work(&fan_watchdog_task);
7372         flush_workqueue(tpacpi_wq);
7373 }
7374
7375 static void fan_suspend(pm_message_t state)
7376 {
7377         int rc;
7378
7379         if (!fan_control_allowed)
7380                 return;
7381
7382         /* Store fan status in cache */
7383         fan_control_resume_level = 0;
7384         rc = fan_get_status_safe(&fan_control_resume_level);
7385         if (rc < 0)
7386                 printk(TPACPI_NOTICE
7387                         "failed to read fan level for later "
7388                         "restore during resume: %d\n", rc);
7389
7390         /* if it is undefined, don't attempt to restore it.
7391          * KEEP THIS LAST */
7392         if (tp_features.fan_ctrl_status_undef)
7393                 fan_control_resume_level = 0;
7394 }
7395
7396 static void fan_resume(void)
7397 {
7398         u8 current_level = 7;
7399         bool do_set = false;
7400         int rc;
7401
7402         /* DSDT *always* updates status on resume */
7403         tp_features.fan_ctrl_status_undef = 0;
7404
7405         if (!fan_control_allowed ||
7406             !fan_control_resume_level ||
7407             (fan_get_status_safe(&current_level) < 0))
7408                 return;
7409
7410         switch (fan_control_access_mode) {
7411         case TPACPI_FAN_WR_ACPI_SFAN:
7412                 /* never decrease fan level */
7413                 do_set = (fan_control_resume_level > current_level);
7414                 break;
7415         case TPACPI_FAN_WR_ACPI_FANS:
7416         case TPACPI_FAN_WR_TPEC:
7417                 /* never decrease fan level, scale is:
7418                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
7419                  *
7420                  * We expect the firmware to set either 7 or AUTO, but we
7421                  * handle FULLSPEED out of paranoia.
7422                  *
7423                  * So, we can safely only restore FULLSPEED or 7, anything
7424                  * else could slow the fan.  Restoring AUTO is useless, at
7425                  * best that's exactly what the DSDT already set (it is the
7426                  * slower it uses).
7427                  *
7428                  * Always keep in mind that the DSDT *will* have set the
7429                  * fans to what the vendor supposes is the best level.  We
7430                  * muck with it only to speed the fan up.
7431                  */
7432                 if (fan_control_resume_level != 7 &&
7433                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
7434                         return;
7435                 else
7436                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
7437                                  (current_level != fan_control_resume_level);
7438                 break;
7439         default:
7440                 return;
7441         }
7442         if (do_set) {
7443                 printk(TPACPI_NOTICE
7444                         "restoring fan level to 0x%02x\n",
7445                         fan_control_resume_level);
7446                 rc = fan_set_level_safe(fan_control_resume_level);
7447                 if (rc < 0)
7448                         printk(TPACPI_NOTICE
7449                                 "failed to restore fan level: %d\n", rc);
7450         }
7451 }
7452
7453 static int fan_read(char *p)
7454 {
7455         int len = 0;
7456         int rc;
7457         u8 status;
7458         unsigned int speed = 0;
7459
7460         switch (fan_status_access_mode) {
7461         case TPACPI_FAN_RD_ACPI_GFAN:
7462                 /* 570, 600e/x, 770e, 770x */
7463                 rc = fan_get_status_safe(&status);
7464                 if (rc < 0)
7465                         return rc;
7466
7467                 len += sprintf(p + len, "status:\t\t%s\n"
7468                                "level:\t\t%d\n",
7469                                (status != 0) ? "enabled" : "disabled", status);
7470                 break;
7471
7472         case TPACPI_FAN_RD_TPEC:
7473                 /* all except 570, 600e/x, 770e, 770x */
7474                 rc = fan_get_status_safe(&status);
7475                 if (rc < 0)
7476                         return rc;
7477
7478                 len += sprintf(p + len, "status:\t\t%s\n",
7479                                (status != 0) ? "enabled" : "disabled");
7480
7481                 rc = fan_get_speed(&speed);
7482                 if (rc < 0)
7483                         return rc;
7484
7485                 len += sprintf(p + len, "speed:\t\t%d\n", speed);
7486
7487                 if (status & TP_EC_FAN_FULLSPEED)
7488                         /* Disengaged mode takes precedence */
7489                         len += sprintf(p + len, "level:\t\tdisengaged\n");
7490                 else if (status & TP_EC_FAN_AUTO)
7491                         len += sprintf(p + len, "level:\t\tauto\n");
7492                 else
7493                         len += sprintf(p + len, "level:\t\t%d\n", status);
7494                 break;
7495
7496         case TPACPI_FAN_NONE:
7497         default:
7498                 len += sprintf(p + len, "status:\t\tnot supported\n");
7499         }
7500
7501         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
7502                 len += sprintf(p + len, "commands:\tlevel <level>");
7503
7504                 switch (fan_control_access_mode) {
7505                 case TPACPI_FAN_WR_ACPI_SFAN:
7506                         len += sprintf(p + len, " (<level> is 0-7)\n");
7507                         break;
7508
7509                 default:
7510                         len += sprintf(p + len, " (<level> is 0-7, "
7511                                        "auto, disengaged, full-speed)\n");
7512                         break;
7513                 }
7514         }
7515
7516         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
7517                 len += sprintf(p + len, "commands:\tenable, disable\n"
7518                                "commands:\twatchdog <timeout> (<timeout> "
7519                                "is 0 (off), 1-120 (seconds))\n");
7520
7521         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
7522                 len += sprintf(p + len, "commands:\tspeed <speed>"
7523                                " (<speed> is 0-65535)\n");
7524
7525         return len;
7526 }
7527
7528 static int fan_write_cmd_level(const char *cmd, int *rc)
7529 {
7530         int level;
7531
7532         if (strlencmp(cmd, "level auto") == 0)
7533                 level = TP_EC_FAN_AUTO;
7534         else if ((strlencmp(cmd, "level disengaged") == 0) |
7535                         (strlencmp(cmd, "level full-speed") == 0))
7536                 level = TP_EC_FAN_FULLSPEED;
7537         else if (sscanf(cmd, "level %d", &level) != 1)
7538                 return 0;
7539
7540         *rc = fan_set_level_safe(level);
7541         if (*rc == -ENXIO)
7542                 printk(TPACPI_ERR "level command accepted for unsupported "
7543                        "access mode %d", fan_control_access_mode);
7544         else if (!*rc)
7545                 tpacpi_disclose_usertask("procfs fan",
7546                         "set level to %d\n", level);
7547
7548         return 1;
7549 }
7550
7551 static int fan_write_cmd_enable(const char *cmd, int *rc)
7552 {
7553         if (strlencmp(cmd, "enable") != 0)
7554                 return 0;
7555
7556         *rc = fan_set_enable();
7557         if (*rc == -ENXIO)
7558                 printk(TPACPI_ERR "enable command accepted for unsupported "
7559                        "access mode %d", fan_control_access_mode);
7560         else if (!*rc)
7561                 tpacpi_disclose_usertask("procfs fan", "enable\n");
7562
7563         return 1;
7564 }
7565
7566 static int fan_write_cmd_disable(const char *cmd, int *rc)
7567 {
7568         if (strlencmp(cmd, "disable") != 0)
7569                 return 0;
7570
7571         *rc = fan_set_disable();
7572         if (*rc == -ENXIO)
7573                 printk(TPACPI_ERR "disable command accepted for unsupported "
7574                        "access mode %d", fan_control_access_mode);
7575         else if (!*rc)
7576                 tpacpi_disclose_usertask("procfs fan", "disable\n");
7577
7578         return 1;
7579 }
7580
7581 static int fan_write_cmd_speed(const char *cmd, int *rc)
7582 {
7583         int speed;
7584
7585         /* TODO:
7586          * Support speed <low> <medium> <high> ? */
7587
7588         if (sscanf(cmd, "speed %d", &speed) != 1)
7589                 return 0;
7590
7591         *rc = fan_set_speed(speed);
7592         if (*rc == -ENXIO)
7593                 printk(TPACPI_ERR "speed command accepted for unsupported "
7594                        "access mode %d", fan_control_access_mode);
7595         else if (!*rc)
7596                 tpacpi_disclose_usertask("procfs fan",
7597                         "set speed to %d\n", speed);
7598
7599         return 1;
7600 }
7601
7602 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
7603 {
7604         int interval;
7605
7606         if (sscanf(cmd, "watchdog %d", &interval) != 1)
7607                 return 0;
7608
7609         if (interval < 0 || interval > 120)
7610                 *rc = -EINVAL;
7611         else {
7612                 fan_watchdog_maxinterval = interval;
7613                 tpacpi_disclose_usertask("procfs fan",
7614                         "set watchdog timer to %d\n",
7615                         interval);
7616         }
7617
7618         return 1;
7619 }
7620
7621 static int fan_write(char *buf)
7622 {
7623         char *cmd;
7624         int rc = 0;
7625
7626         while (!rc && (cmd = next_cmd(&buf))) {
7627                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
7628                       fan_write_cmd_level(cmd, &rc)) &&
7629                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
7630                       (fan_write_cmd_enable(cmd, &rc) ||
7631                        fan_write_cmd_disable(cmd, &rc) ||
7632                        fan_write_cmd_watchdog(cmd, &rc))) &&
7633                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
7634                       fan_write_cmd_speed(cmd, &rc))
7635                     )
7636                         rc = -EINVAL;
7637                 else if (!rc)
7638                         fan_watchdog_reset();
7639         }
7640
7641         return rc;
7642 }
7643
7644 static struct ibm_struct fan_driver_data = {
7645         .name = "fan",
7646         .read = fan_read,
7647         .write = fan_write,
7648         .exit = fan_exit,
7649         .suspend = fan_suspend,
7650         .resume = fan_resume,
7651 };
7652
7653 /****************************************************************************
7654  ****************************************************************************
7655  *
7656  * Infrastructure
7657  *
7658  ****************************************************************************
7659  ****************************************************************************/
7660
7661 /*
7662  * HKEY event callout for other subdrivers go here
7663  * (yes, it is ugly, but it is quick, safe, and gets the job done
7664  */
7665 static void tpacpi_driver_event(const unsigned int hkey_event)
7666 {
7667 }
7668
7669
7670
7671 static void hotkey_driver_event(const unsigned int scancode)
7672 {
7673         tpacpi_driver_event(0x1001 + scancode);
7674 }
7675
7676 /* sysfs name ---------------------------------------------------------- */
7677 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
7678                            struct device_attribute *attr,
7679                            char *buf)
7680 {
7681         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
7682 }
7683
7684 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
7685         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
7686
7687 /* --------------------------------------------------------------------- */
7688
7689 /* /proc support */
7690 static struct proc_dir_entry *proc_dir;
7691
7692 /*
7693  * Module and infrastructure proble, init and exit handling
7694  */
7695
7696 static int force_load;
7697
7698 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
7699 static const char * __init str_supported(int is_supported)
7700 {
7701         static char text_unsupported[] __initdata = "not supported";
7702
7703         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
7704 }
7705 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
7706
7707 static void ibm_exit(struct ibm_struct *ibm)
7708 {
7709         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
7710
7711         list_del_init(&ibm->all_drivers);
7712
7713         if (ibm->flags.acpi_notify_installed) {
7714                 dbg_printk(TPACPI_DBG_EXIT,
7715                         "%s: acpi_remove_notify_handler\n", ibm->name);
7716                 BUG_ON(!ibm->acpi);
7717                 acpi_remove_notify_handler(*ibm->acpi->handle,
7718                                            ibm->acpi->type,
7719                                            dispatch_acpi_notify);
7720                 ibm->flags.acpi_notify_installed = 0;
7721                 ibm->flags.acpi_notify_installed = 0;
7722         }
7723
7724         if (ibm->flags.proc_created) {
7725                 dbg_printk(TPACPI_DBG_EXIT,
7726                         "%s: remove_proc_entry\n", ibm->name);
7727                 remove_proc_entry(ibm->name, proc_dir);
7728                 ibm->flags.proc_created = 0;
7729         }
7730
7731         if (ibm->flags.acpi_driver_registered) {
7732                 dbg_printk(TPACPI_DBG_EXIT,
7733                         "%s: acpi_bus_unregister_driver\n", ibm->name);
7734                 BUG_ON(!ibm->acpi);
7735                 acpi_bus_unregister_driver(ibm->acpi->driver);
7736                 kfree(ibm->acpi->driver);
7737                 ibm->acpi->driver = NULL;
7738                 ibm->flags.acpi_driver_registered = 0;
7739         }
7740
7741         if (ibm->flags.init_called && ibm->exit) {
7742                 ibm->exit();
7743                 ibm->flags.init_called = 0;
7744         }
7745
7746         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
7747 }
7748
7749 static int __init ibm_init(struct ibm_init_struct *iibm)
7750 {
7751         int ret;
7752         struct ibm_struct *ibm = iibm->data;
7753         struct proc_dir_entry *entry;
7754
7755         BUG_ON(ibm == NULL);
7756
7757         INIT_LIST_HEAD(&ibm->all_drivers);
7758
7759         if (ibm->flags.experimental && !experimental)
7760                 return 0;
7761
7762         dbg_printk(TPACPI_DBG_INIT,
7763                 "probing for %s\n", ibm->name);
7764
7765         if (iibm->init) {
7766                 ret = iibm->init(iibm);
7767                 if (ret > 0)
7768                         return 0;       /* probe failed */
7769                 if (ret)
7770                         return ret;
7771
7772                 ibm->flags.init_called = 1;
7773         }
7774
7775         if (ibm->acpi) {
7776                 if (ibm->acpi->hid) {
7777                         ret = register_tpacpi_subdriver(ibm);
7778                         if (ret)
7779                                 goto err_out;
7780                 }
7781
7782                 if (ibm->acpi->notify) {
7783                         ret = setup_acpi_notify(ibm);
7784                         if (ret == -ENODEV) {
7785                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
7786                                         ibm->name);
7787                                 ret = 0;
7788                                 goto err_out;
7789                         }
7790                         if (ret < 0)
7791                                 goto err_out;
7792                 }
7793         }
7794
7795         dbg_printk(TPACPI_DBG_INIT,
7796                 "%s installed\n", ibm->name);
7797
7798         if (ibm->read) {
7799                 entry = create_proc_entry(ibm->name,
7800                                           S_IFREG | S_IRUGO | S_IWUSR,
7801                                           proc_dir);
7802                 if (!entry) {
7803                         printk(TPACPI_ERR "unable to create proc entry %s\n",
7804                                ibm->name);
7805                         ret = -ENODEV;
7806                         goto err_out;
7807                 }
7808                 entry->data = ibm;
7809                 entry->read_proc = &dispatch_procfs_read;
7810                 if (ibm->write)
7811                         entry->write_proc = &dispatch_procfs_write;
7812                 ibm->flags.proc_created = 1;
7813         }
7814
7815         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
7816
7817         return 0;
7818
7819 err_out:
7820         dbg_printk(TPACPI_DBG_INIT,
7821                 "%s: at error exit path with result %d\n",
7822                 ibm->name, ret);
7823
7824         ibm_exit(ibm);
7825         return (ret < 0)? ret : 0;
7826 }
7827
7828 /* Probing */
7829
7830 static bool __pure __init tpacpi_is_fw_digit(const char c)
7831 {
7832         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z');
7833 }
7834
7835 /* Most models: xxyTkkWW (#.##c); Ancient 570/600 and -SL lacks (#.##c) */
7836 static bool __pure __init tpacpi_is_valid_fw_id(const char* const s,
7837                                                 const char t)
7838 {
7839         return s && strlen(s) >= 8 &&
7840                 tpacpi_is_fw_digit(s[0]) &&
7841                 tpacpi_is_fw_digit(s[1]) &&
7842                 s[2] == t && s[3] == 'T' &&
7843                 tpacpi_is_fw_digit(s[4]) &&
7844                 tpacpi_is_fw_digit(s[5]) &&
7845                 s[6] == 'W' && s[7] == 'W';
7846 }
7847
7848 /* returns 0 - probe ok, or < 0 - probe error.
7849  * Probe ok doesn't mean thinkpad found.
7850  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
7851 static int __must_check __init get_thinkpad_model_data(
7852                                                 struct thinkpad_id_data *tp)
7853 {
7854         const struct dmi_device *dev = NULL;
7855         char ec_fw_string[18];
7856         char const *s;
7857
7858         if (!tp)
7859                 return -EINVAL;
7860
7861         memset(tp, 0, sizeof(*tp));
7862
7863         if (dmi_name_in_vendors("IBM"))
7864                 tp->vendor = PCI_VENDOR_ID_IBM;
7865         else if (dmi_name_in_vendors("LENOVO"))
7866                 tp->vendor = PCI_VENDOR_ID_LENOVO;
7867         else
7868                 return 0;
7869
7870         s = dmi_get_system_info(DMI_BIOS_VERSION);
7871         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
7872         if (s && !tp->bios_version_str)
7873                 return -ENOMEM;
7874
7875         /* Really ancient ThinkPad 240X will fail this, which is fine */
7876         if (!tpacpi_is_valid_fw_id(tp->bios_version_str, 'E'))
7877                 return 0;
7878
7879         tp->bios_model = tp->bios_version_str[0]
7880                          | (tp->bios_version_str[1] << 8);
7881         tp->bios_release = (tp->bios_version_str[4] << 8)
7882                          | tp->bios_version_str[5];
7883
7884         /*
7885          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
7886          * X32 or newer, all Z series;  Some models must have an
7887          * up-to-date BIOS or they will not be detected.
7888          *
7889          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
7890          */
7891         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
7892                 if (sscanf(dev->name,
7893                            "IBM ThinkPad Embedded Controller -[%17c",
7894                            ec_fw_string) == 1) {
7895                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
7896                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
7897
7898                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
7899                         if (!tp->ec_version_str)
7900                                 return -ENOMEM;
7901
7902                         if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) {
7903                                 tp->ec_model = ec_fw_string[0]
7904                                                 | (ec_fw_string[1] << 8);
7905                                 tp->ec_release = (ec_fw_string[4] << 8)
7906                                                 | ec_fw_string[5];
7907                         } else {
7908                                 printk(TPACPI_NOTICE
7909                                         "ThinkPad firmware release %s "
7910                                         "doesn't match the known patterns\n",
7911                                         ec_fw_string);
7912                                 printk(TPACPI_NOTICE
7913                                         "please report this to %s\n",
7914                                         TPACPI_MAIL);
7915                         }
7916                         break;
7917                 }
7918         }
7919
7920         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
7921         if (s && !strnicmp(s, "ThinkPad", 8)) {
7922                 tp->model_str = kstrdup(s, GFP_KERNEL);
7923                 if (!tp->model_str)
7924                         return -ENOMEM;
7925         }
7926
7927         s = dmi_get_system_info(DMI_PRODUCT_NAME);
7928         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
7929         if (s && !tp->nummodel_str)
7930                 return -ENOMEM;
7931
7932         return 0;
7933 }
7934
7935 static int __init probe_for_thinkpad(void)
7936 {
7937         int is_thinkpad;
7938
7939         if (acpi_disabled)
7940                 return -ENODEV;
7941
7942         /*
7943          * Non-ancient models have better DMI tagging, but very old models
7944          * don't.  tpacpi_is_fw_known() is a cheat to help in that case.
7945          */
7946         is_thinkpad = (thinkpad_id.model_str != NULL) ||
7947                       (thinkpad_id.ec_model != 0) ||
7948                       tpacpi_is_fw_known();
7949
7950         /* ec is required because many other handles are relative to it */
7951         TPACPI_ACPIHANDLE_INIT(ec);
7952         if (!ec_handle) {
7953                 if (is_thinkpad)
7954                         printk(TPACPI_ERR
7955                                 "Not yet supported ThinkPad detected!\n");
7956                 return -ENODEV;
7957         }
7958
7959         if (!is_thinkpad && !force_load)
7960                 return -ENODEV;
7961
7962         return 0;
7963 }
7964
7965
7966 /* Module init, exit, parameters */
7967
7968 static struct ibm_init_struct ibms_init[] __initdata = {
7969         {
7970                 .init = thinkpad_acpi_driver_init,
7971                 .data = &thinkpad_acpi_driver_data,
7972         },
7973         {
7974                 .init = hotkey_init,
7975                 .data = &hotkey_driver_data,
7976         },
7977         {
7978                 .init = bluetooth_init,
7979                 .data = &bluetooth_driver_data,
7980         },
7981         {
7982                 .init = wan_init,
7983                 .data = &wan_driver_data,
7984         },
7985         {
7986                 .init = uwb_init,
7987                 .data = &uwb_driver_data,
7988         },
7989 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
7990         {
7991                 .init = video_init,
7992                 .data = &video_driver_data,
7993         },
7994 #endif
7995         {
7996                 .init = light_init,
7997                 .data = &light_driver_data,
7998         },
7999         {
8000                 .init = cmos_init,
8001                 .data = &cmos_driver_data,
8002         },
8003         {
8004                 .init = led_init,
8005                 .data = &led_driver_data,
8006         },
8007         {
8008                 .init = beep_init,
8009                 .data = &beep_driver_data,
8010         },
8011         {
8012                 .init = thermal_init,
8013                 .data = &thermal_driver_data,
8014         },
8015         {
8016                 .data = &ecdump_driver_data,
8017         },
8018         {
8019                 .init = brightness_init,
8020                 .data = &brightness_driver_data,
8021         },
8022         {
8023                 .data = &volume_driver_data,
8024         },
8025         {
8026                 .init = fan_init,
8027                 .data = &fan_driver_data,
8028         },
8029 };
8030
8031 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
8032 {
8033         unsigned int i;
8034         struct ibm_struct *ibm;
8035
8036         if (!kp || !kp->name || !val)
8037                 return -EINVAL;
8038
8039         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
8040                 ibm = ibms_init[i].data;
8041                 WARN_ON(ibm == NULL);
8042
8043                 if (!ibm || !ibm->name)
8044                         continue;
8045
8046                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
8047                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
8048                                 return -ENOSPC;
8049                         strcpy(ibms_init[i].param, val);
8050                         strcat(ibms_init[i].param, ",");
8051                         return 0;
8052                 }
8053         }
8054
8055         return -EINVAL;
8056 }
8057
8058 module_param(experimental, int, 0);
8059 MODULE_PARM_DESC(experimental,
8060                  "Enables experimental features when non-zero");
8061
8062 module_param_named(debug, dbg_level, uint, 0);
8063 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
8064
8065 module_param(force_load, bool, 0);
8066 MODULE_PARM_DESC(force_load,
8067                  "Attempts to load the driver even on a "
8068                  "mis-identified ThinkPad when true");
8069
8070 module_param_named(fan_control, fan_control_allowed, bool, 0);
8071 MODULE_PARM_DESC(fan_control,
8072                  "Enables setting fan parameters features when true");
8073
8074 module_param_named(brightness_mode, brightness_mode, uint, 0);
8075 MODULE_PARM_DESC(brightness_mode,
8076                  "Selects brightness control strategy: "
8077                  "0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM");
8078
8079 module_param(brightness_enable, uint, 0);
8080 MODULE_PARM_DESC(brightness_enable,
8081                  "Enables backlight control when 1, disables when 0");
8082
8083 module_param(hotkey_report_mode, uint, 0);
8084 MODULE_PARM_DESC(hotkey_report_mode,
8085                  "used for backwards compatibility with userspace, "
8086                  "see documentation");
8087
8088 #define TPACPI_PARAM(feature) \
8089         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
8090         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
8091                          "at module load, see documentation")
8092
8093 TPACPI_PARAM(hotkey);
8094 TPACPI_PARAM(bluetooth);
8095 TPACPI_PARAM(video);
8096 TPACPI_PARAM(light);
8097 TPACPI_PARAM(cmos);
8098 TPACPI_PARAM(led);
8099 TPACPI_PARAM(beep);
8100 TPACPI_PARAM(ecdump);
8101 TPACPI_PARAM(brightness);
8102 TPACPI_PARAM(volume);
8103 TPACPI_PARAM(fan);
8104
8105 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
8106 module_param(dbg_wlswemul, uint, 0);
8107 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
8108 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
8109 MODULE_PARM_DESC(wlsw_state,
8110                  "Initial state of the emulated WLSW switch");
8111
8112 module_param(dbg_bluetoothemul, uint, 0);
8113 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
8114 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
8115 MODULE_PARM_DESC(bluetooth_state,
8116                  "Initial state of the emulated bluetooth switch");
8117
8118 module_param(dbg_wwanemul, uint, 0);
8119 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
8120 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
8121 MODULE_PARM_DESC(wwan_state,
8122                  "Initial state of the emulated WWAN switch");
8123
8124 module_param(dbg_uwbemul, uint, 0);
8125 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
8126 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
8127 MODULE_PARM_DESC(uwb_state,
8128                  "Initial state of the emulated UWB switch");
8129 #endif
8130
8131 static void thinkpad_acpi_module_exit(void)
8132 {
8133         struct ibm_struct *ibm, *itmp;
8134
8135         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
8136
8137         list_for_each_entry_safe_reverse(ibm, itmp,
8138                                          &tpacpi_all_drivers,
8139                                          all_drivers) {
8140                 ibm_exit(ibm);
8141         }
8142
8143         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
8144
8145         if (tpacpi_inputdev) {
8146                 if (tp_features.input_device_registered)
8147                         input_unregister_device(tpacpi_inputdev);
8148                 else
8149                         input_free_device(tpacpi_inputdev);
8150         }
8151
8152         if (tpacpi_hwmon)
8153                 hwmon_device_unregister(tpacpi_hwmon);
8154
8155         if (tp_features.sensors_pdev_attrs_registered)
8156                 device_remove_file(&tpacpi_sensors_pdev->dev,
8157                                    &dev_attr_thinkpad_acpi_pdev_name);
8158         if (tpacpi_sensors_pdev)
8159                 platform_device_unregister(tpacpi_sensors_pdev);
8160         if (tpacpi_pdev)
8161                 platform_device_unregister(tpacpi_pdev);
8162
8163         if (tp_features.sensors_pdrv_attrs_registered)
8164                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
8165         if (tp_features.platform_drv_attrs_registered)
8166                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
8167
8168         if (tp_features.sensors_pdrv_registered)
8169                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
8170
8171         if (tp_features.platform_drv_registered)
8172                 platform_driver_unregister(&tpacpi_pdriver);
8173
8174         if (proc_dir)
8175                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
8176
8177         if (tpacpi_wq)
8178                 destroy_workqueue(tpacpi_wq);
8179
8180         kfree(thinkpad_id.bios_version_str);
8181         kfree(thinkpad_id.ec_version_str);
8182         kfree(thinkpad_id.model_str);
8183 }
8184
8185
8186 static int __init thinkpad_acpi_module_init(void)
8187 {
8188         int ret, i;
8189
8190         tpacpi_lifecycle = TPACPI_LIFE_INIT;
8191
8192         /* Parameter checking */
8193         if (hotkey_report_mode > 2)
8194                 return -EINVAL;
8195
8196         /* Driver-level probe */
8197
8198         ret = get_thinkpad_model_data(&thinkpad_id);
8199         if (ret) {
8200                 printk(TPACPI_ERR
8201                         "unable to get DMI data: %d\n", ret);
8202                 thinkpad_acpi_module_exit();
8203                 return ret;
8204         }
8205         ret = probe_for_thinkpad();
8206         if (ret) {
8207                 thinkpad_acpi_module_exit();
8208                 return ret;
8209         }
8210
8211         /* Driver initialization */
8212
8213         TPACPI_ACPIHANDLE_INIT(ecrd);
8214         TPACPI_ACPIHANDLE_INIT(ecwr);
8215
8216         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
8217         if (!tpacpi_wq) {
8218                 thinkpad_acpi_module_exit();
8219                 return -ENOMEM;
8220         }
8221
8222         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
8223         if (!proc_dir) {
8224                 printk(TPACPI_ERR
8225                        "unable to create proc dir " TPACPI_PROC_DIR);
8226                 thinkpad_acpi_module_exit();
8227                 return -ENODEV;
8228         }
8229
8230         ret = platform_driver_register(&tpacpi_pdriver);
8231         if (ret) {
8232                 printk(TPACPI_ERR
8233                        "unable to register main platform driver\n");
8234                 thinkpad_acpi_module_exit();
8235                 return ret;
8236         }
8237         tp_features.platform_drv_registered = 1;
8238
8239         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
8240         if (ret) {
8241                 printk(TPACPI_ERR
8242                        "unable to register hwmon platform driver\n");
8243                 thinkpad_acpi_module_exit();
8244                 return ret;
8245         }
8246         tp_features.sensors_pdrv_registered = 1;
8247
8248         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
8249         if (!ret) {
8250                 tp_features.platform_drv_attrs_registered = 1;
8251                 ret = tpacpi_create_driver_attributes(
8252                                         &tpacpi_hwmon_pdriver.driver);
8253         }
8254         if (ret) {
8255                 printk(TPACPI_ERR
8256                        "unable to create sysfs driver attributes\n");
8257                 thinkpad_acpi_module_exit();
8258                 return ret;
8259         }
8260         tp_features.sensors_pdrv_attrs_registered = 1;
8261
8262
8263         /* Device initialization */
8264         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
8265                                                         NULL, 0);
8266         if (IS_ERR(tpacpi_pdev)) {
8267                 ret = PTR_ERR(tpacpi_pdev);
8268                 tpacpi_pdev = NULL;
8269                 printk(TPACPI_ERR "unable to register platform device\n");
8270                 thinkpad_acpi_module_exit();
8271                 return ret;
8272         }
8273         tpacpi_sensors_pdev = platform_device_register_simple(
8274                                                 TPACPI_HWMON_DRVR_NAME,
8275                                                 -1, NULL, 0);
8276         if (IS_ERR(tpacpi_sensors_pdev)) {
8277                 ret = PTR_ERR(tpacpi_sensors_pdev);
8278                 tpacpi_sensors_pdev = NULL;
8279                 printk(TPACPI_ERR
8280                        "unable to register hwmon platform device\n");
8281                 thinkpad_acpi_module_exit();
8282                 return ret;
8283         }
8284         ret = device_create_file(&tpacpi_sensors_pdev->dev,
8285                                  &dev_attr_thinkpad_acpi_pdev_name);
8286         if (ret) {
8287                 printk(TPACPI_ERR
8288                        "unable to create sysfs hwmon device attributes\n");
8289                 thinkpad_acpi_module_exit();
8290                 return ret;
8291         }
8292         tp_features.sensors_pdev_attrs_registered = 1;
8293         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
8294         if (IS_ERR(tpacpi_hwmon)) {
8295                 ret = PTR_ERR(tpacpi_hwmon);
8296                 tpacpi_hwmon = NULL;
8297                 printk(TPACPI_ERR "unable to register hwmon device\n");
8298                 thinkpad_acpi_module_exit();
8299                 return ret;
8300         }
8301         mutex_init(&tpacpi_inputdev_send_mutex);
8302         tpacpi_inputdev = input_allocate_device();
8303         if (!tpacpi_inputdev) {
8304                 printk(TPACPI_ERR "unable to allocate input device\n");
8305                 thinkpad_acpi_module_exit();
8306                 return -ENOMEM;
8307         } else {
8308                 /* Prepare input device, but don't register */
8309                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
8310                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
8311                 tpacpi_inputdev->id.bustype = BUS_HOST;
8312                 tpacpi_inputdev->id.vendor = (thinkpad_id.vendor) ?
8313                                                 thinkpad_id.vendor :
8314                                                 PCI_VENDOR_ID_IBM;
8315                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
8316                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
8317         }
8318         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
8319                 ret = ibm_init(&ibms_init[i]);
8320                 if (ret >= 0 && *ibms_init[i].param)
8321                         ret = ibms_init[i].data->write(ibms_init[i].param);
8322                 if (ret < 0) {
8323                         thinkpad_acpi_module_exit();
8324                         return ret;
8325                 }
8326         }
8327         ret = input_register_device(tpacpi_inputdev);
8328         if (ret < 0) {
8329                 printk(TPACPI_ERR "unable to register input device\n");
8330                 thinkpad_acpi_module_exit();
8331                 return ret;
8332         } else {
8333                 tp_features.input_device_registered = 1;
8334         }
8335
8336         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
8337         return 0;
8338 }
8339
8340 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
8341
8342 /*
8343  * This will autoload the driver in almost every ThinkPad
8344  * in widespread use.
8345  *
8346  * Only _VERY_ old models, like the 240, 240x and 570 lack
8347  * the HKEY event interface.
8348  */
8349 MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids);
8350
8351 /*
8352  * DMI matching for module autoloading
8353  *
8354  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
8355  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
8356  *
8357  * Only models listed in thinkwiki will be supported, so add yours
8358  * if it is not there yet.
8359  */
8360 #define IBM_BIOS_MODULE_ALIAS(__type) \
8361         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*")
8362
8363 /* Ancient thinkpad BIOSes have to be identified by
8364  * BIOS type or model number, and there are far less
8365  * BIOS types than model numbers... */
8366 IBM_BIOS_MODULE_ALIAS("I[MU]");         /* 570, 570e */
8367
8368 MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>");
8369 MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>");
8370 MODULE_DESCRIPTION(TPACPI_DESC);
8371 MODULE_VERSION(TPACPI_VERSION);
8372 MODULE_LICENSE("GPL");
8373
8374 module_init(thinkpad_acpi_module_init);
8375 module_exit(thinkpad_acpi_module_exit);