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