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