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