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