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