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