]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/platform/x86/thinkpad_acpi.c
c1d40410ad794ec353eca3f1d819e5a187337604
[linux-2.6-omap-h63xx.git] / drivers / platform / x86 / thinkpad_acpi.c
1 /*
2  *  thinkpad_acpi.c - ThinkPad ACPI Extras
3  *
4  *
5  *  Copyright (C) 2004-2005 Borislav Deianov <borislav@users.sf.net>
6  *  Copyright (C) 2006-2008 Henrique de Moraes Holschuh <hmh@hmh.eng.br>
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  *  02110-1301, USA.
22  */
23
24 #define TPACPI_VERSION "0.21"
25 #define TPACPI_SYSFS_VERSION 0x020200
26
27 /*
28  *  Changelog:
29  *  2007-10-20          changelog trimmed down
30  *
31  *  2007-03-27  0.14    renamed to thinkpad_acpi and moved to
32  *                      drivers/misc.
33  *
34  *  2006-11-22  0.13    new maintainer
35  *                      changelog now lives in git commit history, and will
36  *                      not be updated further in-file.
37  *
38  *  2005-03-17  0.11    support for 600e, 770x
39  *                          thanks to Jamie Lentin <lentinj@dial.pipex.com>
40  *
41  *  2005-01-16  0.9     use MODULE_VERSION
42  *                          thanks to Henrik Brix Andersen <brix@gentoo.org>
43  *                      fix parameter passing on module loading
44  *                          thanks to Rusty Russell <rusty@rustcorp.com.au>
45  *                          thanks to Jim Radford <radford@blackbean.org>
46  *  2004-11-08  0.8     fix init error case, don't return from a macro
47  *                          thanks to Chris Wright <chrisw@osdl.org>
48  */
49
50 #include <linux/kernel.h>
51 #include <linux/module.h>
52 #include <linux/init.h>
53 #include <linux/types.h>
54 #include <linux/string.h>
55 #include <linux/list.h>
56 #include <linux/mutex.h>
57 #include <linux/kthread.h>
58 #include <linux/freezer.h>
59 #include <linux/delay.h>
60
61 #include <linux/nvram.h>
62 #include <linux/proc_fs.h>
63 #include <linux/sysfs.h>
64 #include <linux/backlight.h>
65 #include <linux/fb.h>
66 #include <linux/platform_device.h>
67 #include <linux/hwmon.h>
68 #include <linux/hwmon-sysfs.h>
69 #include <linux/input.h>
70 #include <linux/leds.h>
71 #include <linux/rfkill.h>
72 #include <asm/uaccess.h>
73
74 #include <linux/dmi.h>
75 #include <linux/jiffies.h>
76 #include <linux/workqueue.h>
77
78 #include <acpi/acpi_drivers.h>
79
80 #include <linux/pci_ids.h>
81
82
83 /* ThinkPad CMOS commands */
84 #define TP_CMOS_VOLUME_DOWN     0
85 #define TP_CMOS_VOLUME_UP       1
86 #define TP_CMOS_VOLUME_MUTE     2
87 #define TP_CMOS_BRIGHTNESS_UP   4
88 #define TP_CMOS_BRIGHTNESS_DOWN 5
89 #define TP_CMOS_THINKLIGHT_ON   12
90 #define TP_CMOS_THINKLIGHT_OFF  13
91
92 /* NVRAM Addresses */
93 enum tp_nvram_addr {
94         TP_NVRAM_ADDR_HK2               = 0x57,
95         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
96         TP_NVRAM_ADDR_VIDEO             = 0x59,
97         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
98         TP_NVRAM_ADDR_MIXER             = 0x60,
99 };
100
101 /* NVRAM bit masks */
102 enum {
103         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
104         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
105         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
106         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
107         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
108         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
109         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
110         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
111         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
112         TP_NVRAM_MASK_MUTE              = 0x40,
113         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
114         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
115         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
116 };
117
118 /* ACPI HIDs */
119 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
120
121 /* Input IDs */
122 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
123 #define TPACPI_HKEY_INPUT_VERSION       0x4101
124
125 /* ACPI \WGSV commands */
126 enum {
127         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
128         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
129         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
130         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
131 };
132
133 /* TP_ACPI_WGSV_GET_STATE bits */
134 enum {
135         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
136         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
137         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
138         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
139         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
140         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
141         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
142         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
143         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
144         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
145 };
146
147 /****************************************************************************
148  * Main driver
149  */
150
151 #define TPACPI_NAME "thinkpad"
152 #define TPACPI_DESC "ThinkPad ACPI Extras"
153 #define TPACPI_FILE TPACPI_NAME "_acpi"
154 #define TPACPI_URL "http://ibm-acpi.sf.net/"
155 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
156
157 #define TPACPI_PROC_DIR "ibm"
158 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
159 #define TPACPI_DRVR_NAME TPACPI_FILE
160 #define TPACPI_DRVR_SHORTNAME "tpacpi"
161 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
162
163 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
164 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
165
166 #define TPACPI_MAX_ACPI_ARGS 3
167
168 /* rfkill switches */
169 enum {
170         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
171         TPACPI_RFK_WWAN_SW_ID,
172         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_interruptible(&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_interruptible(&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_interruptible(&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_interruptible(&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 void hotkey_notify(struct ibm_struct *ibm, u32 event)
2575 {
2576         u32 hkey;
2577         unsigned int scancode;
2578         int send_acpi_ev;
2579         int ignore_acpi_ev;
2580         int unk_ev;
2581
2582         if (event != 0x80) {
2583                 printk(TPACPI_ERR
2584                        "unknown HKEY notification event %d\n", event);
2585                 /* forward it to userspace, maybe it knows how to handle it */
2586                 acpi_bus_generate_netlink_event(
2587                                         ibm->acpi->device->pnp.device_class,
2588                                         dev_name(&ibm->acpi->device->dev),
2589                                         event, 0);
2590                 return;
2591         }
2592
2593         while (1) {
2594                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
2595                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
2596                         return;
2597                 }
2598
2599                 if (hkey == 0) {
2600                         /* queue empty */
2601                         return;
2602                 }
2603
2604                 send_acpi_ev = 1;
2605                 ignore_acpi_ev = 0;
2606                 unk_ev = 0;
2607
2608                 switch (hkey >> 12) {
2609                 case 1:
2610                         /* 0x1000-0x1FFF: key presses */
2611                         scancode = hkey & 0xfff;
2612                         if (scancode > 0 && scancode < 0x21) {
2613                                 scancode--;
2614                                 if (!(hotkey_source_mask & (1 << scancode))) {
2615                                         tpacpi_input_send_key(scancode);
2616                                         send_acpi_ev = 0;
2617                                 } else {
2618                                         ignore_acpi_ev = 1;
2619                                 }
2620                         } else {
2621                                 unk_ev = 1;
2622                         }
2623                         break;
2624                 case 2:
2625                         /* Wakeup reason */
2626                         switch (hkey) {
2627                         case 0x2304: /* suspend, undock */
2628                         case 0x2404: /* hibernation, undock */
2629                                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
2630                                 ignore_acpi_ev = 1;
2631                                 break;
2632                         case 0x2305: /* suspend, bay eject */
2633                         case 0x2405: /* hibernation, bay eject */
2634                                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
2635                                 ignore_acpi_ev = 1;
2636                                 break;
2637                         default:
2638                                 unk_ev = 1;
2639                         }
2640                         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
2641                                 printk(TPACPI_INFO
2642                                        "woke up due to a hot-unplug "
2643                                        "request...\n");
2644                                 hotkey_wakeup_reason_notify_change();
2645                         }
2646                         break;
2647                 case 3:
2648                         /* bay-related wakeups */
2649                         if (hkey == 0x3003) {
2650                                 hotkey_autosleep_ack = 1;
2651                                 printk(TPACPI_INFO
2652                                        "bay ejected\n");
2653                                 hotkey_wakeup_hotunplug_complete_notify_change();
2654                         } else {
2655                                 unk_ev = 1;
2656                         }
2657                         break;
2658                 case 4:
2659                         /* dock-related wakeups */
2660                         if (hkey == 0x4003) {
2661                                 hotkey_autosleep_ack = 1;
2662                                 printk(TPACPI_INFO
2663                                        "undocked\n");
2664                                 hotkey_wakeup_hotunplug_complete_notify_change();
2665                         } else {
2666                                 unk_ev = 1;
2667                         }
2668                         break;
2669                 case 5:
2670                         /* 0x5000-0x5FFF: human interface helpers */
2671                         switch (hkey) {
2672                         case 0x5010: /* Lenovo new BIOS: brightness changed */
2673                         case 0x500b: /* X61t: tablet pen inserted into bay */
2674                         case 0x500c: /* X61t: tablet pen removed from bay */
2675                                 break;
2676                         case 0x5009: /* X41t-X61t: swivel up (tablet mode) */
2677                         case 0x500a: /* X41t-X61t: swivel down (normal mode) */
2678                                 tpacpi_input_send_tabletsw();
2679                                 hotkey_tablet_mode_notify_change();
2680                                 send_acpi_ev = 0;
2681                                 break;
2682                         case 0x5001:
2683                         case 0x5002:
2684                                 /* LID switch events.  Do not propagate */
2685                                 ignore_acpi_ev = 1;
2686                                 break;
2687                         default:
2688                                 unk_ev = 1;
2689                         }
2690                         break;
2691                 case 7:
2692                         /* 0x7000-0x7FFF: misc */
2693                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
2694                                 tpacpi_send_radiosw_update();
2695                                 send_acpi_ev = 0;
2696                                 break;
2697                         }
2698                         /* fallthrough to default */
2699                 default:
2700                         unk_ev = 1;
2701                 }
2702                 if (unk_ev) {
2703                         printk(TPACPI_NOTICE
2704                                "unhandled HKEY event 0x%04x\n", hkey);
2705                 }
2706
2707                 /* Legacy events */
2708                 if (!ignore_acpi_ev &&
2709                     (send_acpi_ev || hotkey_report_mode < 2)) {
2710                         acpi_bus_generate_proc_event(ibm->acpi->device,
2711                                                      event, hkey);
2712                 }
2713
2714                 /* netlink events */
2715                 if (!ignore_acpi_ev && send_acpi_ev) {
2716                         acpi_bus_generate_netlink_event(
2717                                         ibm->acpi->device->pnp.device_class,
2718                                         dev_name(&ibm->acpi->device->dev),
2719                                         event, hkey);
2720                 }
2721         }
2722 }
2723
2724 static void hotkey_suspend(pm_message_t state)
2725 {
2726         /* Do these on suspend, we get the events on early resume! */
2727         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
2728         hotkey_autosleep_ack = 0;
2729 }
2730
2731 static void hotkey_resume(void)
2732 {
2733         tpacpi_disable_brightness_delay();
2734
2735         if (hotkey_mask_get())
2736                 printk(TPACPI_ERR
2737                        "error while trying to read hot key mask "
2738                        "from firmware\n");
2739         tpacpi_send_radiosw_update();
2740         hotkey_tablet_mode_notify_change();
2741         hotkey_wakeup_reason_notify_change();
2742         hotkey_wakeup_hotunplug_complete_notify_change();
2743         hotkey_poll_setup_safe(0);
2744 }
2745
2746 /* procfs -------------------------------------------------------------- */
2747 static int hotkey_read(char *p)
2748 {
2749         int res, status;
2750         int len = 0;
2751
2752         if (!tp_features.hotkey) {
2753                 len += sprintf(p + len, "status:\t\tnot supported\n");
2754                 return len;
2755         }
2756
2757         if (mutex_lock_interruptible(&hotkey_mutex))
2758                 return -ERESTARTSYS;
2759         res = hotkey_status_get(&status);
2760         if (!res)
2761                 res = hotkey_mask_get();
2762         mutex_unlock(&hotkey_mutex);
2763         if (res)
2764                 return res;
2765
2766         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
2767         if (tp_features.hotkey_mask) {
2768                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_mask);
2769                 len += sprintf(p + len,
2770                                "commands:\tenable, disable, reset, <mask>\n");
2771         } else {
2772                 len += sprintf(p + len, "mask:\t\tnot supported\n");
2773                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
2774         }
2775
2776         return len;
2777 }
2778
2779 static int hotkey_write(char *buf)
2780 {
2781         int res, status;
2782         u32 mask;
2783         char *cmd;
2784
2785         if (!tp_features.hotkey)
2786                 return -ENODEV;
2787
2788         if (mutex_lock_interruptible(&hotkey_mutex))
2789                 return -ERESTARTSYS;
2790
2791         status = -1;
2792         mask = hotkey_mask;
2793
2794         res = 0;
2795         while ((cmd = next_cmd(&buf))) {
2796                 if (strlencmp(cmd, "enable") == 0) {
2797                         status = 1;
2798                 } else if (strlencmp(cmd, "disable") == 0) {
2799                         status = 0;
2800                 } else if (strlencmp(cmd, "reset") == 0) {
2801                         status = hotkey_orig_status;
2802                         mask = hotkey_orig_mask;
2803                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
2804                         /* mask set */
2805                 } else if (sscanf(cmd, "%x", &mask) == 1) {
2806                         /* mask set */
2807                 } else {
2808                         res = -EINVAL;
2809                         goto errexit;
2810                 }
2811         }
2812         if (status != -1)
2813                 res = hotkey_status_set(status);
2814
2815         if (!res && mask != hotkey_mask)
2816                 res = hotkey_mask_set(mask);
2817
2818 errexit:
2819         mutex_unlock(&hotkey_mutex);
2820         return res;
2821 }
2822
2823 static const struct acpi_device_id ibm_htk_device_ids[] = {
2824         {TPACPI_ACPI_HKEY_HID, 0},
2825         {"", 0},
2826 };
2827
2828 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
2829         .hid = ibm_htk_device_ids,
2830         .notify = hotkey_notify,
2831         .handle = &hkey_handle,
2832         .type = ACPI_DEVICE_NOTIFY,
2833 };
2834
2835 static struct ibm_struct hotkey_driver_data = {
2836         .name = "hotkey",
2837         .read = hotkey_read,
2838         .write = hotkey_write,
2839         .exit = hotkey_exit,
2840         .resume = hotkey_resume,
2841         .suspend = hotkey_suspend,
2842         .acpi = &ibm_hotkey_acpidriver,
2843 };
2844
2845 /*************************************************************************
2846  * Bluetooth subdriver
2847  */
2848
2849 enum {
2850         /* ACPI GBDC/SBDC bits */
2851         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
2852         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
2853         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
2854                                                    off / last state */
2855 };
2856
2857 enum {
2858         /* ACPI \BLTH commands */
2859         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
2860         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
2861         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
2862         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
2863         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
2864 };
2865
2866 static struct rfkill *tpacpi_bluetooth_rfkill;
2867
2868 static void bluetooth_suspend(pm_message_t state)
2869 {
2870         /* Try to make sure radio will resume powered off */
2871         acpi_evalf(NULL, NULL, "\\BLTH", "vd",
2872                    TP_ACPI_BLTH_PWR_OFF_ON_RESUME);
2873 }
2874
2875 static int bluetooth_get_radiosw(void)
2876 {
2877         int status;
2878
2879         if (!tp_features.bluetooth)
2880                 return -ENODEV;
2881
2882         /* WLSW overrides bluetooth in firmware/hardware, reflect that */
2883         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status)
2884                 return RFKILL_STATE_HARD_BLOCKED;
2885
2886 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2887         if (dbg_bluetoothemul)
2888                 return (tpacpi_bluetooth_emulstate) ?
2889                         RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
2890 #endif
2891
2892         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
2893                 return -EIO;
2894
2895         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
2896                 RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
2897 }
2898
2899 static void bluetooth_update_rfk(void)
2900 {
2901         int status;
2902
2903         if (!tpacpi_bluetooth_rfkill)
2904                 return;
2905
2906         status = bluetooth_get_radiosw();
2907         if (status < 0)
2908                 return;
2909         rfkill_force_state(tpacpi_bluetooth_rfkill, status);
2910 }
2911
2912 static int bluetooth_set_radiosw(int radio_on, int update_rfk)
2913 {
2914         int status;
2915
2916         if (!tp_features.bluetooth)
2917                 return -ENODEV;
2918
2919         /* WLSW overrides bluetooth in firmware/hardware, but there is no
2920          * reason to risk weird behaviour. */
2921         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status
2922             && radio_on)
2923                 return -EPERM;
2924
2925 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2926         if (dbg_bluetoothemul) {
2927                 tpacpi_bluetooth_emulstate = !!radio_on;
2928                 if (update_rfk)
2929                         bluetooth_update_rfk();
2930                 return 0;
2931         }
2932 #endif
2933
2934         /* We make sure to keep TP_ACPI_BLUETOOTH_RESUMECTRL off */
2935         if (radio_on)
2936                 status = TP_ACPI_BLUETOOTH_RADIOSSW;
2937         else
2938                 status = 0;
2939         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
2940                 return -EIO;
2941
2942         if (update_rfk)
2943                 bluetooth_update_rfk();
2944
2945         return 0;
2946 }
2947
2948 /* sysfs bluetooth enable ---------------------------------------------- */
2949 static ssize_t bluetooth_enable_show(struct device *dev,
2950                            struct device_attribute *attr,
2951                            char *buf)
2952 {
2953         int status;
2954
2955         status = bluetooth_get_radiosw();
2956         if (status < 0)
2957                 return status;
2958
2959         return snprintf(buf, PAGE_SIZE, "%d\n",
2960                         (status == RFKILL_STATE_UNBLOCKED) ? 1 : 0);
2961 }
2962
2963 static ssize_t bluetooth_enable_store(struct device *dev,
2964                             struct device_attribute *attr,
2965                             const char *buf, size_t count)
2966 {
2967         unsigned long t;
2968         int res;
2969
2970         if (parse_strtoul(buf, 1, &t))
2971                 return -EINVAL;
2972
2973         res = bluetooth_set_radiosw(t, 1);
2974
2975         return (res) ? res : count;
2976 }
2977
2978 static struct device_attribute dev_attr_bluetooth_enable =
2979         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
2980                 bluetooth_enable_show, bluetooth_enable_store);
2981
2982 /* --------------------------------------------------------------------- */
2983
2984 static struct attribute *bluetooth_attributes[] = {
2985         &dev_attr_bluetooth_enable.attr,
2986         NULL
2987 };
2988
2989 static const struct attribute_group bluetooth_attr_group = {
2990         .attrs = bluetooth_attributes,
2991 };
2992
2993 static int tpacpi_bluetooth_rfk_get(void *data, enum rfkill_state *state)
2994 {
2995         int bts = bluetooth_get_radiosw();
2996
2997         if (bts < 0)
2998                 return bts;
2999
3000         *state = bts;
3001         return 0;
3002 }
3003
3004 static int tpacpi_bluetooth_rfk_set(void *data, enum rfkill_state state)
3005 {
3006         return bluetooth_set_radiosw((state == RFKILL_STATE_UNBLOCKED), 0);
3007 }
3008
3009 static void bluetooth_shutdown(void)
3010 {
3011         /* Order firmware to save current state to NVRAM */
3012         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3013                         TP_ACPI_BLTH_SAVE_STATE))
3014                 printk(TPACPI_NOTICE
3015                         "failed to save bluetooth state to NVRAM\n");
3016 }
3017
3018 static void bluetooth_exit(void)
3019 {
3020         bluetooth_shutdown();
3021
3022         if (tpacpi_bluetooth_rfkill)
3023                 rfkill_unregister(tpacpi_bluetooth_rfkill);
3024
3025         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3026                         &bluetooth_attr_group);
3027 }
3028
3029 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3030 {
3031         int res;
3032         int status = 0;
3033
3034         vdbg_printk(TPACPI_DBG_INIT, "initializing bluetooth subdriver\n");
3035
3036         TPACPI_ACPIHANDLE_INIT(hkey);
3037
3038         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3039            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
3040         tp_features.bluetooth = hkey_handle &&
3041             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
3042
3043         vdbg_printk(TPACPI_DBG_INIT, "bluetooth is %s, status 0x%02x\n",
3044                 str_supported(tp_features.bluetooth),
3045                 status);
3046
3047 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3048         if (dbg_bluetoothemul) {
3049                 tp_features.bluetooth = 1;
3050                 printk(TPACPI_INFO
3051                         "bluetooth switch emulation enabled\n");
3052         } else
3053 #endif
3054         if (tp_features.bluetooth &&
3055             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
3056                 /* no bluetooth hardware present in system */
3057                 tp_features.bluetooth = 0;
3058                 dbg_printk(TPACPI_DBG_INIT,
3059                            "bluetooth hardware not installed\n");
3060         }
3061
3062         if (!tp_features.bluetooth)
3063                 return 1;
3064
3065         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3066                                 &bluetooth_attr_group);
3067         if (res)
3068                 return res;
3069
3070         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
3071                                 &tpacpi_bluetooth_rfkill,
3072                                 RFKILL_TYPE_BLUETOOTH,
3073                                 "tpacpi_bluetooth_sw",
3074                                 true,
3075                                 tpacpi_bluetooth_rfk_set,
3076                                 tpacpi_bluetooth_rfk_get);
3077         if (res) {
3078                 bluetooth_exit();
3079                 return res;
3080         }
3081
3082         return 0;
3083 }
3084
3085 /* procfs -------------------------------------------------------------- */
3086 static int bluetooth_read(char *p)
3087 {
3088         int len = 0;
3089         int status = bluetooth_get_radiosw();
3090
3091         if (!tp_features.bluetooth)
3092                 len += sprintf(p + len, "status:\t\tnot supported\n");
3093         else {
3094                 len += sprintf(p + len, "status:\t\t%s\n",
3095                                 (status == RFKILL_STATE_UNBLOCKED) ?
3096                                         "enabled" : "disabled");
3097                 len += sprintf(p + len, "commands:\tenable, disable\n");
3098         }
3099
3100         return len;
3101 }
3102
3103 static int bluetooth_write(char *buf)
3104 {
3105         char *cmd;
3106
3107         if (!tp_features.bluetooth)
3108                 return -ENODEV;
3109
3110         while ((cmd = next_cmd(&buf))) {
3111                 if (strlencmp(cmd, "enable") == 0) {
3112                         bluetooth_set_radiosw(1, 1);
3113                 } else if (strlencmp(cmd, "disable") == 0) {
3114                         bluetooth_set_radiosw(0, 1);
3115                 } else
3116                         return -EINVAL;
3117         }
3118
3119         return 0;
3120 }
3121
3122 static struct ibm_struct bluetooth_driver_data = {
3123         .name = "bluetooth",
3124         .read = bluetooth_read,
3125         .write = bluetooth_write,
3126         .exit = bluetooth_exit,
3127         .suspend = bluetooth_suspend,
3128         .shutdown = bluetooth_shutdown,
3129 };
3130
3131 /*************************************************************************
3132  * Wan subdriver
3133  */
3134
3135 enum {
3136         /* ACPI GWAN/SWAN bits */
3137         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
3138         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
3139         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
3140                                                    off / last state */
3141 };
3142
3143 static struct rfkill *tpacpi_wan_rfkill;
3144
3145 static void wan_suspend(pm_message_t state)
3146 {
3147         /* Try to make sure radio will resume powered off */
3148         acpi_evalf(NULL, NULL, "\\WGSV", "qvd",
3149                    TP_ACPI_WGSV_PWR_OFF_ON_RESUME);
3150 }
3151
3152 static int wan_get_radiosw(void)
3153 {
3154         int status;
3155
3156         if (!tp_features.wan)
3157                 return -ENODEV;
3158
3159         /* WLSW overrides WWAN in firmware/hardware, reflect that */
3160         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status)
3161                 return RFKILL_STATE_HARD_BLOCKED;
3162
3163 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3164         if (dbg_wwanemul)
3165                 return (tpacpi_wwan_emulstate) ?
3166                         RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
3167 #endif
3168
3169         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
3170                 return -EIO;
3171
3172         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
3173                 RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
3174 }
3175
3176 static void wan_update_rfk(void)
3177 {
3178         int status;
3179
3180         if (!tpacpi_wan_rfkill)
3181                 return;
3182
3183         status = wan_get_radiosw();
3184         if (status < 0)
3185                 return;
3186         rfkill_force_state(tpacpi_wan_rfkill, status);
3187 }
3188
3189 static int wan_set_radiosw(int radio_on, int update_rfk)
3190 {
3191         int status;
3192
3193         if (!tp_features.wan)
3194                 return -ENODEV;
3195
3196         /* WLSW overrides bluetooth in firmware/hardware, but there is no
3197          * reason to risk weird behaviour. */
3198         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status
3199             && radio_on)
3200                 return -EPERM;
3201
3202 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3203         if (dbg_wwanemul) {
3204                 tpacpi_wwan_emulstate = !!radio_on;
3205                 if (update_rfk)
3206                         wan_update_rfk();
3207                 return 0;
3208         }
3209 #endif
3210
3211         /* We make sure to keep TP_ACPI_WANCARD_RESUMECTRL off */
3212         if (radio_on)
3213                 status = TP_ACPI_WANCARD_RADIOSSW;
3214         else
3215                 status = 0;
3216         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
3217                 return -EIO;
3218
3219         if (update_rfk)
3220                 wan_update_rfk();
3221
3222         return 0;
3223 }
3224
3225 /* sysfs wan enable ---------------------------------------------------- */
3226 static ssize_t wan_enable_show(struct device *dev,
3227                            struct device_attribute *attr,
3228                            char *buf)
3229 {
3230         int status;
3231
3232         status = wan_get_radiosw();
3233         if (status < 0)
3234                 return status;
3235
3236         return snprintf(buf, PAGE_SIZE, "%d\n",
3237                         (status == RFKILL_STATE_UNBLOCKED) ? 1 : 0);
3238 }
3239
3240 static ssize_t wan_enable_store(struct device *dev,
3241                             struct device_attribute *attr,
3242                             const char *buf, size_t count)
3243 {
3244         unsigned long t;
3245         int res;
3246
3247         if (parse_strtoul(buf, 1, &t))
3248                 return -EINVAL;
3249
3250         res = wan_set_radiosw(t, 1);
3251
3252         return (res) ? res : count;
3253 }
3254
3255 static struct device_attribute dev_attr_wan_enable =
3256         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
3257                 wan_enable_show, wan_enable_store);
3258
3259 /* --------------------------------------------------------------------- */
3260
3261 static struct attribute *wan_attributes[] = {
3262         &dev_attr_wan_enable.attr,
3263         NULL
3264 };
3265
3266 static const struct attribute_group wan_attr_group = {
3267         .attrs = wan_attributes,
3268 };
3269
3270 static int tpacpi_wan_rfk_get(void *data, enum rfkill_state *state)
3271 {
3272         int wans = wan_get_radiosw();
3273
3274         if (wans < 0)
3275                 return wans;
3276
3277         *state = wans;
3278         return 0;
3279 }
3280
3281 static int tpacpi_wan_rfk_set(void *data, enum rfkill_state state)
3282 {
3283         return wan_set_radiosw((state == RFKILL_STATE_UNBLOCKED), 0);
3284 }
3285
3286 static void wan_shutdown(void)
3287 {
3288         /* Order firmware to save current state to NVRAM */
3289         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
3290                         TP_ACPI_WGSV_SAVE_STATE))
3291                 printk(TPACPI_NOTICE
3292                         "failed to save WWAN state to NVRAM\n");
3293 }
3294
3295 static void wan_exit(void)
3296 {
3297         wan_shutdown();
3298
3299         if (tpacpi_wan_rfkill)
3300                 rfkill_unregister(tpacpi_wan_rfkill);
3301
3302         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3303                 &wan_attr_group);
3304 }
3305
3306 static int __init wan_init(struct ibm_init_struct *iibm)
3307 {
3308         int res;
3309         int status = 0;
3310
3311         vdbg_printk(TPACPI_DBG_INIT, "initializing wan subdriver\n");
3312
3313         TPACPI_ACPIHANDLE_INIT(hkey);
3314
3315         tp_features.wan = hkey_handle &&
3316             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
3317
3318         vdbg_printk(TPACPI_DBG_INIT, "wan is %s, status 0x%02x\n",
3319                 str_supported(tp_features.wan),
3320                 status);
3321
3322 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3323         if (dbg_wwanemul) {
3324                 tp_features.wan = 1;
3325                 printk(TPACPI_INFO
3326                         "wwan switch emulation enabled\n");
3327         } else
3328 #endif
3329         if (tp_features.wan &&
3330             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
3331                 /* no wan hardware present in system */
3332                 tp_features.wan = 0;
3333                 dbg_printk(TPACPI_DBG_INIT,
3334                            "wan hardware not installed\n");
3335         }
3336
3337         if (!tp_features.wan)
3338                 return 1;
3339
3340         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3341                                 &wan_attr_group);
3342         if (res)
3343                 return res;
3344
3345         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
3346                                 &tpacpi_wan_rfkill,
3347                                 RFKILL_TYPE_WWAN,
3348                                 "tpacpi_wwan_sw",
3349                                 true,
3350                                 tpacpi_wan_rfk_set,
3351                                 tpacpi_wan_rfk_get);
3352         if (res) {
3353                 wan_exit();
3354                 return res;
3355         }
3356
3357         return 0;
3358 }
3359
3360 /* procfs -------------------------------------------------------------- */
3361 static int wan_read(char *p)
3362 {
3363         int len = 0;
3364         int status = wan_get_radiosw();
3365
3366         if (!tp_features.wan)
3367                 len += sprintf(p + len, "status:\t\tnot supported\n");
3368         else {
3369                 len += sprintf(p + len, "status:\t\t%s\n",
3370                                 (status == RFKILL_STATE_UNBLOCKED) ?
3371                                         "enabled" : "disabled");
3372                 len += sprintf(p + len, "commands:\tenable, disable\n");
3373         }
3374
3375         return len;
3376 }
3377
3378 static int wan_write(char *buf)
3379 {
3380         char *cmd;
3381
3382         if (!tp_features.wan)
3383                 return -ENODEV;
3384
3385         while ((cmd = next_cmd(&buf))) {
3386                 if (strlencmp(cmd, "enable") == 0) {
3387                         wan_set_radiosw(1, 1);
3388                 } else if (strlencmp(cmd, "disable") == 0) {
3389                         wan_set_radiosw(0, 1);
3390                 } else
3391                         return -EINVAL;
3392         }
3393
3394         return 0;
3395 }
3396
3397 static struct ibm_struct wan_driver_data = {
3398         .name = "wan",
3399         .read = wan_read,
3400         .write = wan_write,
3401         .exit = wan_exit,
3402         .suspend = wan_suspend,
3403         .shutdown = wan_shutdown,
3404 };
3405
3406 /*************************************************************************
3407  * UWB subdriver
3408  */
3409
3410 enum {
3411         /* ACPI GUWB/SUWB bits */
3412         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
3413         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
3414 };
3415
3416 static struct rfkill *tpacpi_uwb_rfkill;
3417
3418 static int uwb_get_radiosw(void)
3419 {
3420         int status;
3421
3422         if (!tp_features.uwb)
3423                 return -ENODEV;
3424
3425         /* WLSW overrides UWB in firmware/hardware, reflect that */
3426         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status)
3427                 return RFKILL_STATE_HARD_BLOCKED;
3428
3429 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3430         if (dbg_uwbemul)
3431                 return (tpacpi_uwb_emulstate) ?
3432                         RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
3433 #endif
3434
3435         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
3436                 return -EIO;
3437
3438         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
3439                 RFKILL_STATE_UNBLOCKED : RFKILL_STATE_SOFT_BLOCKED;
3440 }
3441
3442 static void uwb_update_rfk(void)
3443 {
3444         int status;
3445
3446         if (!tpacpi_uwb_rfkill)
3447                 return;
3448
3449         status = uwb_get_radiosw();
3450         if (status < 0)
3451                 return;
3452         rfkill_force_state(tpacpi_uwb_rfkill, status);
3453 }
3454
3455 static int uwb_set_radiosw(int radio_on, int update_rfk)
3456 {
3457         int status;
3458
3459         if (!tp_features.uwb)
3460                 return -ENODEV;
3461
3462         /* WLSW overrides UWB in firmware/hardware, but there is no
3463          * reason to risk weird behaviour. */
3464         if (tp_features.hotkey_wlsw && !hotkey_get_wlsw(&status) && !status
3465             && radio_on)
3466                 return -EPERM;
3467
3468 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3469         if (dbg_uwbemul) {
3470                 tpacpi_uwb_emulstate = !!radio_on;
3471                 if (update_rfk)
3472                         uwb_update_rfk();
3473                 return 0;
3474         }
3475 #endif
3476
3477         status = (radio_on) ? TP_ACPI_UWB_RADIOSSW : 0;
3478         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
3479                 return -EIO;
3480
3481         if (update_rfk)
3482                 uwb_update_rfk();
3483
3484         return 0;
3485 }
3486
3487 /* --------------------------------------------------------------------- */
3488
3489 static int tpacpi_uwb_rfk_get(void *data, enum rfkill_state *state)
3490 {
3491         int uwbs = uwb_get_radiosw();
3492
3493         if (uwbs < 0)
3494                 return uwbs;
3495
3496         *state = uwbs;
3497         return 0;
3498 }
3499
3500 static int tpacpi_uwb_rfk_set(void *data, enum rfkill_state state)
3501 {
3502         return uwb_set_radiosw((state == RFKILL_STATE_UNBLOCKED), 0);
3503 }
3504
3505 static void uwb_exit(void)
3506 {
3507         if (tpacpi_uwb_rfkill)
3508                 rfkill_unregister(tpacpi_uwb_rfkill);
3509 }
3510
3511 static int __init uwb_init(struct ibm_init_struct *iibm)
3512 {
3513         int res;
3514         int status = 0;
3515
3516         vdbg_printk(TPACPI_DBG_INIT, "initializing uwb subdriver\n");
3517
3518         TPACPI_ACPIHANDLE_INIT(hkey);
3519
3520         tp_features.uwb = hkey_handle &&
3521             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
3522
3523         vdbg_printk(TPACPI_DBG_INIT, "uwb is %s, status 0x%02x\n",
3524                 str_supported(tp_features.uwb),
3525                 status);
3526
3527 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3528         if (dbg_uwbemul) {
3529                 tp_features.uwb = 1;
3530                 printk(TPACPI_INFO
3531                         "uwb switch emulation enabled\n");
3532         } else
3533 #endif
3534         if (tp_features.uwb &&
3535             !(status & TP_ACPI_UWB_HWPRESENT)) {
3536                 /* no uwb hardware present in system */
3537                 tp_features.uwb = 0;
3538                 dbg_printk(TPACPI_DBG_INIT,
3539                            "uwb hardware not installed\n");
3540         }
3541
3542         if (!tp_features.uwb)
3543                 return 1;
3544
3545         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
3546                                 &tpacpi_uwb_rfkill,
3547                                 RFKILL_TYPE_UWB,
3548                                 "tpacpi_uwb_sw",
3549                                 false,
3550                                 tpacpi_uwb_rfk_set,
3551                                 tpacpi_uwb_rfk_get);
3552
3553         return res;
3554 }
3555
3556 static struct ibm_struct uwb_driver_data = {
3557         .name = "uwb",
3558         .exit = uwb_exit,
3559         .flags.experimental = 1,
3560 };
3561
3562 /*************************************************************************
3563  * Video subdriver
3564  */
3565
3566 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
3567
3568 enum video_access_mode {
3569         TPACPI_VIDEO_NONE = 0,
3570         TPACPI_VIDEO_570,       /* 570 */
3571         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
3572         TPACPI_VIDEO_NEW,       /* all others */
3573 };
3574
3575 enum {  /* video status flags, based on VIDEO_570 */
3576         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
3577         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
3578         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
3579 };
3580
3581 enum {  /* TPACPI_VIDEO_570 constants */
3582         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
3583         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
3584                                                  * video_status_flags */
3585         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
3586         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
3587 };
3588
3589 static enum video_access_mode video_supported;
3590 static int video_orig_autosw;
3591
3592 static int video_autosw_get(void);
3593 static int video_autosw_set(int enable);
3594
3595 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
3596
3597 static int __init video_init(struct ibm_init_struct *iibm)
3598 {
3599         int ivga;
3600
3601         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
3602
3603         TPACPI_ACPIHANDLE_INIT(vid);
3604         TPACPI_ACPIHANDLE_INIT(vid2);
3605
3606         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
3607                 /* G41, assume IVGA doesn't change */
3608                 vid_handle = vid2_handle;
3609
3610         if (!vid_handle)
3611                 /* video switching not supported on R30, R31 */
3612                 video_supported = TPACPI_VIDEO_NONE;
3613         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
3614                 /* 570 */
3615                 video_supported = TPACPI_VIDEO_570;
3616         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
3617                 /* 600e/x, 770e, 770x */
3618                 video_supported = TPACPI_VIDEO_770;
3619         else
3620                 /* all others */
3621                 video_supported = TPACPI_VIDEO_NEW;
3622
3623         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
3624                 str_supported(video_supported != TPACPI_VIDEO_NONE),
3625                 video_supported);
3626
3627         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
3628 }
3629
3630 static void video_exit(void)
3631 {
3632         dbg_printk(TPACPI_DBG_EXIT,
3633                    "restoring original video autoswitch mode\n");
3634         if (video_autosw_set(video_orig_autosw))
3635                 printk(TPACPI_ERR "error while trying to restore original "
3636                         "video autoswitch mode\n");
3637 }
3638
3639 static int video_outputsw_get(void)
3640 {
3641         int status = 0;
3642         int i;
3643
3644         switch (video_supported) {
3645         case TPACPI_VIDEO_570:
3646                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
3647                                  TP_ACPI_VIDEO_570_PHSCMD))
3648                         return -EIO;
3649                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
3650                 break;
3651         case TPACPI_VIDEO_770:
3652                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
3653                         return -EIO;
3654                 if (i)
3655                         status |= TP_ACPI_VIDEO_S_LCD;
3656                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
3657                         return -EIO;
3658                 if (i)
3659                         status |= TP_ACPI_VIDEO_S_CRT;
3660                 break;
3661         case TPACPI_VIDEO_NEW:
3662                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
3663                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
3664                         return -EIO;
3665                 if (i)
3666                         status |= TP_ACPI_VIDEO_S_CRT;
3667
3668                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
3669                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
3670                         return -EIO;
3671                 if (i)
3672                         status |= TP_ACPI_VIDEO_S_LCD;
3673                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
3674                         return -EIO;
3675                 if (i)
3676                         status |= TP_ACPI_VIDEO_S_DVI;
3677                 break;
3678         default:
3679                 return -ENOSYS;
3680         }
3681
3682         return status;
3683 }
3684
3685 static int video_outputsw_set(int status)
3686 {
3687         int autosw;
3688         int res = 0;
3689
3690         switch (video_supported) {
3691         case TPACPI_VIDEO_570:
3692                 res = acpi_evalf(NULL, NULL,
3693                                  "\\_SB.PHS2", "vdd",
3694                                  TP_ACPI_VIDEO_570_PHS2CMD,
3695                                  status | TP_ACPI_VIDEO_570_PHS2SET);
3696                 break;
3697         case TPACPI_VIDEO_770:
3698                 autosw = video_autosw_get();
3699                 if (autosw < 0)
3700                         return autosw;
3701
3702                 res = video_autosw_set(1);
3703                 if (res)
3704                         return res;
3705                 res = acpi_evalf(vid_handle, NULL,
3706                                  "ASWT", "vdd", status * 0x100, 0);
3707                 if (!autosw && video_autosw_set(autosw)) {
3708                         printk(TPACPI_ERR
3709                                "video auto-switch left enabled due to error\n");
3710                         return -EIO;
3711                 }
3712                 break;
3713         case TPACPI_VIDEO_NEW:
3714                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
3715                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
3716                 break;
3717         default:
3718                 return -ENOSYS;
3719         }
3720
3721         return (res)? 0 : -EIO;
3722 }
3723
3724 static int video_autosw_get(void)
3725 {
3726         int autosw = 0;
3727
3728         switch (video_supported) {
3729         case TPACPI_VIDEO_570:
3730                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
3731                         return -EIO;
3732                 break;
3733         case TPACPI_VIDEO_770:
3734         case TPACPI_VIDEO_NEW:
3735                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
3736                         return -EIO;
3737                 break;
3738         default:
3739                 return -ENOSYS;
3740         }
3741
3742         return autosw & 1;
3743 }
3744
3745 static int video_autosw_set(int enable)
3746 {
3747         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
3748                 return -EIO;
3749         return 0;
3750 }
3751
3752 static int video_outputsw_cycle(void)
3753 {
3754         int autosw = video_autosw_get();
3755         int res;
3756
3757         if (autosw < 0)
3758                 return autosw;
3759
3760         switch (video_supported) {
3761         case TPACPI_VIDEO_570:
3762                 res = video_autosw_set(1);
3763                 if (res)
3764                         return res;
3765                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
3766                 break;
3767         case TPACPI_VIDEO_770:
3768         case TPACPI_VIDEO_NEW:
3769                 res = video_autosw_set(1);
3770                 if (res)
3771                         return res;
3772                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
3773                 break;
3774         default:
3775                 return -ENOSYS;
3776         }
3777         if (!autosw && video_autosw_set(autosw)) {
3778                 printk(TPACPI_ERR
3779                        "video auto-switch left enabled due to error\n");
3780                 return -EIO;
3781         }
3782
3783         return (res)? 0 : -EIO;
3784 }
3785
3786 static int video_expand_toggle(void)
3787 {
3788         switch (video_supported) {
3789         case TPACPI_VIDEO_570:
3790                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
3791                         0 : -EIO;
3792         case TPACPI_VIDEO_770:
3793                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
3794                         0 : -EIO;
3795         case TPACPI_VIDEO_NEW:
3796                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
3797                         0 : -EIO;
3798         default:
3799                 return -ENOSYS;
3800         }
3801         /* not reached */
3802 }
3803
3804 static int video_read(char *p)
3805 {
3806         int status, autosw;
3807         int len = 0;
3808
3809         if (video_supported == TPACPI_VIDEO_NONE) {
3810                 len += sprintf(p + len, "status:\t\tnot supported\n");
3811                 return len;
3812         }
3813
3814         status = video_outputsw_get();
3815         if (status < 0)
3816                 return status;
3817
3818         autosw = video_autosw_get();
3819         if (autosw < 0)
3820                 return autosw;
3821
3822         len += sprintf(p + len, "status:\t\tsupported\n");
3823         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
3824         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
3825         if (video_supported == TPACPI_VIDEO_NEW)
3826                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
3827         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
3828         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
3829         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
3830         if (video_supported == TPACPI_VIDEO_NEW)
3831                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
3832         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
3833         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
3834
3835         return len;
3836 }
3837
3838 static int video_write(char *buf)
3839 {
3840         char *cmd;
3841         int enable, disable, status;
3842         int res;
3843
3844         if (video_supported == TPACPI_VIDEO_NONE)
3845                 return -ENODEV;
3846
3847         enable = 0;
3848         disable = 0;
3849
3850         while ((cmd = next_cmd(&buf))) {
3851                 if (strlencmp(cmd, "lcd_enable") == 0) {
3852                         enable |= TP_ACPI_VIDEO_S_LCD;
3853                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
3854                         disable |= TP_ACPI_VIDEO_S_LCD;
3855                 } else if (strlencmp(cmd, "crt_enable") == 0) {
3856                         enable |= TP_ACPI_VIDEO_S_CRT;
3857                 } else if (strlencmp(cmd, "crt_disable") == 0) {
3858                         disable |= TP_ACPI_VIDEO_S_CRT;
3859                 } else if (video_supported == TPACPI_VIDEO_NEW &&
3860                            strlencmp(cmd, "dvi_enable") == 0) {
3861                         enable |= TP_ACPI_VIDEO_S_DVI;
3862                 } else if (video_supported == TPACPI_VIDEO_NEW &&
3863                            strlencmp(cmd, "dvi_disable") == 0) {
3864                         disable |= TP_ACPI_VIDEO_S_DVI;
3865                 } else if (strlencmp(cmd, "auto_enable") == 0) {
3866                         res = video_autosw_set(1);
3867                         if (res)
3868                                 return res;
3869                 } else if (strlencmp(cmd, "auto_disable") == 0) {
3870                         res = video_autosw_set(0);
3871                         if (res)
3872                                 return res;
3873                 } else if (strlencmp(cmd, "video_switch") == 0) {
3874                         res = video_outputsw_cycle();
3875                         if (res)
3876                                 return res;
3877                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
3878                         res = video_expand_toggle();
3879                         if (res)
3880                                 return res;
3881                 } else
3882                         return -EINVAL;
3883         }
3884
3885         if (enable || disable) {
3886                 status = video_outputsw_get();
3887                 if (status < 0)
3888                         return status;
3889                 res = video_outputsw_set((status & ~disable) | enable);
3890                 if (res)
3891                         return res;
3892         }
3893
3894         return 0;
3895 }
3896
3897 static struct ibm_struct video_driver_data = {
3898         .name = "video",
3899         .read = video_read,
3900         .write = video_write,
3901         .exit = video_exit,
3902 };
3903
3904 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
3905
3906 /*************************************************************************
3907  * Light (thinklight) subdriver
3908  */
3909
3910 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
3911 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
3912
3913 static int light_get_status(void)
3914 {
3915         int status = 0;
3916
3917         if (tp_features.light_status) {
3918                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
3919                         return -EIO;
3920                 return (!!status);
3921         }
3922
3923         return -ENXIO;
3924 }
3925
3926 static int light_set_status(int status)
3927 {
3928         int rc;
3929
3930         if (tp_features.light) {
3931                 if (cmos_handle) {
3932                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
3933                                         (status)?
3934                                                 TP_CMOS_THINKLIGHT_ON :
3935                                                 TP_CMOS_THINKLIGHT_OFF);
3936                 } else {
3937                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
3938                                         (status)? 1 : 0);
3939                 }
3940                 return (rc)? 0 : -EIO;
3941         }
3942
3943         return -ENXIO;
3944 }
3945
3946 static void light_set_status_worker(struct work_struct *work)
3947 {
3948         struct tpacpi_led_classdev *data =
3949                         container_of(work, struct tpacpi_led_classdev, work);
3950
3951         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
3952                 light_set_status((data->new_brightness != LED_OFF));
3953 }
3954
3955 static void light_sysfs_set(struct led_classdev *led_cdev,
3956                         enum led_brightness brightness)
3957 {
3958         struct tpacpi_led_classdev *data =
3959                 container_of(led_cdev,
3960                              struct tpacpi_led_classdev,
3961                              led_classdev);
3962         data->new_brightness = brightness;
3963         queue_work(tpacpi_wq, &data->work);
3964 }
3965
3966 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
3967 {
3968         return (light_get_status() == 1)? LED_FULL : LED_OFF;
3969 }
3970
3971 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
3972         .led_classdev = {
3973                 .name           = "tpacpi::thinklight",
3974                 .brightness_set = &light_sysfs_set,
3975                 .brightness_get = &light_sysfs_get,
3976         }
3977 };
3978
3979 static int __init light_init(struct ibm_init_struct *iibm)
3980 {
3981         int rc;
3982
3983         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
3984
3985         TPACPI_ACPIHANDLE_INIT(ledb);
3986         TPACPI_ACPIHANDLE_INIT(lght);
3987         TPACPI_ACPIHANDLE_INIT(cmos);
3988         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
3989
3990         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
3991         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
3992
3993         if (tp_features.light)
3994                 /* light status not supported on
3995                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
3996                 tp_features.light_status =
3997                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
3998
3999         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4000                 str_supported(tp_features.light),
4001                 str_supported(tp_features.light_status));
4002
4003         if (!tp_features.light)
4004                 return 1;
4005
4006         rc = led_classdev_register(&tpacpi_pdev->dev,
4007                                    &tpacpi_led_thinklight.led_classdev);
4008
4009         if (rc < 0) {
4010                 tp_features.light = 0;
4011                 tp_features.light_status = 0;
4012         } else  {
4013                 rc = 0;
4014         }
4015
4016         return rc;
4017 }
4018
4019 static void light_exit(void)
4020 {
4021         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4022         if (work_pending(&tpacpi_led_thinklight.work))
4023                 flush_workqueue(tpacpi_wq);
4024 }
4025
4026 static int light_read(char *p)
4027 {
4028         int len = 0;
4029         int status;
4030
4031         if (!tp_features.light) {
4032                 len += sprintf(p + len, "status:\t\tnot supported\n");
4033         } else if (!tp_features.light_status) {
4034                 len += sprintf(p + len, "status:\t\tunknown\n");
4035                 len += sprintf(p + len, "commands:\ton, off\n");
4036         } else {
4037                 status = light_get_status();
4038                 if (status < 0)
4039                         return status;
4040                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
4041                 len += sprintf(p + len, "commands:\ton, off\n");
4042         }
4043
4044         return len;
4045 }
4046
4047 static int light_write(char *buf)
4048 {
4049         char *cmd;
4050         int newstatus = 0;
4051
4052         if (!tp_features.light)
4053                 return -ENODEV;
4054
4055         while ((cmd = next_cmd(&buf))) {
4056                 if (strlencmp(cmd, "on") == 0) {
4057                         newstatus = 1;
4058                 } else if (strlencmp(cmd, "off") == 0) {
4059                         newstatus = 0;
4060                 } else
4061                         return -EINVAL;
4062         }
4063
4064         return light_set_status(newstatus);
4065 }
4066
4067 static struct ibm_struct light_driver_data = {
4068         .name = "light",
4069         .read = light_read,
4070         .write = light_write,
4071         .exit = light_exit,
4072 };
4073
4074 /*************************************************************************
4075  * Dock subdriver
4076  */
4077
4078 #ifdef CONFIG_THINKPAD_ACPI_DOCK
4079
4080 static void dock_notify(struct ibm_struct *ibm, u32 event);
4081 static int dock_read(char *p);
4082 static int dock_write(char *buf);
4083
4084 TPACPI_HANDLE(dock, root, "\\_SB.GDCK", /* X30, X31, X40 */
4085            "\\_SB.PCI0.DOCK",   /* 600e/x,770e,770x,A2xm/p,T20-22,X20-21 */
4086            "\\_SB.PCI0.PCI1.DOCK",      /* all others */
4087            "\\_SB.PCI.ISA.SLCE",        /* 570 */
4088     );                          /* A21e,G4x,R30,R31,R32,R40,R40e,R50e */
4089
4090 /* don't list other alternatives as we install a notify handler on the 570 */
4091 TPACPI_HANDLE(pci, root, "\\_SB.PCI");  /* 570 */
4092
4093 static const struct acpi_device_id ibm_pci_device_ids[] = {
4094         {PCI_ROOT_HID_STRING, 0},
4095         {"", 0},
4096 };
4097
4098 static struct tp_acpi_drv_struct ibm_dock_acpidriver[2] = {
4099         {
4100          .notify = dock_notify,
4101          .handle = &dock_handle,
4102          .type = ACPI_SYSTEM_NOTIFY,
4103         },
4104         {
4105         /* THIS ONE MUST NEVER BE USED FOR DRIVER AUTOLOADING.
4106          * We just use it to get notifications of dock hotplug
4107          * in very old thinkpads */
4108          .hid = ibm_pci_device_ids,
4109          .notify = dock_notify,
4110          .handle = &pci_handle,
4111          .type = ACPI_SYSTEM_NOTIFY,
4112         },
4113 };
4114
4115 static struct ibm_struct dock_driver_data[2] = {
4116         {
4117          .name = "dock",
4118          .read = dock_read,
4119          .write = dock_write,
4120          .acpi = &ibm_dock_acpidriver[0],
4121         },
4122         {
4123          .name = "dock",
4124          .acpi = &ibm_dock_acpidriver[1],
4125         },
4126 };
4127
4128 #define dock_docked() (_sta(dock_handle) & 1)
4129
4130 static int __init dock_init(struct ibm_init_struct *iibm)
4131 {
4132         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver\n");
4133
4134         TPACPI_ACPIHANDLE_INIT(dock);
4135
4136         vdbg_printk(TPACPI_DBG_INIT, "dock is %s\n",
4137                 str_supported(dock_handle != NULL));
4138
4139         return (dock_handle)? 0 : 1;
4140 }
4141
4142 static int __init dock_init2(struct ibm_init_struct *iibm)
4143 {
4144         int dock2_needed;
4145
4146         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver part 2\n");
4147
4148         if (dock_driver_data[0].flags.acpi_driver_registered &&
4149             dock_driver_data[0].flags.acpi_notify_installed) {
4150                 TPACPI_ACPIHANDLE_INIT(pci);
4151                 dock2_needed = (pci_handle != NULL);
4152                 vdbg_printk(TPACPI_DBG_INIT,
4153                             "dock PCI handler for the TP 570 is %s\n",
4154                             str_supported(dock2_needed));
4155         } else {
4156                 vdbg_printk(TPACPI_DBG_INIT,
4157                 "dock subdriver part 2 not required\n");
4158                 dock2_needed = 0;
4159         }
4160
4161         return (dock2_needed)? 0 : 1;
4162 }
4163
4164 static void dock_notify(struct ibm_struct *ibm, u32 event)
4165 {
4166         int docked = dock_docked();
4167         int pci = ibm->acpi->hid && ibm->acpi->device &&
4168                 acpi_match_device_ids(ibm->acpi->device, ibm_pci_device_ids);
4169         int data;
4170
4171         if (event == 1 && !pci) /* 570 */
4172                 data = 1;       /* button */
4173         else if (event == 1 && pci)     /* 570 */
4174                 data = 3;       /* dock */
4175         else if (event == 3 && docked)
4176                 data = 1;       /* button */
4177         else if (event == 3 && !docked)
4178                 data = 2;       /* undock */
4179         else if (event == 0 && docked)
4180                 data = 3;       /* dock */
4181         else {
4182                 printk(TPACPI_ERR "unknown dock event %d, status %d\n",
4183                        event, _sta(dock_handle));
4184                 data = 0;       /* unknown */
4185         }
4186         acpi_bus_generate_proc_event(ibm->acpi->device, event, data);
4187         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
4188                                           dev_name(&ibm->acpi->device->dev),
4189                                           event, data);
4190 }
4191
4192 static int dock_read(char *p)
4193 {
4194         int len = 0;
4195         int docked = dock_docked();
4196
4197         if (!dock_handle)
4198                 len += sprintf(p + len, "status:\t\tnot supported\n");
4199         else if (!docked)
4200                 len += sprintf(p + len, "status:\t\tundocked\n");
4201         else {
4202                 len += sprintf(p + len, "status:\t\tdocked\n");
4203                 len += sprintf(p + len, "commands:\tdock, undock\n");
4204         }
4205
4206         return len;
4207 }
4208
4209 static int dock_write(char *buf)
4210 {
4211         char *cmd;
4212
4213         if (!dock_docked())
4214                 return -ENODEV;
4215
4216         while ((cmd = next_cmd(&buf))) {
4217                 if (strlencmp(cmd, "undock") == 0) {
4218                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 0) ||
4219                             !acpi_evalf(dock_handle, NULL, "_EJ0", "vd", 1))
4220                                 return -EIO;
4221                 } else if (strlencmp(cmd, "dock") == 0) {
4222                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 1))
4223                                 return -EIO;
4224                 } else
4225                         return -EINVAL;
4226         }
4227
4228         return 0;
4229 }
4230
4231 #endif /* CONFIG_THINKPAD_ACPI_DOCK */
4232
4233 /*************************************************************************
4234  * Bay subdriver
4235  */
4236
4237 #ifdef CONFIG_THINKPAD_ACPI_BAY
4238
4239 TPACPI_HANDLE(bay, root, "\\_SB.PCI.IDE.SECN.MAST",     /* 570 */
4240            "\\_SB.PCI0.IDE0.IDES.IDSM", /* 600e/x, 770e, 770x */
4241            "\\_SB.PCI0.SATA.SCND.MSTR", /* T60, X60, Z60 */
4242            "\\_SB.PCI0.IDE0.SCND.MSTR", /* all others */
4243            );                           /* A21e, R30, R31 */
4244 TPACPI_HANDLE(bay_ej, bay, "_EJ3",      /* 600e/x, A2xm/p, A3x */
4245            "_EJ0",              /* all others */
4246            );                   /* 570,A21e,G4x,R30,R31,R32,R40e,R50e */
4247 TPACPI_HANDLE(bay2, root, "\\_SB.PCI0.IDE0.PRIM.SLAV",  /* A3x, R32 */
4248            "\\_SB.PCI0.IDE0.IDEP.IDPS", /* 600e/x, 770e, 770x */
4249            );                           /* all others */
4250 TPACPI_HANDLE(bay2_ej, bay2, "_EJ3",    /* 600e/x, 770e, A3x */
4251            "_EJ0",                      /* 770x */
4252            );                           /* all others */
4253
4254 static int __init bay_init(struct ibm_init_struct *iibm)
4255 {
4256         vdbg_printk(TPACPI_DBG_INIT, "initializing bay subdriver\n");
4257
4258         TPACPI_ACPIHANDLE_INIT(bay);
4259         if (bay_handle)
4260                 TPACPI_ACPIHANDLE_INIT(bay_ej);
4261         TPACPI_ACPIHANDLE_INIT(bay2);
4262         if (bay2_handle)
4263                 TPACPI_ACPIHANDLE_INIT(bay2_ej);
4264
4265         tp_features.bay_status = bay_handle &&
4266                 acpi_evalf(bay_handle, NULL, "_STA", "qv");
4267         tp_features.bay_status2 = bay2_handle &&
4268                 acpi_evalf(bay2_handle, NULL, "_STA", "qv");
4269
4270         tp_features.bay_eject = bay_handle && bay_ej_handle &&
4271                 (strlencmp(bay_ej_path, "_EJ0") == 0 || experimental);
4272         tp_features.bay_eject2 = bay2_handle && bay2_ej_handle &&
4273                 (strlencmp(bay2_ej_path, "_EJ0") == 0 || experimental);
4274
4275         vdbg_printk(TPACPI_DBG_INIT,
4276                 "bay 1: status %s, eject %s; bay 2: status %s, eject %s\n",
4277                 str_supported(tp_features.bay_status),
4278                 str_supported(tp_features.bay_eject),
4279                 str_supported(tp_features.bay_status2),
4280                 str_supported(tp_features.bay_eject2));
4281
4282         return (tp_features.bay_status || tp_features.bay_eject ||
4283                 tp_features.bay_status2 || tp_features.bay_eject2)? 0 : 1;
4284 }
4285
4286 static void bay_notify(struct ibm_struct *ibm, u32 event)
4287 {
4288         acpi_bus_generate_proc_event(ibm->acpi->device, event, 0);
4289         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
4290                                           dev_name(&ibm->acpi->device->dev),
4291                                           event, 0);
4292 }
4293
4294 #define bay_occupied(b) (_sta(b##_handle) & 1)
4295
4296 static int bay_read(char *p)
4297 {
4298         int len = 0;
4299         int occupied = bay_occupied(bay);
4300         int occupied2 = bay_occupied(bay2);
4301         int eject, eject2;
4302
4303         len += sprintf(p + len, "status:\t\t%s\n",
4304                 tp_features.bay_status ?
4305                         (occupied ? "occupied" : "unoccupied") :
4306                                 "not supported");
4307         if (tp_features.bay_status2)
4308                 len += sprintf(p + len, "status2:\t%s\n", occupied2 ?
4309                                "occupied" : "unoccupied");
4310
4311         eject = tp_features.bay_eject && occupied;
4312         eject2 = tp_features.bay_eject2 && occupied2;
4313
4314         if (eject && eject2)
4315                 len += sprintf(p + len, "commands:\teject, eject2\n");
4316         else if (eject)
4317                 len += sprintf(p + len, "commands:\teject\n");
4318         else if (eject2)
4319                 len += sprintf(p + len, "commands:\teject2\n");
4320
4321         return len;
4322 }
4323
4324 static int bay_write(char *buf)
4325 {
4326         char *cmd;
4327
4328         if (!tp_features.bay_eject && !tp_features.bay_eject2)
4329                 return -ENODEV;
4330
4331         while ((cmd = next_cmd(&buf))) {
4332                 if (tp_features.bay_eject && strlencmp(cmd, "eject") == 0) {
4333                         if (!acpi_evalf(bay_ej_handle, NULL, NULL, "vd", 1))
4334                                 return -EIO;
4335                 } else if (tp_features.bay_eject2 &&
4336                            strlencmp(cmd, "eject2") == 0) {
4337                         if (!acpi_evalf(bay2_ej_handle, NULL, NULL, "vd", 1))
4338                                 return -EIO;
4339                 } else
4340                         return -EINVAL;
4341         }
4342
4343         return 0;
4344 }
4345
4346 static struct tp_acpi_drv_struct ibm_bay_acpidriver = {
4347         .notify = bay_notify,
4348         .handle = &bay_handle,
4349         .type = ACPI_SYSTEM_NOTIFY,
4350 };
4351
4352 static struct ibm_struct bay_driver_data = {
4353         .name = "bay",
4354         .read = bay_read,
4355         .write = bay_write,
4356         .acpi = &ibm_bay_acpidriver,
4357 };
4358
4359 #endif /* CONFIG_THINKPAD_ACPI_BAY */
4360
4361 /*************************************************************************
4362  * CMOS subdriver
4363  */
4364
4365 /* sysfs cmos_command -------------------------------------------------- */
4366 static ssize_t cmos_command_store(struct device *dev,
4367                             struct device_attribute *attr,
4368                             const char *buf, size_t count)
4369 {
4370         unsigned long cmos_cmd;
4371         int res;
4372
4373         if (parse_strtoul(buf, 21, &cmos_cmd))
4374                 return -EINVAL;
4375
4376         res = issue_thinkpad_cmos_command(cmos_cmd);
4377         return (res)? res : count;
4378 }
4379
4380 static struct device_attribute dev_attr_cmos_command =
4381         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4382
4383 /* --------------------------------------------------------------------- */
4384
4385 static int __init cmos_init(struct ibm_init_struct *iibm)
4386 {
4387         int res;
4388
4389         vdbg_printk(TPACPI_DBG_INIT,
4390                 "initializing cmos commands subdriver\n");
4391
4392         TPACPI_ACPIHANDLE_INIT(cmos);
4393
4394         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4395                 str_supported(cmos_handle != NULL));
4396
4397         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4398         if (res)
4399                 return res;
4400
4401         return (cmos_handle)? 0 : 1;
4402 }
4403
4404 static void cmos_exit(void)
4405 {
4406         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4407 }
4408
4409 static int cmos_read(char *p)
4410 {
4411         int len = 0;
4412
4413         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4414            R30, R31, T20-22, X20-21 */
4415         if (!cmos_handle)
4416                 len += sprintf(p + len, "status:\t\tnot supported\n");
4417         else {
4418                 len += sprintf(p + len, "status:\t\tsupported\n");
4419                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
4420         }
4421
4422         return len;
4423 }
4424
4425 static int cmos_write(char *buf)
4426 {
4427         char *cmd;
4428         int cmos_cmd, res;
4429
4430         while ((cmd = next_cmd(&buf))) {
4431                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4432                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4433                         /* cmos_cmd set */
4434                 } else
4435                         return -EINVAL;
4436
4437                 res = issue_thinkpad_cmos_command(cmos_cmd);
4438                 if (res)
4439                         return res;
4440         }
4441
4442         return 0;
4443 }
4444
4445 static struct ibm_struct cmos_driver_data = {
4446         .name = "cmos",
4447         .read = cmos_read,
4448         .write = cmos_write,
4449         .exit = cmos_exit,
4450 };
4451
4452 /*************************************************************************
4453  * LED subdriver
4454  */
4455
4456 enum led_access_mode {
4457         TPACPI_LED_NONE = 0,
4458         TPACPI_LED_570, /* 570 */
4459         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4460         TPACPI_LED_NEW, /* all others */
4461 };
4462
4463 enum {  /* For TPACPI_LED_OLD */
4464         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4465         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4466         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4467 };
4468
4469 enum led_status_t {
4470         TPACPI_LED_OFF = 0,
4471         TPACPI_LED_ON,
4472         TPACPI_LED_BLINK,
4473 };
4474
4475 static enum led_access_mode led_supported;
4476
4477 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4478            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4479                                 /* T20-22, X20-21 */
4480            "LED",               /* all others */
4481            );                   /* R30, R31 */
4482
4483 #define TPACPI_LED_NUMLEDS 8
4484 static struct tpacpi_led_classdev *tpacpi_leds;
4485 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4486 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4487         /* there's a limit of 19 chars + NULL before 2.6.26 */
4488         "tpacpi::power",
4489         "tpacpi:orange:batt",
4490         "tpacpi:green:batt",
4491         "tpacpi::dock_active",
4492         "tpacpi::bay_active",
4493         "tpacpi::dock_batt",
4494         "tpacpi::unknown_led",
4495         "tpacpi::standby",
4496 };
4497
4498 static int led_get_status(const unsigned int led)
4499 {
4500         int status;
4501         enum led_status_t led_s;
4502
4503         switch (led_supported) {
4504         case TPACPI_LED_570:
4505                 if (!acpi_evalf(ec_handle,
4506                                 &status, "GLED", "dd", 1 << led))
4507                         return -EIO;
4508                 led_s = (status == 0)?
4509                                 TPACPI_LED_OFF :
4510                                 ((status == 1)?
4511                                         TPACPI_LED_ON :
4512                                         TPACPI_LED_BLINK);
4513                 tpacpi_led_state_cache[led] = led_s;
4514                 return led_s;
4515         default:
4516                 return -ENXIO;
4517         }
4518
4519         /* not reached */
4520 }
4521
4522 static int led_set_status(const unsigned int led,
4523                           const enum led_status_t ledstatus)
4524 {
4525         /* off, on, blink. Index is led_status_t */
4526         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
4527         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
4528
4529         int rc = 0;
4530
4531         switch (led_supported) {
4532         case TPACPI_LED_570:
4533                 /* 570 */
4534                 if (led > 7)
4535                         return -EINVAL;
4536                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4537                                 (1 << led), led_sled_arg1[ledstatus]))
4538                         rc = -EIO;
4539                 break;
4540         case TPACPI_LED_OLD:
4541                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
4542                 if (led > 7)
4543                         return -EINVAL;
4544                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
4545                 if (rc >= 0)
4546                         rc = ec_write(TPACPI_LED_EC_HLBL,
4547                                       (ledstatus == TPACPI_LED_BLINK) << led);
4548                 if (rc >= 0)
4549                         rc = ec_write(TPACPI_LED_EC_HLCL,
4550                                       (ledstatus != TPACPI_LED_OFF) << led);
4551                 break;
4552         case TPACPI_LED_NEW:
4553                 /* all others */
4554                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4555                                 led, led_led_arg1[ledstatus]))
4556                         rc = -EIO;
4557                 break;
4558         default:
4559                 rc = -ENXIO;
4560         }
4561
4562         if (!rc)
4563                 tpacpi_led_state_cache[led] = ledstatus;
4564
4565         return rc;
4566 }
4567
4568 static void led_sysfs_set_status(unsigned int led,
4569                                  enum led_brightness brightness)
4570 {
4571         led_set_status(led,
4572                         (brightness == LED_OFF) ?
4573                         TPACPI_LED_OFF :
4574                         (tpacpi_led_state_cache[led] == TPACPI_LED_BLINK) ?
4575                                 TPACPI_LED_BLINK : TPACPI_LED_ON);
4576 }
4577
4578 static void led_set_status_worker(struct work_struct *work)
4579 {
4580         struct tpacpi_led_classdev *data =
4581                 container_of(work, struct tpacpi_led_classdev, work);
4582
4583         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4584                 led_sysfs_set_status(data->led, data->new_brightness);
4585 }
4586
4587 static void led_sysfs_set(struct led_classdev *led_cdev,
4588                         enum led_brightness brightness)
4589 {
4590         struct tpacpi_led_classdev *data = container_of(led_cdev,
4591                              struct tpacpi_led_classdev, led_classdev);
4592
4593         data->new_brightness = brightness;
4594         queue_work(tpacpi_wq, &data->work);
4595 }
4596
4597 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
4598                         unsigned long *delay_on, unsigned long *delay_off)
4599 {
4600         struct tpacpi_led_classdev *data = container_of(led_cdev,
4601                              struct tpacpi_led_classdev, led_classdev);
4602
4603         /* Can we choose the flash rate? */
4604         if (*delay_on == 0 && *delay_off == 0) {
4605                 /* yes. set them to the hardware blink rate (1 Hz) */
4606                 *delay_on = 500; /* ms */
4607                 *delay_off = 500; /* ms */
4608         } else if ((*delay_on != 500) || (*delay_off != 500))
4609                 return -EINVAL;
4610
4611         data->new_brightness = TPACPI_LED_BLINK;
4612         queue_work(tpacpi_wq, &data->work);
4613
4614         return 0;
4615 }
4616
4617 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
4618 {
4619         int rc;
4620
4621         struct tpacpi_led_classdev *data = container_of(led_cdev,
4622                              struct tpacpi_led_classdev, led_classdev);
4623
4624         rc = led_get_status(data->led);
4625
4626         if (rc == TPACPI_LED_OFF || rc < 0)
4627                 rc = LED_OFF;   /* no error handling in led class :( */
4628         else
4629                 rc = LED_FULL;
4630
4631         return rc;
4632 }
4633
4634 static void led_exit(void)
4635 {
4636         unsigned int i;
4637
4638         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
4639                 if (tpacpi_leds[i].led_classdev.name)
4640                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
4641         }
4642
4643         kfree(tpacpi_leds);
4644 }
4645
4646 static int __init led_init(struct ibm_init_struct *iibm)
4647 {
4648         unsigned int i;
4649         int rc;
4650
4651         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
4652
4653         TPACPI_ACPIHANDLE_INIT(led);
4654
4655         if (!led_handle)
4656                 /* led not supported on R30, R31 */
4657                 led_supported = TPACPI_LED_NONE;
4658         else if (strlencmp(led_path, "SLED") == 0)
4659                 /* 570 */
4660                 led_supported = TPACPI_LED_570;
4661         else if (strlencmp(led_path, "SYSL") == 0)
4662                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4663                 led_supported = TPACPI_LED_OLD;
4664         else
4665                 /* all others */
4666                 led_supported = TPACPI_LED_NEW;
4667
4668         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
4669                 str_supported(led_supported), led_supported);
4670
4671         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
4672                               GFP_KERNEL);
4673         if (!tpacpi_leds) {
4674                 printk(TPACPI_ERR "Out of memory for LED data\n");
4675                 return -ENOMEM;
4676         }
4677
4678         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
4679                 tpacpi_leds[i].led = i;
4680
4681                 tpacpi_leds[i].led_classdev.brightness_set = &led_sysfs_set;
4682                 tpacpi_leds[i].led_classdev.blink_set = &led_sysfs_blink_set;
4683                 if (led_supported == TPACPI_LED_570)
4684                         tpacpi_leds[i].led_classdev.brightness_get =
4685                                                         &led_sysfs_get;
4686
4687                 tpacpi_leds[i].led_classdev.name = tpacpi_led_names[i];
4688
4689                 INIT_WORK(&tpacpi_leds[i].work, led_set_status_worker);
4690
4691                 rc = led_classdev_register(&tpacpi_pdev->dev,
4692                                            &tpacpi_leds[i].led_classdev);
4693                 if (rc < 0) {
4694                         tpacpi_leds[i].led_classdev.name = NULL;
4695                         led_exit();
4696                         return rc;
4697                 }
4698         }
4699
4700         return (led_supported != TPACPI_LED_NONE)? 0 : 1;
4701 }
4702
4703 #define str_led_status(s) \
4704         ((s) == TPACPI_LED_OFF ? "off" : \
4705                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
4706
4707 static int led_read(char *p)
4708 {
4709         int len = 0;
4710
4711         if (!led_supported) {
4712                 len += sprintf(p + len, "status:\t\tnot supported\n");
4713                 return len;
4714         }
4715         len += sprintf(p + len, "status:\t\tsupported\n");
4716
4717         if (led_supported == TPACPI_LED_570) {
4718                 /* 570 */
4719                 int i, status;
4720                 for (i = 0; i < 8; i++) {
4721                         status = led_get_status(i);
4722                         if (status < 0)
4723                                 return -EIO;
4724                         len += sprintf(p + len, "%d:\t\t%s\n",
4725                                        i, str_led_status(status));
4726                 }
4727         }
4728
4729         len += sprintf(p + len, "commands:\t"
4730                        "<led> on, <led> off, <led> blink (<led> is 0-7)\n");
4731
4732         return len;
4733 }
4734
4735 static int led_write(char *buf)
4736 {
4737         char *cmd;
4738         int led, rc;
4739         enum led_status_t s;
4740
4741         if (!led_supported)
4742                 return -ENODEV;
4743
4744         while ((cmd = next_cmd(&buf))) {
4745                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 7)
4746                         return -EINVAL;
4747
4748                 if (strstr(cmd, "off")) {
4749                         s = TPACPI_LED_OFF;
4750                 } else if (strstr(cmd, "on")) {
4751                         s = TPACPI_LED_ON;
4752                 } else if (strstr(cmd, "blink")) {
4753                         s = TPACPI_LED_BLINK;
4754                 } else {
4755                         return -EINVAL;
4756                 }
4757
4758                 rc = led_set_status(led, s);
4759                 if (rc < 0)
4760                         return rc;
4761         }
4762
4763         return 0;
4764 }
4765
4766 static struct ibm_struct led_driver_data = {
4767         .name = "led",
4768         .read = led_read,
4769         .write = led_write,
4770         .exit = led_exit,
4771 };
4772
4773 /*************************************************************************
4774  * Beep subdriver
4775  */
4776
4777 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
4778
4779 static int __init beep_init(struct ibm_init_struct *iibm)
4780 {
4781         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
4782
4783         TPACPI_ACPIHANDLE_INIT(beep);
4784
4785         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
4786                 str_supported(beep_handle != NULL));
4787
4788         return (beep_handle)? 0 : 1;
4789 }
4790
4791 static int beep_read(char *p)
4792 {
4793         int len = 0;
4794
4795         if (!beep_handle)
4796                 len += sprintf(p + len, "status:\t\tnot supported\n");
4797         else {
4798                 len += sprintf(p + len, "status:\t\tsupported\n");
4799                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
4800         }
4801
4802         return len;
4803 }
4804
4805 static int beep_write(char *buf)
4806 {
4807         char *cmd;
4808         int beep_cmd;
4809
4810         if (!beep_handle)
4811                 return -ENODEV;
4812
4813         while ((cmd = next_cmd(&buf))) {
4814                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
4815                     beep_cmd >= 0 && beep_cmd <= 17) {
4816                         /* beep_cmd set */
4817                 } else
4818                         return -EINVAL;
4819                 if (!acpi_evalf(beep_handle, NULL, NULL, "vdd", beep_cmd, 0))
4820                         return -EIO;
4821         }
4822
4823         return 0;
4824 }
4825
4826 static struct ibm_struct beep_driver_data = {
4827         .name = "beep",
4828         .read = beep_read,
4829         .write = beep_write,
4830 };
4831
4832 /*************************************************************************
4833  * Thermal subdriver
4834  */
4835
4836 enum thermal_access_mode {
4837         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
4838         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
4839         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
4840         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
4841         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
4842 };
4843
4844 enum { /* TPACPI_THERMAL_TPEC_* */
4845         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
4846         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
4847         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
4848 };
4849
4850 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
4851 struct ibm_thermal_sensors_struct {
4852         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
4853 };
4854
4855 static enum thermal_access_mode thermal_read_mode;
4856
4857 /* idx is zero-based */
4858 static int thermal_get_sensor(int idx, s32 *value)
4859 {
4860         int t;
4861         s8 tmp;
4862         char tmpi[5];
4863
4864         t = TP_EC_THERMAL_TMP0;
4865
4866         switch (thermal_read_mode) {
4867 #if TPACPI_MAX_THERMAL_SENSORS >= 16
4868         case TPACPI_THERMAL_TPEC_16:
4869                 if (idx >= 8 && idx <= 15) {
4870                         t = TP_EC_THERMAL_TMP8;
4871                         idx -= 8;
4872                 }
4873                 /* fallthrough */
4874 #endif
4875         case TPACPI_THERMAL_TPEC_8:
4876                 if (idx <= 7) {
4877                         if (!acpi_ec_read(t + idx, &tmp))
4878                                 return -EIO;
4879                         *value = tmp * 1000;
4880                         return 0;
4881                 }
4882                 break;
4883
4884         case TPACPI_THERMAL_ACPI_UPDT:
4885                 if (idx <= 7) {
4886                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
4887                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
4888                                 return -EIO;
4889                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
4890                                 return -EIO;
4891                         *value = (t - 2732) * 100;
4892                         return 0;
4893                 }
4894                 break;
4895
4896         case TPACPI_THERMAL_ACPI_TMP07:
4897                 if (idx <= 7) {
4898                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
4899                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
4900                                 return -EIO;
4901                         if (t > 127 || t < -127)
4902                                 t = TP_EC_THERMAL_TMP_NA;
4903                         *value = t * 1000;
4904                         return 0;
4905                 }
4906                 break;
4907
4908         case TPACPI_THERMAL_NONE:
4909         default:
4910                 return -ENOSYS;
4911         }
4912
4913         return -EINVAL;
4914 }
4915
4916 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
4917 {
4918         int res, i;
4919         int n;
4920
4921         n = 8;
4922         i = 0;
4923
4924         if (!s)
4925                 return -EINVAL;
4926
4927         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
4928                 n = 16;
4929
4930         for (i = 0 ; i < n; i++) {
4931                 res = thermal_get_sensor(i, &s->temp[i]);
4932                 if (res)
4933                         return res;
4934         }
4935
4936         return n;
4937 }
4938
4939 /* sysfs temp##_input -------------------------------------------------- */
4940
4941 static ssize_t thermal_temp_input_show(struct device *dev,
4942                            struct device_attribute *attr,
4943                            char *buf)
4944 {
4945         struct sensor_device_attribute *sensor_attr =
4946                                         to_sensor_dev_attr(attr);
4947         int idx = sensor_attr->index;
4948         s32 value;
4949         int res;
4950
4951         res = thermal_get_sensor(idx, &value);
4952         if (res)
4953                 return res;
4954         if (value == TP_EC_THERMAL_TMP_NA * 1000)
4955                 return -ENXIO;
4956
4957         return snprintf(buf, PAGE_SIZE, "%d\n", value);
4958 }
4959
4960 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
4961          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
4962                      thermal_temp_input_show, NULL, _idxB)
4963
4964 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
4965         THERMAL_SENSOR_ATTR_TEMP(1, 0),
4966         THERMAL_SENSOR_ATTR_TEMP(2, 1),
4967         THERMAL_SENSOR_ATTR_TEMP(3, 2),
4968         THERMAL_SENSOR_ATTR_TEMP(4, 3),
4969         THERMAL_SENSOR_ATTR_TEMP(5, 4),
4970         THERMAL_SENSOR_ATTR_TEMP(6, 5),
4971         THERMAL_SENSOR_ATTR_TEMP(7, 6),
4972         THERMAL_SENSOR_ATTR_TEMP(8, 7),
4973         THERMAL_SENSOR_ATTR_TEMP(9, 8),
4974         THERMAL_SENSOR_ATTR_TEMP(10, 9),
4975         THERMAL_SENSOR_ATTR_TEMP(11, 10),
4976         THERMAL_SENSOR_ATTR_TEMP(12, 11),
4977         THERMAL_SENSOR_ATTR_TEMP(13, 12),
4978         THERMAL_SENSOR_ATTR_TEMP(14, 13),
4979         THERMAL_SENSOR_ATTR_TEMP(15, 14),
4980         THERMAL_SENSOR_ATTR_TEMP(16, 15),
4981 };
4982
4983 #define THERMAL_ATTRS(X) \
4984         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
4985
4986 static struct attribute *thermal_temp_input_attr[] = {
4987         THERMAL_ATTRS(8),
4988         THERMAL_ATTRS(9),
4989         THERMAL_ATTRS(10),
4990         THERMAL_ATTRS(11),
4991         THERMAL_ATTRS(12),
4992         THERMAL_ATTRS(13),
4993         THERMAL_ATTRS(14),
4994         THERMAL_ATTRS(15),
4995         THERMAL_ATTRS(0),
4996         THERMAL_ATTRS(1),
4997         THERMAL_ATTRS(2),
4998         THERMAL_ATTRS(3),
4999         THERMAL_ATTRS(4),
5000         THERMAL_ATTRS(5),
5001         THERMAL_ATTRS(6),
5002         THERMAL_ATTRS(7),
5003         NULL
5004 };
5005
5006 static const struct attribute_group thermal_temp_input16_group = {
5007         .attrs = thermal_temp_input_attr
5008 };
5009
5010 static const struct attribute_group thermal_temp_input8_group = {
5011         .attrs = &thermal_temp_input_attr[8]
5012 };
5013
5014 #undef THERMAL_SENSOR_ATTR_TEMP
5015 #undef THERMAL_ATTRS
5016
5017 /* --------------------------------------------------------------------- */
5018
5019 static int __init thermal_init(struct ibm_init_struct *iibm)
5020 {
5021         u8 t, ta1, ta2;
5022         int i;
5023         int acpi_tmp7;
5024         int res;
5025
5026         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5027
5028         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5029
5030         if (thinkpad_id.ec_model) {
5031                 /*
5032                  * Direct EC access mode: sensors at registers
5033                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5034                  * non-implemented, thermal sensors return 0x80 when
5035                  * not available
5036                  */
5037
5038                 ta1 = ta2 = 0;
5039                 for (i = 0; i < 8; i++) {
5040                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5041                                 ta1 |= t;
5042                         } else {
5043                                 ta1 = 0;
5044                                 break;
5045                         }
5046                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5047                                 ta2 |= t;
5048                         } else {
5049                                 ta1 = 0;
5050                                 break;
5051                         }
5052                 }
5053                 if (ta1 == 0) {
5054                         /* This is sheer paranoia, but we handle it anyway */
5055                         if (acpi_tmp7) {
5056                                 printk(TPACPI_ERR
5057                                        "ThinkPad ACPI EC access misbehaving, "
5058                                        "falling back to ACPI TMPx access "
5059                                        "mode\n");
5060                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5061                         } else {
5062                                 printk(TPACPI_ERR
5063                                        "ThinkPad ACPI EC access misbehaving, "
5064                                        "disabling thermal sensors access\n");
5065                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5066                         }
5067                 } else {
5068                         thermal_read_mode =
5069                             (ta2 != 0) ?
5070                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5071                 }
5072         } else if (acpi_tmp7) {
5073                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5074                         /* 600e/x, 770e, 770x */
5075                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5076                 } else {
5077                         /* Standard ACPI TMPx access, max 8 sensors */
5078                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5079                 }
5080         } else {
5081                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5082                 thermal_read_mode = TPACPI_THERMAL_NONE;
5083         }
5084
5085         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5086                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5087                 thermal_read_mode);
5088
5089         switch (thermal_read_mode) {
5090         case TPACPI_THERMAL_TPEC_16:
5091                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5092                                 &thermal_temp_input16_group);
5093                 if (res)
5094                         return res;
5095                 break;
5096         case TPACPI_THERMAL_TPEC_8:
5097         case TPACPI_THERMAL_ACPI_TMP07:
5098         case TPACPI_THERMAL_ACPI_UPDT:
5099                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5100                                 &thermal_temp_input8_group);
5101                 if (res)
5102                         return res;
5103                 break;
5104         case TPACPI_THERMAL_NONE:
5105         default:
5106                 return 1;
5107         }
5108
5109         return 0;
5110 }
5111
5112 static void thermal_exit(void)
5113 {
5114         switch (thermal_read_mode) {
5115         case TPACPI_THERMAL_TPEC_16:
5116                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5117                                    &thermal_temp_input16_group);
5118                 break;
5119         case TPACPI_THERMAL_TPEC_8:
5120         case TPACPI_THERMAL_ACPI_TMP07:
5121         case TPACPI_THERMAL_ACPI_UPDT:
5122                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5123                                    &thermal_temp_input16_group);
5124                 break;
5125         case TPACPI_THERMAL_NONE:
5126         default:
5127                 break;
5128         }
5129 }
5130
5131 static int thermal_read(char *p)
5132 {
5133         int len = 0;
5134         int n, i;
5135         struct ibm_thermal_sensors_struct t;
5136
5137         n = thermal_get_sensors(&t);
5138         if (unlikely(n < 0))
5139                 return n;
5140
5141         len += sprintf(p + len, "temperatures:\t");
5142
5143         if (n > 0) {
5144                 for (i = 0; i < (n - 1); i++)
5145                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
5146                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
5147         } else
5148                 len += sprintf(p + len, "not supported\n");
5149
5150         return len;
5151 }
5152
5153 static struct ibm_struct thermal_driver_data = {
5154         .name = "thermal",
5155         .read = thermal_read,
5156         .exit = thermal_exit,
5157 };
5158
5159 /*************************************************************************
5160  * EC Dump subdriver
5161  */
5162
5163 static u8 ecdump_regs[256];
5164
5165 static int ecdump_read(char *p)
5166 {
5167         int len = 0;
5168         int i, j;
5169         u8 v;
5170
5171         len += sprintf(p + len, "EC      "
5172                        " +00 +01 +02 +03 +04 +05 +06 +07"
5173                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5174         for (i = 0; i < 256; i += 16) {
5175                 len += sprintf(p + len, "EC 0x%02x:", i);
5176                 for (j = 0; j < 16; j++) {
5177                         if (!acpi_ec_read(i + j, &v))
5178                                 break;
5179                         if (v != ecdump_regs[i + j])
5180                                 len += sprintf(p + len, " *%02x", v);
5181                         else
5182                                 len += sprintf(p + len, "  %02x", v);
5183                         ecdump_regs[i + j] = v;
5184                 }
5185                 len += sprintf(p + len, "\n");
5186                 if (j != 16)
5187                         break;
5188         }
5189
5190         /* These are way too dangerous to advertise openly... */
5191 #if 0
5192         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
5193                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5194         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
5195                        " (<offset> is 00-ff, <value> is 0-255)\n");
5196 #endif
5197         return len;
5198 }
5199
5200 static int ecdump_write(char *buf)
5201 {
5202         char *cmd;
5203         int i, v;
5204
5205         while ((cmd = next_cmd(&buf))) {
5206                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5207                         /* i and v set */
5208                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5209                         /* i and v set */
5210                 } else
5211                         return -EINVAL;
5212                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5213                         if (!acpi_ec_write(i, v))
5214                                 return -EIO;
5215                 } else
5216                         return -EINVAL;
5217         }
5218
5219         return 0;
5220 }
5221
5222 static struct ibm_struct ecdump_driver_data = {
5223         .name = "ecdump",
5224         .read = ecdump_read,
5225         .write = ecdump_write,
5226         .flags.experimental = 1,
5227 };
5228
5229 /*************************************************************************
5230  * Backlight/brightness subdriver
5231  */
5232
5233 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5234
5235 enum {
5236         TP_EC_BACKLIGHT = 0x31,
5237
5238         /* TP_EC_BACKLIGHT bitmasks */
5239         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5240         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5241         TP_EC_BACKLIGHT_MAPSW = 0x20,
5242 };
5243
5244 static struct backlight_device *ibm_backlight_device;
5245 static int brightness_mode;
5246 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5247
5248 static struct mutex brightness_mutex;
5249
5250 /*
5251  * ThinkPads can read brightness from two places: EC 0x31, or
5252  * CMOS NVRAM byte 0x5E, bits 0-3.
5253  *
5254  * EC 0x31 has the following layout
5255  *   Bit 7: unknown function
5256  *   Bit 6: unknown function
5257  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5258  *   Bit 4: must be set to zero to avoid problems
5259  *   Bit 3-0: backlight brightness level
5260  *
5261  * brightness_get_raw returns status data in the EC 0x31 layout
5262  */
5263 static int brightness_get_raw(int *status)
5264 {
5265         u8 lec = 0, lcmos = 0, level = 0;
5266
5267         if (brightness_mode & 1) {
5268                 if (!acpi_ec_read(TP_EC_BACKLIGHT, &lec))
5269                         return -EIO;
5270                 level = lec & TP_EC_BACKLIGHT_LVLMSK;
5271         };
5272         if (brightness_mode & 2) {
5273                 lcmos = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5274                          & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5275                         >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5276                 lcmos &= (tp_features.bright_16levels)? 0x0f : 0x07;
5277                 level = lcmos;
5278         }
5279
5280         if (brightness_mode == 3) {
5281                 *status = lec;  /* Prefer EC, CMOS is just a backing store */
5282                 lec &= TP_EC_BACKLIGHT_LVLMSK;
5283                 if (lec == lcmos)
5284                         tp_warned.bright_cmos_ec_unsync = 0;
5285                 else {
5286                         if (!tp_warned.bright_cmos_ec_unsync) {
5287                                 printk(TPACPI_ERR
5288                                         "CMOS NVRAM (%u) and EC (%u) do not "
5289                                         "agree on display brightness level\n",
5290                                         (unsigned int) lcmos,
5291                                         (unsigned int) lec);
5292                                 tp_warned.bright_cmos_ec_unsync = 1;
5293                         }
5294                         return -EIO;
5295                 }
5296         } else {
5297                 *status = level;
5298         }
5299
5300         return 0;
5301 }
5302
5303 /* May return EINTR which can always be mapped to ERESTARTSYS */
5304 static int brightness_set(int value)
5305 {
5306         int cmos_cmd, inc, i, res;
5307         int current_value;
5308         int command_bits;
5309
5310         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
5311             value < 0)
5312                 return -EINVAL;
5313
5314         res = mutex_lock_interruptible(&brightness_mutex);
5315         if (res < 0)
5316                 return res;
5317
5318         res = brightness_get_raw(&current_value);
5319         if (res < 0)
5320                 goto errout;
5321
5322         command_bits = current_value & TP_EC_BACKLIGHT_CMDMSK;
5323         current_value &= TP_EC_BACKLIGHT_LVLMSK;
5324
5325         cmos_cmd = value > current_value ?
5326                         TP_CMOS_BRIGHTNESS_UP :
5327                         TP_CMOS_BRIGHTNESS_DOWN;
5328         inc = (value > current_value)? 1 : -1;
5329
5330         res = 0;
5331         for (i = current_value; i != value; i += inc) {
5332                 if ((brightness_mode & 2) &&
5333                     issue_thinkpad_cmos_command(cmos_cmd)) {
5334                         res = -EIO;
5335                         goto errout;
5336                 }
5337                 if ((brightness_mode & 1) &&
5338                     !acpi_ec_write(TP_EC_BACKLIGHT,
5339                                    (i + inc) | command_bits)) {
5340                         res = -EIO;
5341                         goto errout;;
5342                 }
5343         }
5344
5345 errout:
5346         mutex_unlock(&brightness_mutex);
5347         return res;
5348 }
5349
5350 /* sysfs backlight class ----------------------------------------------- */
5351
5352 static int brightness_update_status(struct backlight_device *bd)
5353 {
5354         /* it is the backlight class's job (caller) to handle
5355          * EINTR and other errors properly */
5356         return brightness_set(
5357                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
5358                  bd->props.power == FB_BLANK_UNBLANK) ?
5359                                 bd->props.brightness : 0);
5360 }
5361
5362 static int brightness_get(struct backlight_device *bd)
5363 {
5364         int status, res;
5365
5366         res = brightness_get_raw(&status);
5367         if (res < 0)
5368                 return 0; /* FIXME: teach backlight about error handling */
5369
5370         return status & TP_EC_BACKLIGHT_LVLMSK;
5371 }
5372
5373 static struct backlight_ops ibm_backlight_data = {
5374         .get_brightness = brightness_get,
5375         .update_status  = brightness_update_status,
5376 };
5377
5378 /* --------------------------------------------------------------------- */
5379
5380 static int __init brightness_init(struct ibm_init_struct *iibm)
5381 {
5382         int b;
5383
5384         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
5385
5386         mutex_init(&brightness_mutex);
5387
5388         /*
5389          * We always attempt to detect acpi support, so as to switch
5390          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
5391          * going to publish a backlight interface
5392          */
5393         b = tpacpi_check_std_acpi_brightness_support();
5394         if (b > 0) {
5395
5396                 if (acpi_video_backlight_support()) {
5397                         if (brightness_enable > 1) {
5398                                 printk(TPACPI_NOTICE
5399                                        "Standard ACPI backlight interface "
5400                                        "available, not loading native one.\n");
5401                                 return 1;
5402                         } else if (brightness_enable == 1) {
5403                                 printk(TPACPI_NOTICE
5404                                        "Backlight control force enabled, even if standard "
5405                                        "ACPI backlight interface is available\n");
5406                         }
5407                 } else {
5408                         if (brightness_enable > 1) {
5409                                 printk(TPACPI_NOTICE
5410                                        "Standard ACPI backlight interface not "
5411                                        "available, thinkpad_acpi native "
5412                                        "brightness control enabled\n");
5413                         }
5414                 }
5415         }
5416
5417         if (!brightness_enable) {
5418                 dbg_printk(TPACPI_DBG_INIT,
5419                            "brightness support disabled by "
5420                            "module parameter\n");
5421                 return 1;
5422         }
5423
5424         if (b > 16) {
5425                 printk(TPACPI_ERR
5426                        "Unsupported brightness interface, "
5427                        "please contact %s\n", TPACPI_MAIL);
5428                 return 1;
5429         }
5430         if (b == 16)
5431                 tp_features.bright_16levels = 1;
5432
5433         if (!brightness_mode) {
5434                 if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO)
5435                         brightness_mode = 2;
5436                 else
5437                         brightness_mode = 3;
5438
5439                 dbg_printk(TPACPI_DBG_INIT, "selected brightness_mode=%d\n",
5440                         brightness_mode);
5441         }
5442
5443         if (brightness_mode > 3)
5444                 return -EINVAL;
5445
5446         if (brightness_get_raw(&b) < 0)
5447                 return 1;
5448
5449         if (tp_features.bright_16levels)
5450                 printk(TPACPI_INFO
5451                        "detected a 16-level brightness capable ThinkPad\n");
5452
5453         ibm_backlight_device = backlight_device_register(
5454                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
5455                                         &ibm_backlight_data);
5456         if (IS_ERR(ibm_backlight_device)) {
5457                 printk(TPACPI_ERR "Could not register backlight device\n");
5458                 return PTR_ERR(ibm_backlight_device);
5459         }
5460         vdbg_printk(TPACPI_DBG_INIT, "brightness is supported\n");
5461
5462         ibm_backlight_device->props.max_brightness =
5463                                 (tp_features.bright_16levels)? 15 : 7;
5464         ibm_backlight_device->props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
5465         backlight_update_status(ibm_backlight_device);
5466
5467         return 0;
5468 }
5469
5470 static void brightness_exit(void)
5471 {
5472         if (ibm_backlight_device) {
5473                 vdbg_printk(TPACPI_DBG_EXIT,
5474                             "calling backlight_device_unregister()\n");
5475                 backlight_device_unregister(ibm_backlight_device);
5476         }
5477 }
5478
5479 static int brightness_read(char *p)
5480 {
5481         int len = 0;
5482         int level;
5483
5484         level = brightness_get(NULL);
5485         if (level < 0) {
5486                 len += sprintf(p + len, "level:\t\tunreadable\n");
5487         } else {
5488                 len += sprintf(p + len, "level:\t\t%d\n", level);
5489                 len += sprintf(p + len, "commands:\tup, down\n");
5490                 len += sprintf(p + len, "commands:\tlevel <level>"
5491                                " (<level> is 0-%d)\n",
5492                                (tp_features.bright_16levels) ? 15 : 7);
5493         }
5494
5495         return len;
5496 }
5497
5498 static int brightness_write(char *buf)
5499 {
5500         int level;
5501         int rc;
5502         char *cmd;
5503         int max_level = (tp_features.bright_16levels) ? 15 : 7;
5504
5505         level = brightness_get(NULL);
5506         if (level < 0)
5507                 return level;
5508
5509         while ((cmd = next_cmd(&buf))) {
5510                 if (strlencmp(cmd, "up") == 0) {
5511                         if (level < max_level)
5512                                 level++;
5513                 } else if (strlencmp(cmd, "down") == 0) {
5514                         if (level > 0)
5515                                 level--;
5516                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
5517                            level >= 0 && level <= max_level) {
5518                         /* new level set */
5519                 } else
5520                         return -EINVAL;
5521         }
5522
5523         /*
5524          * Now we know what the final level should be, so we try to set it.
5525          * Doing it this way makes the syscall restartable in case of EINTR
5526          */
5527         rc = brightness_set(level);
5528         return (rc == -EINTR)? ERESTARTSYS : rc;
5529 }
5530
5531 static struct ibm_struct brightness_driver_data = {
5532         .name = "brightness",
5533         .read = brightness_read,
5534         .write = brightness_write,
5535         .exit = brightness_exit,
5536 };
5537
5538 /*************************************************************************
5539  * Volume subdriver
5540  */
5541
5542 static int volume_offset = 0x30;
5543
5544 static int volume_read(char *p)
5545 {
5546         int len = 0;
5547         u8 level;
5548
5549         if (!acpi_ec_read(volume_offset, &level)) {
5550                 len += sprintf(p + len, "level:\t\tunreadable\n");
5551         } else {
5552                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
5553                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
5554                 len += sprintf(p + len, "commands:\tup, down, mute\n");
5555                 len += sprintf(p + len, "commands:\tlevel <level>"
5556                                " (<level> is 0-15)\n");
5557         }
5558
5559         return len;
5560 }
5561
5562 static int volume_write(char *buf)
5563 {
5564         int cmos_cmd, inc, i;
5565         u8 level, mute;
5566         int new_level, new_mute;
5567         char *cmd;
5568
5569         while ((cmd = next_cmd(&buf))) {
5570                 if (!acpi_ec_read(volume_offset, &level))
5571                         return -EIO;
5572                 new_mute = mute = level & 0x40;
5573                 new_level = level = level & 0xf;
5574
5575                 if (strlencmp(cmd, "up") == 0) {
5576                         if (mute)
5577                                 new_mute = 0;
5578                         else
5579                                 new_level = level == 15 ? 15 : level + 1;
5580                 } else if (strlencmp(cmd, "down") == 0) {
5581                         if (mute)
5582                                 new_mute = 0;
5583                         else
5584                                 new_level = level == 0 ? 0 : level - 1;
5585                 } else if (sscanf(cmd, "level %d", &new_level) == 1 &&
5586                            new_level >= 0 && new_level <= 15) {
5587                         /* new_level set */
5588                 } else if (strlencmp(cmd, "mute") == 0) {
5589                         new_mute = 0x40;
5590                 } else
5591                         return -EINVAL;
5592
5593                 if (new_level != level) {
5594                         /* mute doesn't change */
5595
5596                         cmos_cmd = (new_level > level) ?
5597                                         TP_CMOS_VOLUME_UP : TP_CMOS_VOLUME_DOWN;
5598                         inc = new_level > level ? 1 : -1;
5599
5600                         if (mute && (issue_thinkpad_cmos_command(cmos_cmd) ||
5601                                      !acpi_ec_write(volume_offset, level)))
5602                                 return -EIO;
5603
5604                         for (i = level; i != new_level; i += inc)
5605                                 if (issue_thinkpad_cmos_command(cmos_cmd) ||
5606                                     !acpi_ec_write(volume_offset, i + inc))
5607                                         return -EIO;
5608
5609                         if (mute &&
5610                             (issue_thinkpad_cmos_command(TP_CMOS_VOLUME_MUTE) ||
5611                              !acpi_ec_write(volume_offset, new_level + mute))) {
5612                                 return -EIO;
5613                         }
5614                 }
5615
5616                 if (new_mute != mute) {
5617                         /* level doesn't change */
5618
5619                         cmos_cmd = (new_mute) ?
5620                                    TP_CMOS_VOLUME_MUTE : TP_CMOS_VOLUME_UP;
5621
5622                         if (issue_thinkpad_cmos_command(cmos_cmd) ||
5623                             !acpi_ec_write(volume_offset, level + new_mute))
5624                                 return -EIO;
5625                 }
5626         }
5627
5628         return 0;
5629 }
5630
5631 static struct ibm_struct volume_driver_data = {
5632         .name = "volume",
5633         .read = volume_read,
5634         .write = volume_write,
5635 };
5636
5637 /*************************************************************************
5638  * Fan subdriver
5639  */
5640
5641 /*
5642  * FAN ACCESS MODES
5643  *
5644  * TPACPI_FAN_RD_ACPI_GFAN:
5645  *      ACPI GFAN method: returns fan level
5646  *
5647  *      see TPACPI_FAN_WR_ACPI_SFAN
5648  *      EC 0x2f (HFSP) not available if GFAN exists
5649  *
5650  * TPACPI_FAN_WR_ACPI_SFAN:
5651  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
5652  *
5653  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
5654  *      it for writing.
5655  *
5656  * TPACPI_FAN_WR_TPEC:
5657  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
5658  *      Supported on almost all ThinkPads
5659  *
5660  *      Fan speed changes of any sort (including those caused by the
5661  *      disengaged mode) are usually done slowly by the firmware as the
5662  *      maximum ammount of fan duty cycle change per second seems to be
5663  *      limited.
5664  *
5665  *      Reading is not available if GFAN exists.
5666  *      Writing is not available if SFAN exists.
5667  *
5668  *      Bits
5669  *       7      automatic mode engaged;
5670  *              (default operation mode of the ThinkPad)
5671  *              fan level is ignored in this mode.
5672  *       6      full speed mode (takes precedence over bit 7);
5673  *              not available on all thinkpads.  May disable
5674  *              the tachometer while the fan controller ramps up
5675  *              the speed (which can take up to a few *minutes*).
5676  *              Speeds up fan to 100% duty-cycle, which is far above
5677  *              the standard RPM levels.  It is not impossible that
5678  *              it could cause hardware damage.
5679  *      5-3     unused in some models.  Extra bits for fan level
5680  *              in others, but still useless as all values above
5681  *              7 map to the same speed as level 7 in these models.
5682  *      2-0     fan level (0..7 usually)
5683  *                      0x00 = stop
5684  *                      0x07 = max (set when temperatures critical)
5685  *              Some ThinkPads may have other levels, see
5686  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
5687  *
5688  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
5689  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
5690  *      does so, its initial value is meaningless (0x07).
5691  *
5692  *      For firmware bugs, refer to:
5693  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
5694  *
5695  *      ----
5696  *
5697  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
5698  *      Main fan tachometer reading (in RPM)
5699  *
5700  *      This register is present on all ThinkPads with a new-style EC, and
5701  *      it is known not to be present on the A21m/e, and T22, as there is
5702  *      something else in offset 0x84 according to the ACPI DSDT.  Other
5703  *      ThinkPads from this same time period (and earlier) probably lack the
5704  *      tachometer as well.
5705  *
5706  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firwmare
5707  *      was never fixed by IBM to report the EC firmware version string
5708  *      probably support the tachometer (like the early X models), so
5709  *      detecting it is quite hard.  We need more data to know for sure.
5710  *
5711  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
5712  *      might result.
5713  *
5714  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
5715  *      mode.
5716  *
5717  *      For firmware bugs, refer to:
5718  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
5719  *
5720  * TPACPI_FAN_WR_ACPI_FANS:
5721  *      ThinkPad X31, X40, X41.  Not available in the X60.
5722  *
5723  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
5724  *      high speed.  ACPI DSDT seems to map these three speeds to levels
5725  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
5726  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
5727  *
5728  *      The speeds are stored on handles
5729  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
5730  *
5731  *      There are three default speed sets, acessible as handles:
5732  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
5733  *
5734  *      ACPI DSDT switches which set is in use depending on various
5735  *      factors.
5736  *
5737  *      TPACPI_FAN_WR_TPEC is also available and should be used to
5738  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
5739  *      but the ACPI tables just mention level 7.
5740  */
5741
5742 enum {                                  /* Fan control constants */
5743         fan_status_offset = 0x2f,       /* EC register 0x2f */
5744         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
5745                                          * 0x84 must be read before 0x85 */
5746
5747         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
5748         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
5749
5750         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
5751 };
5752
5753 enum fan_status_access_mode {
5754         TPACPI_FAN_NONE = 0,            /* No fan status or control */
5755         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
5756         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
5757 };
5758
5759 enum fan_control_access_mode {
5760         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
5761         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
5762         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
5763         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
5764 };
5765
5766 enum fan_control_commands {
5767         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
5768         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
5769         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
5770                                                  * and also watchdog cmd */
5771 };
5772
5773 static int fan_control_allowed;
5774
5775 static enum fan_status_access_mode fan_status_access_mode;
5776 static enum fan_control_access_mode fan_control_access_mode;
5777 static enum fan_control_commands fan_control_commands;
5778
5779 static u8 fan_control_initial_status;
5780 static u8 fan_control_desired_level;
5781 static u8 fan_control_resume_level;
5782 static int fan_watchdog_maxinterval;
5783
5784 static struct mutex fan_mutex;
5785
5786 static void fan_watchdog_fire(struct work_struct *ignored);
5787 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
5788
5789 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
5790 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
5791            "\\FSPD",            /* 600e/x, 770e, 770x */
5792            );                   /* all others */
5793 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
5794            "JFNS",              /* 770x-JL */
5795            );                   /* all others */
5796
5797 /*
5798  * Call with fan_mutex held
5799  */
5800 static void fan_update_desired_level(u8 status)
5801 {
5802         if ((status &
5803              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
5804                 if (status > 7)
5805                         fan_control_desired_level = 7;
5806                 else
5807                         fan_control_desired_level = status;
5808         }
5809 }
5810
5811 static int fan_get_status(u8 *status)
5812 {
5813         u8 s;
5814
5815         /* TODO:
5816          * Add TPACPI_FAN_RD_ACPI_FANS ? */
5817
5818         switch (fan_status_access_mode) {
5819         case TPACPI_FAN_RD_ACPI_GFAN:
5820                 /* 570, 600e/x, 770e, 770x */
5821
5822                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
5823                         return -EIO;
5824
5825                 if (likely(status))
5826                         *status = s & 0x07;
5827
5828                 break;
5829
5830         case TPACPI_FAN_RD_TPEC:
5831                 /* all except 570, 600e/x, 770e, 770x */
5832                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
5833                         return -EIO;
5834
5835                 if (likely(status))
5836                         *status = s;
5837
5838                 break;
5839
5840         default:
5841                 return -ENXIO;
5842         }
5843
5844         return 0;
5845 }
5846
5847 static int fan_get_status_safe(u8 *status)
5848 {
5849         int rc;
5850         u8 s;
5851
5852         if (mutex_lock_interruptible(&fan_mutex))
5853                 return -ERESTARTSYS;
5854         rc = fan_get_status(&s);
5855         if (!rc)
5856                 fan_update_desired_level(s);
5857         mutex_unlock(&fan_mutex);
5858
5859         if (status)
5860                 *status = s;
5861
5862         return rc;
5863 }
5864
5865 static int fan_get_speed(unsigned int *speed)
5866 {
5867         u8 hi, lo;
5868
5869         switch (fan_status_access_mode) {
5870         case TPACPI_FAN_RD_TPEC:
5871                 /* all except 570, 600e/x, 770e, 770x */
5872                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
5873                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
5874                         return -EIO;
5875
5876                 if (likely(speed))
5877                         *speed = (hi << 8) | lo;
5878
5879                 break;
5880
5881         default:
5882                 return -ENXIO;
5883         }
5884
5885         return 0;
5886 }
5887
5888 static int fan_set_level(int level)
5889 {
5890         if (!fan_control_allowed)
5891                 return -EPERM;
5892
5893         switch (fan_control_access_mode) {
5894         case TPACPI_FAN_WR_ACPI_SFAN:
5895                 if (level >= 0 && level <= 7) {
5896                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
5897                                 return -EIO;
5898                 } else
5899                         return -EINVAL;
5900                 break;
5901
5902         case TPACPI_FAN_WR_ACPI_FANS:
5903         case TPACPI_FAN_WR_TPEC:
5904                 if (!(level & TP_EC_FAN_AUTO) &&
5905                     !(level & TP_EC_FAN_FULLSPEED) &&
5906                     ((level < 0) || (level > 7)))
5907                         return -EINVAL;
5908
5909                 /* safety net should the EC not support AUTO
5910                  * or FULLSPEED mode bits and just ignore them */
5911                 if (level & TP_EC_FAN_FULLSPEED)
5912                         level |= 7;     /* safety min speed 7 */
5913                 else if (level & TP_EC_FAN_AUTO)
5914                         level |= 4;     /* safety min speed 4 */
5915
5916                 if (!acpi_ec_write(fan_status_offset, level))
5917                         return -EIO;
5918                 else
5919                         tp_features.fan_ctrl_status_undef = 0;
5920                 break;
5921
5922         default:
5923                 return -ENXIO;
5924         }
5925         return 0;
5926 }
5927
5928 static int fan_set_level_safe(int level)
5929 {
5930         int rc;
5931
5932         if (!fan_control_allowed)
5933                 return -EPERM;
5934
5935         if (mutex_lock_interruptible(&fan_mutex))
5936                 return -ERESTARTSYS;
5937
5938         if (level == TPACPI_FAN_LAST_LEVEL)
5939                 level = fan_control_desired_level;
5940
5941         rc = fan_set_level(level);
5942         if (!rc)
5943                 fan_update_desired_level(level);
5944
5945         mutex_unlock(&fan_mutex);
5946         return rc;
5947 }
5948
5949 static int fan_set_enable(void)
5950 {
5951         u8 s;
5952         int rc;
5953
5954         if (!fan_control_allowed)
5955                 return -EPERM;
5956
5957         if (mutex_lock_interruptible(&fan_mutex))
5958                 return -ERESTARTSYS;
5959
5960         switch (fan_control_access_mode) {
5961         case TPACPI_FAN_WR_ACPI_FANS:
5962         case TPACPI_FAN_WR_TPEC:
5963                 rc = fan_get_status(&s);
5964                 if (rc < 0)
5965                         break;
5966
5967                 /* Don't go out of emergency fan mode */
5968                 if (s != 7) {
5969                         s &= 0x07;
5970                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
5971                 }
5972
5973                 if (!acpi_ec_write(fan_status_offset, s))
5974                         rc = -EIO;
5975                 else {
5976                         tp_features.fan_ctrl_status_undef = 0;
5977                         rc = 0;
5978                 }
5979                 break;
5980
5981         case TPACPI_FAN_WR_ACPI_SFAN:
5982                 rc = fan_get_status(&s);
5983                 if (rc < 0)
5984                         break;
5985
5986                 s &= 0x07;
5987
5988                 /* Set fan to at least level 4 */
5989                 s |= 4;
5990
5991                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
5992                         rc = -EIO;
5993                 else
5994                         rc = 0;
5995                 break;
5996
5997         default:
5998                 rc = -ENXIO;
5999         }
6000
6001         mutex_unlock(&fan_mutex);
6002         return rc;
6003 }
6004
6005 static int fan_set_disable(void)
6006 {
6007         int rc;
6008
6009         if (!fan_control_allowed)
6010                 return -EPERM;
6011
6012         if (mutex_lock_interruptible(&fan_mutex))
6013                 return -ERESTARTSYS;
6014
6015         rc = 0;
6016         switch (fan_control_access_mode) {
6017         case TPACPI_FAN_WR_ACPI_FANS:
6018         case TPACPI_FAN_WR_TPEC:
6019                 if (!acpi_ec_write(fan_status_offset, 0x00))
6020                         rc = -EIO;
6021                 else {
6022                         fan_control_desired_level = 0;
6023                         tp_features.fan_ctrl_status_undef = 0;
6024                 }
6025                 break;
6026
6027         case TPACPI_FAN_WR_ACPI_SFAN:
6028                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
6029                         rc = -EIO;
6030                 else
6031                         fan_control_desired_level = 0;
6032                 break;
6033
6034         default:
6035                 rc = -ENXIO;
6036         }
6037
6038
6039         mutex_unlock(&fan_mutex);
6040         return rc;
6041 }
6042
6043 static int fan_set_speed(int speed)
6044 {
6045         int rc;
6046
6047         if (!fan_control_allowed)
6048                 return -EPERM;
6049
6050         if (mutex_lock_interruptible(&fan_mutex))
6051                 return -ERESTARTSYS;
6052
6053         rc = 0;
6054         switch (fan_control_access_mode) {
6055         case TPACPI_FAN_WR_ACPI_FANS:
6056                 if (speed >= 0 && speed <= 65535) {
6057                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
6058                                         speed, speed, speed))
6059                                 rc = -EIO;
6060                 } else
6061                         rc = -EINVAL;
6062                 break;
6063
6064         default:
6065                 rc = -ENXIO;
6066         }
6067
6068         mutex_unlock(&fan_mutex);
6069         return rc;
6070 }
6071
6072 static void fan_watchdog_reset(void)
6073 {
6074         static int fan_watchdog_active;
6075
6076         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
6077                 return;
6078
6079         if (fan_watchdog_active)
6080                 cancel_delayed_work(&fan_watchdog_task);
6081
6082         if (fan_watchdog_maxinterval > 0 &&
6083             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
6084                 fan_watchdog_active = 1;
6085                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
6086                                 msecs_to_jiffies(fan_watchdog_maxinterval
6087                                                  * 1000))) {
6088                         printk(TPACPI_ERR
6089                                "failed to queue the fan watchdog, "
6090                                "watchdog will not trigger\n");
6091                 }
6092         } else
6093                 fan_watchdog_active = 0;
6094 }
6095
6096 static void fan_watchdog_fire(struct work_struct *ignored)
6097 {
6098         int rc;
6099
6100         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
6101                 return;
6102
6103         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
6104         rc = fan_set_enable();
6105         if (rc < 0) {
6106                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
6107                         "will try again later...\n", -rc);
6108                 /* reschedule for later */
6109                 fan_watchdog_reset();
6110         }
6111 }
6112
6113 /*
6114  * SYSFS fan layout: hwmon compatible (device)
6115  *
6116  * pwm*_enable:
6117  *      0: "disengaged" mode
6118  *      1: manual mode
6119  *      2: native EC "auto" mode (recommended, hardware default)
6120  *
6121  * pwm*: set speed in manual mode, ignored otherwise.
6122  *      0 is level 0; 255 is level 7. Intermediate points done with linear
6123  *      interpolation.
6124  *
6125  * fan*_input: tachometer reading, RPM
6126  *
6127  *
6128  * SYSFS fan layout: extensions
6129  *
6130  * fan_watchdog (driver):
6131  *      fan watchdog interval in seconds, 0 disables (default), max 120
6132  */
6133
6134 /* sysfs fan pwm1_enable ----------------------------------------------- */
6135 static ssize_t fan_pwm1_enable_show(struct device *dev,
6136                                     struct device_attribute *attr,
6137                                     char *buf)
6138 {
6139         int res, mode;
6140         u8 status;
6141
6142         res = fan_get_status_safe(&status);
6143         if (res)
6144                 return res;
6145
6146         if (unlikely(tp_features.fan_ctrl_status_undef)) {
6147                 if (status != fan_control_initial_status) {
6148                         tp_features.fan_ctrl_status_undef = 0;
6149                 } else {
6150                         /* Return most likely status. In fact, it
6151                          * might be the only possible status */
6152                         status = TP_EC_FAN_AUTO;
6153                 }
6154         }
6155
6156         if (status & TP_EC_FAN_FULLSPEED) {
6157                 mode = 0;
6158         } else if (status & TP_EC_FAN_AUTO) {
6159                 mode = 2;
6160         } else
6161                 mode = 1;
6162
6163         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
6164 }
6165
6166 static ssize_t fan_pwm1_enable_store(struct device *dev,
6167                                      struct device_attribute *attr,
6168                                      const char *buf, size_t count)
6169 {
6170         unsigned long t;
6171         int res, level;
6172
6173         if (parse_strtoul(buf, 2, &t))
6174                 return -EINVAL;
6175
6176         switch (t) {
6177         case 0:
6178                 level = TP_EC_FAN_FULLSPEED;
6179                 break;
6180         case 1:
6181                 level = TPACPI_FAN_LAST_LEVEL;
6182                 break;
6183         case 2:
6184                 level = TP_EC_FAN_AUTO;
6185                 break;
6186         case 3:
6187                 /* reserved for software-controlled auto mode */
6188                 return -ENOSYS;
6189         default:
6190                 return -EINVAL;
6191         }
6192
6193         res = fan_set_level_safe(level);
6194         if (res == -ENXIO)
6195                 return -EINVAL;
6196         else if (res < 0)
6197                 return res;
6198
6199         fan_watchdog_reset();
6200
6201         return count;
6202 }
6203
6204 static struct device_attribute dev_attr_fan_pwm1_enable =
6205         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
6206                 fan_pwm1_enable_show, fan_pwm1_enable_store);
6207
6208 /* sysfs fan pwm1 ------------------------------------------------------ */
6209 static ssize_t fan_pwm1_show(struct device *dev,
6210                              struct device_attribute *attr,
6211                              char *buf)
6212 {
6213         int res;
6214         u8 status;
6215
6216         res = fan_get_status_safe(&status);
6217         if (res)
6218                 return res;
6219
6220         if (unlikely(tp_features.fan_ctrl_status_undef)) {
6221                 if (status != fan_control_initial_status) {
6222                         tp_features.fan_ctrl_status_undef = 0;
6223                 } else {
6224                         status = TP_EC_FAN_AUTO;
6225                 }
6226         }
6227
6228         if ((status &
6229              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
6230                 status = fan_control_desired_level;
6231
6232         if (status > 7)
6233                 status = 7;
6234
6235         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
6236 }
6237
6238 static ssize_t fan_pwm1_store(struct device *dev,
6239                               struct device_attribute *attr,
6240                               const char *buf, size_t count)
6241 {
6242         unsigned long s;
6243         int rc;
6244         u8 status, newlevel;
6245
6246         if (parse_strtoul(buf, 255, &s))
6247                 return -EINVAL;
6248
6249         /* scale down from 0-255 to 0-7 */
6250         newlevel = (s >> 5) & 0x07;
6251
6252         if (mutex_lock_interruptible(&fan_mutex))
6253                 return -ERESTARTSYS;
6254
6255         rc = fan_get_status(&status);
6256         if (!rc && (status &
6257                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
6258                 rc = fan_set_level(newlevel);
6259                 if (rc == -ENXIO)
6260                         rc = -EINVAL;
6261                 else if (!rc) {
6262                         fan_update_desired_level(newlevel);
6263                         fan_watchdog_reset();
6264                 }
6265         }
6266
6267         mutex_unlock(&fan_mutex);
6268         return (rc)? rc : count;
6269 }
6270
6271 static struct device_attribute dev_attr_fan_pwm1 =
6272         __ATTR(pwm1, S_IWUSR | S_IRUGO,
6273                 fan_pwm1_show, fan_pwm1_store);
6274
6275 /* sysfs fan fan1_input ------------------------------------------------ */
6276 static ssize_t fan_fan1_input_show(struct device *dev,
6277                            struct device_attribute *attr,
6278                            char *buf)
6279 {
6280         int res;
6281         unsigned int speed;
6282
6283         res = fan_get_speed(&speed);
6284         if (res < 0)
6285                 return res;
6286
6287         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
6288 }
6289
6290 static struct device_attribute dev_attr_fan_fan1_input =
6291         __ATTR(fan1_input, S_IRUGO,
6292                 fan_fan1_input_show, NULL);
6293
6294 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
6295 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
6296                                      char *buf)
6297 {
6298         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
6299 }
6300
6301 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
6302                                       const char *buf, size_t count)
6303 {
6304         unsigned long t;
6305
6306         if (parse_strtoul(buf, 120, &t))
6307                 return -EINVAL;
6308
6309         if (!fan_control_allowed)
6310                 return -EPERM;
6311
6312         fan_watchdog_maxinterval = t;
6313         fan_watchdog_reset();
6314
6315         return count;
6316 }
6317
6318 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
6319                 fan_fan_watchdog_show, fan_fan_watchdog_store);
6320
6321 /* --------------------------------------------------------------------- */
6322 static struct attribute *fan_attributes[] = {
6323         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
6324         &dev_attr_fan_fan1_input.attr,
6325         NULL
6326 };
6327
6328 static const struct attribute_group fan_attr_group = {
6329         .attrs = fan_attributes,
6330 };
6331
6332 static int __init fan_init(struct ibm_init_struct *iibm)
6333 {
6334         int rc;
6335
6336         vdbg_printk(TPACPI_DBG_INIT, "initializing fan subdriver\n");
6337
6338         mutex_init(&fan_mutex);
6339         fan_status_access_mode = TPACPI_FAN_NONE;
6340         fan_control_access_mode = TPACPI_FAN_WR_NONE;
6341         fan_control_commands = 0;
6342         fan_watchdog_maxinterval = 0;
6343         tp_features.fan_ctrl_status_undef = 0;
6344         fan_control_desired_level = 7;
6345
6346         TPACPI_ACPIHANDLE_INIT(fans);
6347         TPACPI_ACPIHANDLE_INIT(gfan);
6348         TPACPI_ACPIHANDLE_INIT(sfan);
6349
6350         if (gfan_handle) {
6351                 /* 570, 600e/x, 770e, 770x */
6352                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
6353         } else {
6354                 /* all other ThinkPads: note that even old-style
6355                  * ThinkPad ECs supports the fan control register */
6356                 if (likely(acpi_ec_read(fan_status_offset,
6357                                         &fan_control_initial_status))) {
6358                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
6359
6360                         /* In some ThinkPads, neither the EC nor the ACPI
6361                          * DSDT initialize the fan status, and it ends up
6362                          * being set to 0x07 when it *could* be either
6363                          * 0x07 or 0x80.
6364                          *
6365                          * Enable for TP-1Y (T43), TP-78 (R51e),
6366                          * TP-76 (R52), TP-70 (T43, R52), which are known
6367                          * to be buggy. */
6368                         if (fan_control_initial_status == 0x07) {
6369                                 switch (thinkpad_id.ec_model) {
6370                                 case 0x5931: /* TP-1Y */
6371                                 case 0x3837: /* TP-78 */
6372                                 case 0x3637: /* TP-76 */
6373                                 case 0x3037: /* TP-70 */
6374                                         printk(TPACPI_NOTICE
6375                                                "fan_init: initial fan status "
6376                                                "is unknown, assuming it is "
6377                                                "in auto mode\n");
6378                                         tp_features.fan_ctrl_status_undef = 1;
6379                                         ;;
6380                                 }
6381                         }
6382                 } else {
6383                         printk(TPACPI_ERR
6384                                "ThinkPad ACPI EC access misbehaving, "
6385                                "fan status and control unavailable\n");
6386                         return 1;
6387                 }
6388         }
6389
6390         if (sfan_handle) {
6391                 /* 570, 770x-JL */
6392                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
6393                 fan_control_commands |=
6394                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
6395         } else {
6396                 if (!gfan_handle) {
6397                         /* gfan without sfan means no fan control */
6398                         /* all other models implement TP EC 0x2f control */
6399
6400                         if (fans_handle) {
6401                                 /* X31, X40, X41 */
6402                                 fan_control_access_mode =
6403                                     TPACPI_FAN_WR_ACPI_FANS;
6404                                 fan_control_commands |=
6405                                     TPACPI_FAN_CMD_SPEED |
6406                                     TPACPI_FAN_CMD_LEVEL |
6407                                     TPACPI_FAN_CMD_ENABLE;
6408                         } else {
6409                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
6410                                 fan_control_commands |=
6411                                     TPACPI_FAN_CMD_LEVEL |
6412                                     TPACPI_FAN_CMD_ENABLE;
6413                         }
6414                 }
6415         }
6416
6417         vdbg_printk(TPACPI_DBG_INIT, "fan is %s, modes %d, %d\n",
6418                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
6419                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
6420                 fan_status_access_mode, fan_control_access_mode);
6421
6422         /* fan control master switch */
6423         if (!fan_control_allowed) {
6424                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
6425                 fan_control_commands = 0;
6426                 dbg_printk(TPACPI_DBG_INIT,
6427                            "fan control features disabled by parameter\n");
6428         }
6429
6430         /* update fan_control_desired_level */
6431         if (fan_status_access_mode != TPACPI_FAN_NONE)
6432                 fan_get_status_safe(NULL);
6433
6434         if (fan_status_access_mode != TPACPI_FAN_NONE ||
6435             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
6436                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
6437                                          &fan_attr_group);
6438                 if (rc < 0)
6439                         return rc;
6440
6441                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
6442                                         &driver_attr_fan_watchdog);
6443                 if (rc < 0) {
6444                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
6445                                         &fan_attr_group);
6446                         return rc;
6447                 }
6448                 return 0;
6449         } else
6450                 return 1;
6451 }
6452
6453 static void fan_exit(void)
6454 {
6455         vdbg_printk(TPACPI_DBG_EXIT,
6456                     "cancelling any pending fan watchdog tasks\n");
6457
6458         /* FIXME: can we really do this unconditionally? */
6459         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
6460         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
6461                            &driver_attr_fan_watchdog);
6462
6463         cancel_delayed_work(&fan_watchdog_task);
6464         flush_workqueue(tpacpi_wq);
6465 }
6466
6467 static void fan_suspend(pm_message_t state)
6468 {
6469         int rc;
6470
6471         if (!fan_control_allowed)
6472                 return;
6473
6474         /* Store fan status in cache */
6475         fan_control_resume_level = 0;
6476         rc = fan_get_status_safe(&fan_control_resume_level);
6477         if (rc < 0)
6478                 printk(TPACPI_NOTICE
6479                         "failed to read fan level for later "
6480                         "restore during resume: %d\n", rc);
6481
6482         /* if it is undefined, don't attempt to restore it.
6483          * KEEP THIS LAST */
6484         if (tp_features.fan_ctrl_status_undef)
6485                 fan_control_resume_level = 0;
6486 }
6487
6488 static void fan_resume(void)
6489 {
6490         u8 current_level = 7;
6491         bool do_set = false;
6492         int rc;
6493
6494         /* DSDT *always* updates status on resume */
6495         tp_features.fan_ctrl_status_undef = 0;
6496
6497         if (!fan_control_allowed ||
6498             !fan_control_resume_level ||
6499             (fan_get_status_safe(&current_level) < 0))
6500                 return;
6501
6502         switch (fan_control_access_mode) {
6503         case TPACPI_FAN_WR_ACPI_SFAN:
6504                 /* never decrease fan level */
6505                 do_set = (fan_control_resume_level > current_level);
6506                 break;
6507         case TPACPI_FAN_WR_ACPI_FANS:
6508         case TPACPI_FAN_WR_TPEC:
6509                 /* never decrease fan level, scale is:
6510                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
6511                  *
6512                  * We expect the firmware to set either 7 or AUTO, but we
6513                  * handle FULLSPEED out of paranoia.
6514                  *
6515                  * So, we can safely only restore FULLSPEED or 7, anything
6516                  * else could slow the fan.  Restoring AUTO is useless, at
6517                  * best that's exactly what the DSDT already set (it is the
6518                  * slower it uses).
6519                  *
6520                  * Always keep in mind that the DSDT *will* have set the
6521                  * fans to what the vendor supposes is the best level.  We
6522                  * muck with it only to speed the fan up.
6523                  */
6524                 if (fan_control_resume_level != 7 &&
6525                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
6526                         return;
6527                 else
6528                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
6529                                  (current_level != fan_control_resume_level);
6530                 break;
6531         default:
6532                 return;
6533         }
6534         if (do_set) {
6535                 printk(TPACPI_NOTICE
6536                         "restoring fan level to 0x%02x\n",
6537                         fan_control_resume_level);
6538                 rc = fan_set_level_safe(fan_control_resume_level);
6539                 if (rc < 0)
6540                         printk(TPACPI_NOTICE
6541                                 "failed to restore fan level: %d\n", rc);
6542         }
6543 }
6544
6545 static int fan_read(char *p)
6546 {
6547         int len = 0;
6548         int rc;
6549         u8 status;
6550         unsigned int speed = 0;
6551
6552         switch (fan_status_access_mode) {
6553         case TPACPI_FAN_RD_ACPI_GFAN:
6554                 /* 570, 600e/x, 770e, 770x */
6555                 rc = fan_get_status_safe(&status);
6556                 if (rc < 0)
6557                         return rc;
6558
6559                 len += sprintf(p + len, "status:\t\t%s\n"
6560                                "level:\t\t%d\n",
6561                                (status != 0) ? "enabled" : "disabled", status);
6562                 break;
6563
6564         case TPACPI_FAN_RD_TPEC:
6565                 /* all except 570, 600e/x, 770e, 770x */
6566                 rc = fan_get_status_safe(&status);
6567                 if (rc < 0)
6568                         return rc;
6569
6570                 if (unlikely(tp_features.fan_ctrl_status_undef)) {
6571                         if (status != fan_control_initial_status)
6572                                 tp_features.fan_ctrl_status_undef = 0;
6573                         else
6574                                 /* Return most likely status. In fact, it
6575                                  * might be the only possible status */
6576                                 status = TP_EC_FAN_AUTO;
6577                 }
6578
6579                 len += sprintf(p + len, "status:\t\t%s\n",
6580                                (status != 0) ? "enabled" : "disabled");
6581
6582                 rc = fan_get_speed(&speed);
6583                 if (rc < 0)
6584                         return rc;
6585
6586                 len += sprintf(p + len, "speed:\t\t%d\n", speed);
6587
6588                 if (status & TP_EC_FAN_FULLSPEED)
6589                         /* Disengaged mode takes precedence */
6590                         len += sprintf(p + len, "level:\t\tdisengaged\n");
6591                 else if (status & TP_EC_FAN_AUTO)
6592                         len += sprintf(p + len, "level:\t\tauto\n");
6593                 else
6594                         len += sprintf(p + len, "level:\t\t%d\n", status);
6595                 break;
6596
6597         case TPACPI_FAN_NONE:
6598         default:
6599                 len += sprintf(p + len, "status:\t\tnot supported\n");
6600         }
6601
6602         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
6603                 len += sprintf(p + len, "commands:\tlevel <level>");
6604
6605                 switch (fan_control_access_mode) {
6606                 case TPACPI_FAN_WR_ACPI_SFAN:
6607                         len += sprintf(p + len, " (<level> is 0-7)\n");
6608                         break;
6609
6610                 default:
6611                         len += sprintf(p + len, " (<level> is 0-7, "
6612                                        "auto, disengaged, full-speed)\n");
6613                         break;
6614                 }
6615         }
6616
6617         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
6618                 len += sprintf(p + len, "commands:\tenable, disable\n"
6619                                "commands:\twatchdog <timeout> (<timeout> "
6620                                "is 0 (off), 1-120 (seconds))\n");
6621
6622         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
6623                 len += sprintf(p + len, "commands:\tspeed <speed>"
6624                                " (<speed> is 0-65535)\n");
6625
6626         return len;
6627 }
6628
6629 static int fan_write_cmd_level(const char *cmd, int *rc)
6630 {
6631         int level;
6632
6633         if (strlencmp(cmd, "level auto") == 0)
6634                 level = TP_EC_FAN_AUTO;
6635         else if ((strlencmp(cmd, "level disengaged") == 0) |
6636                         (strlencmp(cmd, "level full-speed") == 0))
6637                 level = TP_EC_FAN_FULLSPEED;
6638         else if (sscanf(cmd, "level %d", &level) != 1)
6639                 return 0;
6640
6641         *rc = fan_set_level_safe(level);
6642         if (*rc == -ENXIO)
6643                 printk(TPACPI_ERR "level command accepted for unsupported "
6644                        "access mode %d", fan_control_access_mode);
6645
6646         return 1;
6647 }
6648
6649 static int fan_write_cmd_enable(const char *cmd, int *rc)
6650 {
6651         if (strlencmp(cmd, "enable") != 0)
6652                 return 0;
6653
6654         *rc = fan_set_enable();
6655         if (*rc == -ENXIO)
6656                 printk(TPACPI_ERR "enable command accepted for unsupported "
6657                        "access mode %d", fan_control_access_mode);
6658
6659         return 1;
6660 }
6661
6662 static int fan_write_cmd_disable(const char *cmd, int *rc)
6663 {
6664         if (strlencmp(cmd, "disable") != 0)
6665                 return 0;
6666
6667         *rc = fan_set_disable();
6668         if (*rc == -ENXIO)
6669                 printk(TPACPI_ERR "disable command accepted for unsupported "
6670                        "access mode %d", fan_control_access_mode);
6671
6672         return 1;
6673 }
6674
6675 static int fan_write_cmd_speed(const char *cmd, int *rc)
6676 {
6677         int speed;
6678
6679         /* TODO:
6680          * Support speed <low> <medium> <high> ? */
6681
6682         if (sscanf(cmd, "speed %d", &speed) != 1)
6683                 return 0;
6684
6685         *rc = fan_set_speed(speed);
6686         if (*rc == -ENXIO)
6687                 printk(TPACPI_ERR "speed command accepted for unsupported "
6688                        "access mode %d", fan_control_access_mode);
6689
6690         return 1;
6691 }
6692
6693 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
6694 {
6695         int interval;
6696
6697         if (sscanf(cmd, "watchdog %d", &interval) != 1)
6698                 return 0;
6699
6700         if (interval < 0 || interval > 120)
6701                 *rc = -EINVAL;
6702         else
6703                 fan_watchdog_maxinterval = interval;
6704
6705         return 1;
6706 }
6707
6708 static int fan_write(char *buf)
6709 {
6710         char *cmd;
6711         int rc = 0;
6712
6713         while (!rc && (cmd = next_cmd(&buf))) {
6714                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
6715                       fan_write_cmd_level(cmd, &rc)) &&
6716                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
6717                       (fan_write_cmd_enable(cmd, &rc) ||
6718                        fan_write_cmd_disable(cmd, &rc) ||
6719                        fan_write_cmd_watchdog(cmd, &rc))) &&
6720                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
6721                       fan_write_cmd_speed(cmd, &rc))
6722                     )
6723                         rc = -EINVAL;
6724                 else if (!rc)
6725                         fan_watchdog_reset();
6726         }
6727
6728         return rc;
6729 }
6730
6731 static struct ibm_struct fan_driver_data = {
6732         .name = "fan",
6733         .read = fan_read,
6734         .write = fan_write,
6735         .exit = fan_exit,
6736         .suspend = fan_suspend,
6737         .resume = fan_resume,
6738 };
6739
6740 /****************************************************************************
6741  ****************************************************************************
6742  *
6743  * Infrastructure
6744  *
6745  ****************************************************************************
6746  ****************************************************************************/
6747
6748 /* sysfs name ---------------------------------------------------------- */
6749 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
6750                            struct device_attribute *attr,
6751                            char *buf)
6752 {
6753         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
6754 }
6755
6756 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
6757         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
6758
6759 /* --------------------------------------------------------------------- */
6760
6761 /* /proc support */
6762 static struct proc_dir_entry *proc_dir;
6763
6764 /*
6765  * Module and infrastructure proble, init and exit handling
6766  */
6767
6768 static int force_load;
6769
6770 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
6771 static const char * __init str_supported(int is_supported)
6772 {
6773         static char text_unsupported[] __initdata = "not supported";
6774
6775         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
6776 }
6777 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
6778
6779 static void ibm_exit(struct ibm_struct *ibm)
6780 {
6781         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
6782
6783         list_del_init(&ibm->all_drivers);
6784
6785         if (ibm->flags.acpi_notify_installed) {
6786                 dbg_printk(TPACPI_DBG_EXIT,
6787                         "%s: acpi_remove_notify_handler\n", ibm->name);
6788                 BUG_ON(!ibm->acpi);
6789                 acpi_remove_notify_handler(*ibm->acpi->handle,
6790                                            ibm->acpi->type,
6791                                            dispatch_acpi_notify);
6792                 ibm->flags.acpi_notify_installed = 0;
6793                 ibm->flags.acpi_notify_installed = 0;
6794         }
6795
6796         if (ibm->flags.proc_created) {
6797                 dbg_printk(TPACPI_DBG_EXIT,
6798                         "%s: remove_proc_entry\n", ibm->name);
6799                 remove_proc_entry(ibm->name, proc_dir);
6800                 ibm->flags.proc_created = 0;
6801         }
6802
6803         if (ibm->flags.acpi_driver_registered) {
6804                 dbg_printk(TPACPI_DBG_EXIT,
6805                         "%s: acpi_bus_unregister_driver\n", ibm->name);
6806                 BUG_ON(!ibm->acpi);
6807                 acpi_bus_unregister_driver(ibm->acpi->driver);
6808                 kfree(ibm->acpi->driver);
6809                 ibm->acpi->driver = NULL;
6810                 ibm->flags.acpi_driver_registered = 0;
6811         }
6812
6813         if (ibm->flags.init_called && ibm->exit) {
6814                 ibm->exit();
6815                 ibm->flags.init_called = 0;
6816         }
6817
6818         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
6819 }
6820
6821 static int __init ibm_init(struct ibm_init_struct *iibm)
6822 {
6823         int ret;
6824         struct ibm_struct *ibm = iibm->data;
6825         struct proc_dir_entry *entry;
6826
6827         BUG_ON(ibm == NULL);
6828
6829         INIT_LIST_HEAD(&ibm->all_drivers);
6830
6831         if (ibm->flags.experimental && !experimental)
6832                 return 0;
6833
6834         dbg_printk(TPACPI_DBG_INIT,
6835                 "probing for %s\n", ibm->name);
6836
6837         if (iibm->init) {
6838                 ret = iibm->init(iibm);
6839                 if (ret > 0)
6840                         return 0;       /* probe failed */
6841                 if (ret)
6842                         return ret;
6843
6844                 ibm->flags.init_called = 1;
6845         }
6846
6847         if (ibm->acpi) {
6848                 if (ibm->acpi->hid) {
6849                         ret = register_tpacpi_subdriver(ibm);
6850                         if (ret)
6851                                 goto err_out;
6852                 }
6853
6854                 if (ibm->acpi->notify) {
6855                         ret = setup_acpi_notify(ibm);
6856                         if (ret == -ENODEV) {
6857                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
6858                                         ibm->name);
6859                                 ret = 0;
6860                                 goto err_out;
6861                         }
6862                         if (ret < 0)
6863                                 goto err_out;
6864                 }
6865         }
6866
6867         dbg_printk(TPACPI_DBG_INIT,
6868                 "%s installed\n", ibm->name);
6869
6870         if (ibm->read) {
6871                 entry = create_proc_entry(ibm->name,
6872                                           S_IFREG | S_IRUGO | S_IWUSR,
6873                                           proc_dir);
6874                 if (!entry) {
6875                         printk(TPACPI_ERR "unable to create proc entry %s\n",
6876                                ibm->name);
6877                         ret = -ENODEV;
6878                         goto err_out;
6879                 }
6880                 entry->owner = THIS_MODULE;
6881                 entry->data = ibm;
6882                 entry->read_proc = &dispatch_procfs_read;
6883                 if (ibm->write)
6884                         entry->write_proc = &dispatch_procfs_write;
6885                 ibm->flags.proc_created = 1;
6886         }
6887
6888         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
6889
6890         return 0;
6891
6892 err_out:
6893         dbg_printk(TPACPI_DBG_INIT,
6894                 "%s: at error exit path with result %d\n",
6895                 ibm->name, ret);
6896
6897         ibm_exit(ibm);
6898         return (ret < 0)? ret : 0;
6899 }
6900
6901 /* Probing */
6902
6903 /* returns 0 - probe ok, or < 0 - probe error.
6904  * Probe ok doesn't mean thinkpad found.
6905  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
6906 static int __must_check __init get_thinkpad_model_data(
6907                                                 struct thinkpad_id_data *tp)
6908 {
6909         const struct dmi_device *dev = NULL;
6910         char ec_fw_string[18];
6911         char const *s;
6912
6913         if (!tp)
6914                 return -EINVAL;
6915
6916         memset(tp, 0, sizeof(*tp));
6917
6918         if (dmi_name_in_vendors("IBM"))
6919                 tp->vendor = PCI_VENDOR_ID_IBM;
6920         else if (dmi_name_in_vendors("LENOVO"))
6921                 tp->vendor = PCI_VENDOR_ID_LENOVO;
6922         else
6923                 return 0;
6924
6925         s = dmi_get_system_info(DMI_BIOS_VERSION);
6926         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
6927         if (s && !tp->bios_version_str)
6928                 return -ENOMEM;
6929         if (!tp->bios_version_str)
6930                 return 0;
6931         tp->bios_model = tp->bios_version_str[0]
6932                          | (tp->bios_version_str[1] << 8);
6933
6934         /*
6935          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
6936          * X32 or newer, all Z series;  Some models must have an
6937          * up-to-date BIOS or they will not be detected.
6938          *
6939          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
6940          */
6941         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
6942                 if (sscanf(dev->name,
6943                            "IBM ThinkPad Embedded Controller -[%17c",
6944                            ec_fw_string) == 1) {
6945                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
6946                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
6947
6948                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
6949                         if (!tp->ec_version_str)
6950                                 return -ENOMEM;
6951                         tp->ec_model = ec_fw_string[0]
6952                                         | (ec_fw_string[1] << 8);
6953                         break;
6954                 }
6955         }
6956
6957         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
6958         if (s && !strnicmp(s, "ThinkPad", 8)) {
6959                 tp->model_str = kstrdup(s, GFP_KERNEL);
6960                 if (!tp->model_str)
6961                         return -ENOMEM;
6962         }
6963
6964         s = dmi_get_system_info(DMI_PRODUCT_NAME);
6965         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
6966         if (s && !tp->nummodel_str)
6967                 return -ENOMEM;
6968
6969         return 0;
6970 }
6971
6972 static int __init probe_for_thinkpad(void)
6973 {
6974         int is_thinkpad;
6975
6976         if (acpi_disabled)
6977                 return -ENODEV;
6978
6979         /*
6980          * Non-ancient models have better DMI tagging, but very old models
6981          * don't.
6982          */
6983         is_thinkpad = (thinkpad_id.model_str != NULL);
6984
6985         /* ec is required because many other handles are relative to it */
6986         TPACPI_ACPIHANDLE_INIT(ec);
6987         if (!ec_handle) {
6988                 if (is_thinkpad)
6989                         printk(TPACPI_ERR
6990                                 "Not yet supported ThinkPad detected!\n");
6991                 return -ENODEV;
6992         }
6993
6994         /*
6995          * Risks a regression on very old machines, but reduces potential
6996          * false positives a damn great deal
6997          */
6998         if (!is_thinkpad)
6999                 is_thinkpad = (thinkpad_id.vendor == PCI_VENDOR_ID_IBM);
7000
7001         if (!is_thinkpad && !force_load)
7002                 return -ENODEV;
7003
7004         return 0;
7005 }
7006
7007
7008 /* Module init, exit, parameters */
7009
7010 static struct ibm_init_struct ibms_init[] __initdata = {
7011         {
7012                 .init = thinkpad_acpi_driver_init,
7013                 .data = &thinkpad_acpi_driver_data,
7014         },
7015         {
7016                 .init = hotkey_init,
7017                 .data = &hotkey_driver_data,
7018         },
7019         {
7020                 .init = bluetooth_init,
7021                 .data = &bluetooth_driver_data,
7022         },
7023         {
7024                 .init = wan_init,
7025                 .data = &wan_driver_data,
7026         },
7027         {
7028                 .init = uwb_init,
7029                 .data = &uwb_driver_data,
7030         },
7031 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
7032         {
7033                 .init = video_init,
7034                 .data = &video_driver_data,
7035         },
7036 #endif
7037         {
7038                 .init = light_init,
7039                 .data = &light_driver_data,
7040         },
7041 #ifdef CONFIG_THINKPAD_ACPI_DOCK
7042         {
7043                 .init = dock_init,
7044                 .data = &dock_driver_data[0],
7045         },
7046         {
7047                 .init = dock_init2,
7048                 .data = &dock_driver_data[1],
7049         },
7050 #endif
7051 #ifdef CONFIG_THINKPAD_ACPI_BAY
7052         {
7053                 .init = bay_init,
7054                 .data = &bay_driver_data,
7055         },
7056 #endif
7057         {
7058                 .init = cmos_init,
7059                 .data = &cmos_driver_data,
7060         },
7061         {
7062                 .init = led_init,
7063                 .data = &led_driver_data,
7064         },
7065         {
7066                 .init = beep_init,
7067                 .data = &beep_driver_data,
7068         },
7069         {
7070                 .init = thermal_init,
7071                 .data = &thermal_driver_data,
7072         },
7073         {
7074                 .data = &ecdump_driver_data,
7075         },
7076         {
7077                 .init = brightness_init,
7078                 .data = &brightness_driver_data,
7079         },
7080         {
7081                 .data = &volume_driver_data,
7082         },
7083         {
7084                 .init = fan_init,
7085                 .data = &fan_driver_data,
7086         },
7087 };
7088
7089 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
7090 {
7091         unsigned int i;
7092         struct ibm_struct *ibm;
7093
7094         if (!kp || !kp->name || !val)
7095                 return -EINVAL;
7096
7097         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
7098                 ibm = ibms_init[i].data;
7099                 WARN_ON(ibm == NULL);
7100
7101                 if (!ibm || !ibm->name)
7102                         continue;
7103
7104                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
7105                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
7106                                 return -ENOSPC;
7107                         strcpy(ibms_init[i].param, val);
7108                         strcat(ibms_init[i].param, ",");
7109                         return 0;
7110                 }
7111         }
7112
7113         return -EINVAL;
7114 }
7115
7116 module_param(experimental, int, 0);
7117 MODULE_PARM_DESC(experimental,
7118                  "Enables experimental features when non-zero");
7119
7120 module_param_named(debug, dbg_level, uint, 0);
7121 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
7122
7123 module_param(force_load, bool, 0);
7124 MODULE_PARM_DESC(force_load,
7125                  "Attempts to load the driver even on a "
7126                  "mis-identified ThinkPad when true");
7127
7128 module_param_named(fan_control, fan_control_allowed, bool, 0);
7129 MODULE_PARM_DESC(fan_control,
7130                  "Enables setting fan parameters features when true");
7131
7132 module_param_named(brightness_mode, brightness_mode, int, 0);
7133 MODULE_PARM_DESC(brightness_mode,
7134                  "Selects brightness control strategy: "
7135                  "0=auto, 1=EC, 2=CMOS, 3=both");
7136
7137 module_param(brightness_enable, uint, 0);
7138 MODULE_PARM_DESC(brightness_enable,
7139                  "Enables backlight control when 1, disables when 0");
7140
7141 module_param(hotkey_report_mode, uint, 0);
7142 MODULE_PARM_DESC(hotkey_report_mode,
7143                  "used for backwards compatibility with userspace, "
7144                  "see documentation");
7145
7146 #define TPACPI_PARAM(feature) \
7147         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
7148         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
7149                          "at module load, see documentation")
7150
7151 TPACPI_PARAM(hotkey);
7152 TPACPI_PARAM(bluetooth);
7153 TPACPI_PARAM(video);
7154 TPACPI_PARAM(light);
7155 #ifdef CONFIG_THINKPAD_ACPI_DOCK
7156 TPACPI_PARAM(dock);
7157 #endif
7158 #ifdef CONFIG_THINKPAD_ACPI_BAY
7159 TPACPI_PARAM(bay);
7160 #endif /* CONFIG_THINKPAD_ACPI_BAY */
7161 TPACPI_PARAM(cmos);
7162 TPACPI_PARAM(led);
7163 TPACPI_PARAM(beep);
7164 TPACPI_PARAM(ecdump);
7165 TPACPI_PARAM(brightness);
7166 TPACPI_PARAM(volume);
7167 TPACPI_PARAM(fan);
7168
7169 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
7170 module_param(dbg_wlswemul, uint, 0);
7171 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
7172 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
7173 MODULE_PARM_DESC(wlsw_state,
7174                  "Initial state of the emulated WLSW switch");
7175
7176 module_param(dbg_bluetoothemul, uint, 0);
7177 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
7178 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
7179 MODULE_PARM_DESC(bluetooth_state,
7180                  "Initial state of the emulated bluetooth switch");
7181
7182 module_param(dbg_wwanemul, uint, 0);
7183 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
7184 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
7185 MODULE_PARM_DESC(wwan_state,
7186                  "Initial state of the emulated WWAN switch");
7187
7188 module_param(dbg_uwbemul, uint, 0);
7189 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
7190 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
7191 MODULE_PARM_DESC(uwb_state,
7192                  "Initial state of the emulated UWB switch");
7193 #endif
7194
7195 static void thinkpad_acpi_module_exit(void)
7196 {
7197         struct ibm_struct *ibm, *itmp;
7198
7199         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
7200
7201         list_for_each_entry_safe_reverse(ibm, itmp,
7202                                          &tpacpi_all_drivers,
7203                                          all_drivers) {
7204                 ibm_exit(ibm);
7205         }
7206
7207         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
7208
7209         if (tpacpi_inputdev) {
7210                 if (tp_features.input_device_registered)
7211                         input_unregister_device(tpacpi_inputdev);
7212                 else
7213                         input_free_device(tpacpi_inputdev);
7214         }
7215
7216         if (tpacpi_hwmon)
7217                 hwmon_device_unregister(tpacpi_hwmon);
7218
7219         if (tp_features.sensors_pdev_attrs_registered)
7220                 device_remove_file(&tpacpi_sensors_pdev->dev,
7221                                    &dev_attr_thinkpad_acpi_pdev_name);
7222         if (tpacpi_sensors_pdev)
7223                 platform_device_unregister(tpacpi_sensors_pdev);
7224         if (tpacpi_pdev)
7225                 platform_device_unregister(tpacpi_pdev);
7226
7227         if (tp_features.sensors_pdrv_attrs_registered)
7228                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
7229         if (tp_features.platform_drv_attrs_registered)
7230                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
7231
7232         if (tp_features.sensors_pdrv_registered)
7233                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
7234
7235         if (tp_features.platform_drv_registered)
7236                 platform_driver_unregister(&tpacpi_pdriver);
7237
7238         if (proc_dir)
7239                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
7240
7241         if (tpacpi_wq)
7242                 destroy_workqueue(tpacpi_wq);
7243
7244         kfree(thinkpad_id.bios_version_str);
7245         kfree(thinkpad_id.ec_version_str);
7246         kfree(thinkpad_id.model_str);
7247 }
7248
7249
7250 static int __init thinkpad_acpi_module_init(void)
7251 {
7252         int ret, i;
7253
7254         tpacpi_lifecycle = TPACPI_LIFE_INIT;
7255
7256         /* Parameter checking */
7257         if (hotkey_report_mode > 2)
7258                 return -EINVAL;
7259
7260         /* Driver-level probe */
7261
7262         ret = get_thinkpad_model_data(&thinkpad_id);
7263         if (ret) {
7264                 printk(TPACPI_ERR
7265                         "unable to get DMI data: %d\n", ret);
7266                 thinkpad_acpi_module_exit();
7267                 return ret;
7268         }
7269         ret = probe_for_thinkpad();
7270         if (ret) {
7271                 thinkpad_acpi_module_exit();
7272                 return ret;
7273         }
7274
7275         /* Driver initialization */
7276
7277         TPACPI_ACPIHANDLE_INIT(ecrd);
7278         TPACPI_ACPIHANDLE_INIT(ecwr);
7279
7280         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
7281         if (!tpacpi_wq) {
7282                 thinkpad_acpi_module_exit();
7283                 return -ENOMEM;
7284         }
7285
7286         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
7287         if (!proc_dir) {
7288                 printk(TPACPI_ERR
7289                        "unable to create proc dir " TPACPI_PROC_DIR);
7290                 thinkpad_acpi_module_exit();
7291                 return -ENODEV;
7292         }
7293         proc_dir->owner = THIS_MODULE;
7294
7295         ret = platform_driver_register(&tpacpi_pdriver);
7296         if (ret) {
7297                 printk(TPACPI_ERR
7298                        "unable to register main platform driver\n");
7299                 thinkpad_acpi_module_exit();
7300                 return ret;
7301         }
7302         tp_features.platform_drv_registered = 1;
7303
7304         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
7305         if (ret) {
7306                 printk(TPACPI_ERR
7307                        "unable to register hwmon platform driver\n");
7308                 thinkpad_acpi_module_exit();
7309                 return ret;
7310         }
7311         tp_features.sensors_pdrv_registered = 1;
7312
7313         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
7314         if (!ret) {
7315                 tp_features.platform_drv_attrs_registered = 1;
7316                 ret = tpacpi_create_driver_attributes(
7317                                         &tpacpi_hwmon_pdriver.driver);
7318         }
7319         if (ret) {
7320                 printk(TPACPI_ERR
7321                        "unable to create sysfs driver attributes\n");
7322                 thinkpad_acpi_module_exit();
7323                 return ret;
7324         }
7325         tp_features.sensors_pdrv_attrs_registered = 1;
7326
7327
7328         /* Device initialization */
7329         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
7330                                                         NULL, 0);
7331         if (IS_ERR(tpacpi_pdev)) {
7332                 ret = PTR_ERR(tpacpi_pdev);
7333                 tpacpi_pdev = NULL;
7334                 printk(TPACPI_ERR "unable to register platform device\n");
7335                 thinkpad_acpi_module_exit();
7336                 return ret;
7337         }
7338         tpacpi_sensors_pdev = platform_device_register_simple(
7339                                                 TPACPI_HWMON_DRVR_NAME,
7340                                                 -1, NULL, 0);
7341         if (IS_ERR(tpacpi_sensors_pdev)) {
7342                 ret = PTR_ERR(tpacpi_sensors_pdev);
7343                 tpacpi_sensors_pdev = NULL;
7344                 printk(TPACPI_ERR
7345                        "unable to register hwmon platform device\n");
7346                 thinkpad_acpi_module_exit();
7347                 return ret;
7348         }
7349         ret = device_create_file(&tpacpi_sensors_pdev->dev,
7350                                  &dev_attr_thinkpad_acpi_pdev_name);
7351         if (ret) {
7352                 printk(TPACPI_ERR
7353                        "unable to create sysfs hwmon device attributes\n");
7354                 thinkpad_acpi_module_exit();
7355                 return ret;
7356         }
7357         tp_features.sensors_pdev_attrs_registered = 1;
7358         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
7359         if (IS_ERR(tpacpi_hwmon)) {
7360                 ret = PTR_ERR(tpacpi_hwmon);
7361                 tpacpi_hwmon = NULL;
7362                 printk(TPACPI_ERR "unable to register hwmon device\n");
7363                 thinkpad_acpi_module_exit();
7364                 return ret;
7365         }
7366         mutex_init(&tpacpi_inputdev_send_mutex);
7367         tpacpi_inputdev = input_allocate_device();
7368         if (!tpacpi_inputdev) {
7369                 printk(TPACPI_ERR "unable to allocate input device\n");
7370                 thinkpad_acpi_module_exit();
7371                 return -ENOMEM;
7372         } else {
7373                 /* Prepare input device, but don't register */
7374                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
7375                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
7376                 tpacpi_inputdev->id.bustype = BUS_HOST;
7377                 tpacpi_inputdev->id.vendor = (thinkpad_id.vendor) ?
7378                                                 thinkpad_id.vendor :
7379                                                 PCI_VENDOR_ID_IBM;
7380                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
7381                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
7382         }
7383         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
7384                 ret = ibm_init(&ibms_init[i]);
7385                 if (ret >= 0 && *ibms_init[i].param)
7386                         ret = ibms_init[i].data->write(ibms_init[i].param);
7387                 if (ret < 0) {
7388                         thinkpad_acpi_module_exit();
7389                         return ret;
7390                 }
7391         }
7392         ret = input_register_device(tpacpi_inputdev);
7393         if (ret < 0) {
7394                 printk(TPACPI_ERR "unable to register input device\n");
7395                 thinkpad_acpi_module_exit();
7396                 return ret;
7397         } else {
7398                 tp_features.input_device_registered = 1;
7399         }
7400
7401         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
7402         return 0;
7403 }
7404
7405 /* Please remove this in year 2009 */
7406 MODULE_ALIAS("ibm_acpi");
7407
7408 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
7409
7410 /*
7411  * DMI matching for module autoloading
7412  *
7413  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
7414  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
7415  *
7416  * Only models listed in thinkwiki will be supported, so add yours
7417  * if it is not there yet.
7418  */
7419 #define IBM_BIOS_MODULE_ALIAS(__type) \
7420         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW")
7421
7422 /* Non-ancient thinkpads */
7423 MODULE_ALIAS("dmi:bvnIBM:*:svnIBM:*:pvrThinkPad*:rvnIBM:*");
7424 MODULE_ALIAS("dmi:bvnLENOVO:*:svnLENOVO:*:pvrThinkPad*:rvnLENOVO:*");
7425
7426 /* Ancient thinkpad BIOSes have to be identified by
7427  * BIOS type or model number, and there are far less
7428  * BIOS types than model numbers... */
7429 IBM_BIOS_MODULE_ALIAS("I[B,D,H,I,M,N,O,T,W,V,Y,Z]");
7430 IBM_BIOS_MODULE_ALIAS("1[0,3,6,8,A-G,I,K,M-P,S,T]");
7431 IBM_BIOS_MODULE_ALIAS("K[U,X-Z]");
7432
7433 MODULE_AUTHOR("Borislav Deianov, Henrique de Moraes Holschuh");
7434 MODULE_DESCRIPTION(TPACPI_DESC);
7435 MODULE_VERSION(TPACPI_VERSION);
7436 MODULE_LICENSE("GPL");
7437
7438 module_init(thinkpad_acpi_module_init);
7439 module_exit(thinkpad_acpi_module_exit);