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