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