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