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